94%
lib94%
rules96%
checker.js
var vowFs = require('vow-fs');
var Vow = require('vow');
var StringChecker = require('./string-checker');
var extractJs = require('./extract-js');
var utils = require('util');
var NodeConfiguration = require('./config/node-configuration');
/**
* Starts Code Style checking process.
*
* @name Checker
* @see StringChecker constructor
*/
Function (anonymous_1)
✓ Was called
var Checker = function() {···
StringChecker.apply(this, arguments);
};
var Checker = function() {
StringChecker.apply(this, arguments);
};
utils.inherits(Checker, StringChecker);
/**
* Loads configuration from JS Object. Activates and configures required rules.
*
* @param {Object} config
*/
Function (anonymous_2)
✓ Was called
Checker.prototype.configure = function(config) {···
StringChecker.prototype.configure.call(this, config);
};
Checker.prototype.configure = function(config) {
StringChecker.prototype.configure.call(this, config);
};
/**
* Execute checker depending on config value either checks or checks and fixes
*
* @see Checker#checkPath/Checker#fixPath
*/
Function (anonymous_3)
✓ Was called
Checker.prototype.execute = function() {···
var method = this._configuration.getFix() === true ? this.fixPath : this.checkPath;

return method.apply(this, arguments);
};
Checker.prototype.execute = function() {
Branch ConditionalExpression
✓ Positive was returned (? ...)
var method = this._configuration.getFix() === true ? this.fixPath : this.checkPath;
✓ Negative was returned (: ...)
var method = this._configuration.getFix() === true ? this.fixPath : this.checkPath;
var method = this._configuration.getFix() === true ? this.fixPath : this.checkPath;
return method.apply(this, arguments);
};
/**
* Checks single file.
*
* @param {String} path
* @returns {Promise.<Errors>}
*/
Function (anonymous_4)
✓ Was called
Checker.prototype.checkFile = function(path) {···
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}

return vowFs.read(path, 'utf8').then(function(data) {
return this.checkString(data, path);
}, this);
};
Checker.prototype.checkFile = function(path) {
Branch IfStatement
✓ Positive was executed (if)
if (this._configuration.isFileExcluded(path)) {···
return Vow.resolve(null);
}
✓ Negative was executed (else)
}···

return vowFs.read(path, 'utf8').then(function(data) {
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}
Function (anonymous_5)
✓ Was called
return vowFs.read(path, 'utf8').then(function(data) {···
return this.checkString(data, path);
}, this);
return vowFs.read(path, 'utf8').then(function(data) {
return this.checkString(data, path);
}, this);
};
/**
* Fixes single file.
*
* @param {String} path
* @returns {Promise.<Errors>}
*/
Function (anonymous_6)
✓ Was called
Checker.prototype.fixFile = function(path) {···
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}

return vowFs.read(path, 'utf8').then(function(data) {
var result = this.fixString(data, path);
return vowFs.write(path, result.output).then(function() {
return result.errors;
});
}, this);
};
Checker.prototype.fixFile = function(path) {
Branch IfStatement
✓ Positive was executed (if)
if (this._configuration.isFileExcluded(path)) {···
return Vow.resolve(null);
}
✓ Negative was executed (else)
}···

return vowFs.read(path, 'utf8').then(function(data) {
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}
Function (anonymous_7)
✓ Was called
return vowFs.read(path, 'utf8').then(function(data) {···
var result = this.fixString(data, path);
return vowFs.write(path, result.output).then(function() {
return result.errors;
});
}, this);
return vowFs.read(path, 'utf8').then(function(data) {
var result = this.fixString(data, path);
Function (anonymous_8)
✓ Was called
return vowFs.write(path, result.output).then(function() {···
return result.errors;
});
return vowFs.write(path, result.output).then(function() {
return result.errors;
});
}, this);
};
/**
* Extract JavaScript from file.
*
* @param {String} path
* @returns {Promise.<Errors>}
*/
Function (anonymous_9)
✓ Was called
Checker.prototype.extractFile = function(path) {···
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}

if (!this._configuration.shouldExtractFile(path)) {
return Vow.resolve(null);
}

return vowFs.read(path, 'utf8').then(function(data) {
var result = extractJs(path, data);

result.sources.forEach(function(script) {
this.checkString(script.source, path).getErrorList().forEach(function(error) {
error.line += script.line;
error.column += script.offset;
result.addError(error);
});
}, this);

return result.errors;
}, this);
};
Checker.prototype.extractFile = function(path) {
Branch IfStatement
✓ Positive was executed (if)
if (this._configuration.isFileExcluded(path)) {···
return Vow.resolve(null);
}
✓ Negative was executed (else)
}···

if (!this._configuration.shouldExtractFile(path)) {
if (this._configuration.isFileExcluded(path)) {
return Vow.resolve(null);
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._configuration.shouldExtractFile(path)) {···
return Vow.resolve(null);
}
✓ Negative was executed (else)
}···

return vowFs.read(path, 'utf8').then(function(data) {
if (!this._configuration.shouldExtractFile(path)) {
return Vow.resolve(null);
}
Function (anonymous_10)
✓ Was called
return vowFs.read(path, 'utf8').then(function(data) {···
var result = extractJs(path, data);

result.sources.forEach(function(script) {
this.checkString(script.source, path).getErrorList().forEach(function(error) {
error.line += script.line;
error.column += script.offset;
result.addError(error);
});
}, this);

return result.errors;
}, this);
return vowFs.read(path, 'utf8').then(function(data) {
var result = extractJs(path, data);
Function (anonymous_11)
✓ Was called
result.sources.forEach(function(script) {···
this.checkString(script.source, path).getErrorList().forEach(function(error) {
error.line += script.line;
error.column += script.offset;
result.addError(error);
});
}, this);
result.sources.forEach(function(script) {
Function (anonymous_12)
✓ Was called
this.checkString(script.source, path).getErrorList().forEach(function(error) {···
error.line += script.line;
error.column += script.offset;
result.addError(error);
});
this.checkString(script.source, path).getErrorList().forEach(function(error) {
error.line += script.line;
error.column += script.offset;
result.addError(error);
});
}, this);
return result.errors;
}, this);
};
/**
* Checks directory recursively.
*
* @param {String} path
* @returns {Promise.<Error[]>}
*/
Function (anonymous_13)
✓ Was called
Checker.prototype.checkDirectory = function(path) {···
return this._processDirectory(path, this.checkFile.bind(this));
};
Checker.prototype.checkDirectory = function(path) {
return this._processDirectory(path, this.checkFile.bind(this));
};
/**
* Checks directory or file.
*
* @param {String} path
* @returns {Promise.<Error[]>}
*/
Function (anonymous_14)
✓ Was called
Checker.prototype.checkPath = function(path) {···
return this._processPath(path, this.checkFile.bind(this));
};
Checker.prototype.checkPath = function(path) {
return this._processPath(path, this.checkFile.bind(this));
};
/**
* Fixes directory or file.
*
* @param {String} path
* @returns {Promise.<Error[]>}
*/
Function (anonymous_15)
✓ Was called
Checker.prototype.fixPath = function(path) {···
return this._processPath(path, this.fixFile.bind(this));
};
Checker.prototype.fixPath = function(path) {
return this._processPath(path, this.fixFile.bind(this));
};
/**
* Processes directory recursively.
*
* @param {String} path
* @param {Function} fileHandler
* @returns {Promise.<Error[]>}
*/
Function (anonymous_16)
✓ Was called
Checker.prototype._processDirectory = function(path, fileHandler) {···
return vowFs.listDir(path).then(function(filenames) {
return Vow.all(filenames.map(function(filename) {
var fullname = path + '/' + filename;

if (this._configuration.isFileExcluded(fullname)) {
return [];
}

return vowFs.stat(fullname).then(function(stat) {
if (stat.isDirectory()) {
return this._processDirectory(fullname, fileHandler);
}

if (!this._configuration.hasCorrectExtension(fullname)) {
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}

return this.extractFile(fullname);
}

return fileHandler(fullname);
}, this);
}, this)).then(function(results) {
return [].concat.apply([], results);
});
}, this);
};
Checker.prototype._processDirectory = function(path, fileHandler) {
Function (anonymous_17)
✓ Was called
return vowFs.listDir(path).then(function(filenames) {···
return Vow.all(filenames.map(function(filename) {
var fullname = path + '/' + filename;

if (this._configuration.isFileExcluded(fullname)) {
return [];
}

return vowFs.stat(fullname).then(function(stat) {
if (stat.isDirectory()) {
return this._processDirectory(fullname, fileHandler);
}

if (!this._configuration.hasCorrectExtension(fullname)) {
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}

return this.extractFile(fullname);
}

return fileHandler(fullname);
}, this);
}, this)).then(function(results) {
return [].concat.apply([], results);
});
}, this);
return vowFs.listDir(path).then(function(filenames) {
Function (anonymous_18)
✓ Was called
return Vow.all(filenames.map(function(filename) {···
var fullname = path + '/' + filename;

if (this._configuration.isFileExcluded(fullname)) {
return [];
}

return vowFs.stat(fullname).then(function(stat) {
if (stat.isDirectory()) {
return this._processDirectory(fullname, fileHandler);
}

if (!this._configuration.hasCorrectExtension(fullname)) {
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}

return this.extractFile(fullname);
}

return fileHandler(fullname);
}, this);
}, this)).then(function(results) {
return Vow.all(filenames.map(function(filename) {
var fullname = path + '/' + filename;
Branch IfStatement
✓ Positive was executed (if)
if (this._configuration.isFileExcluded(fullname)) {···
return [];
}
✓ Negative was executed (else)
}···

return vowFs.stat(fullname).then(function(stat) {
if (this._configuration.isFileExcluded(fullname)) {
return [];
}
Function (anonymous_19)
✓ Was called
return vowFs.stat(fullname).then(function(stat) {···
if (stat.isDirectory()) {
return this._processDirectory(fullname, fileHandler);
}

if (!this._configuration.hasCorrectExtension(fullname)) {
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}

return this.extractFile(fullname);
}

return fileHandler(fullname);
}, this);
return vowFs.stat(fullname).then(function(stat) {
Branch IfStatement
✓ Positive was executed (if)
if (stat.isDirectory()) {···
return this._processDirectory(fullname, fileHandler);
}
✓ Negative was executed (else)
}···

if (!this._configuration.hasCorrectExtension(fullname)) {
if (stat.isDirectory()) {
return this._processDirectory(fullname, fileHandler);
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._configuration.hasCorrectExtension(fullname)) {···
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}

return this.extractFile(fullname);
}
✓ Negative was executed (else)
}···

return fileHandler(fullname);
if (!this._configuration.hasCorrectExtension(fullname)) {
Branch IfStatement
✓ Positive was executed (if)
if (!this._configuration.shouldExtractFile(fullname)) {···
return [];
}
✓ Negative was executed (else)
}···

return this.extractFile(fullname);
if (!this._configuration.shouldExtractFile(fullname)) {
return [];
}
return this.extractFile(fullname);
}
return fileHandler(fullname);
}, this);
Function (anonymous_20)
✓ Was called
}, this)).then(function(results) {···
return [].concat.apply([], results);
});
}, this)).then(function(results) {
return [].concat.apply([], results);
});
}, this);
};
/**
* Processes directory or file.
*
* @param {String} path
* @param {Function} fileHandler
* @returns {Promise.<Error[]>}
*/
Function (anonymous_21)
✓ Was called
Checker.prototype._processPath = function(path, fileHandler) {···
path = path.replace(/\/$/, '');

return vowFs.exists(path).then(function(exists) {
if (!exists) {
throw new Error('Path ' + path + ' was not found.');
}

return vowFs.stat(path).then(function(stat) {
if (stat.isDirectory()) {
return this._processDirectory(path, fileHandler);
}

return fileHandler(path).then(function(errors) {
if (errors) {
return [errors];
}

return [];
});
}, this);
}, this);
};
Checker.prototype._processPath = function(path, fileHandler) {
path = path.replace(/\/$/, '');
Function (anonymous_22)
✓ Was called
return vowFs.exists(path).then(function(exists) {···
if (!exists) {
throw new Error('Path ' + path + ' was not found.');
}

return vowFs.stat(path).then(function(stat) {
if (stat.isDirectory()) {
return this._processDirectory(path, fileHandler);
}

return fileHandler(path).then(function(errors) {
if (errors) {
return [errors];
}

return [];
});
}, this);
}, this);
return vowFs.exists(path).then(function(exists) {
Branch IfStatement
✓ Positive was executed (if)
if (!exists) {···
throw new Error('Path ' + path + ' was not found.');
}
✓ Negative was executed (else)
}···

return vowFs.stat(path).then(function(stat) {
if (!exists) {
throw new Error('Path ' + path + ' was not found.');
}
Function (anonymous_23)
✓ Was called
return vowFs.stat(path).then(function(stat) {···
if (stat.isDirectory()) {
return this._processDirectory(path, fileHandler);
}

return fileHandler(path).then(function(errors) {
if (errors) {
return [errors];
}

return [];
});
}, this);
return vowFs.stat(path).then(function(stat) {
Branch IfStatement
✓ Positive was executed (if)
if (stat.isDirectory()) {···
return this._processDirectory(path, fileHandler);
}
✓ Negative was executed (else)
}···

return fileHandler(path).then(function(errors) {
if (stat.isDirectory()) {
return this._processDirectory(path, fileHandler);
}
Function (anonymous_24)
✓ Was called
return fileHandler(path).then(function(errors) {···
if (errors) {
return [errors];
}

return [];
});
return fileHandler(path).then(function(errors) {
Branch IfStatement
✓ Positive was executed (if)
if (errors) {···
return [errors];
}
✓ Negative was executed (else)
}···

return [];
if (errors) {
return [errors];
}
return [];
});
}, this);
}, this);
};
/**
* Checks stdin for input
*
* @returns {Promise}
*/
Function (anonymous_25)
✓ Was called
Checker.prototype.checkStdin = function() {···
return this._processStdin(this.checkString.bind(this));
};
Checker.prototype.checkStdin = function() {
return this._processStdin(this.checkString.bind(this));
};
/**
* Fixes stdin input
*
* @returns {Promise}
*/
Function (anonymous_26)
✓ Was called
Checker.prototype.fixStdin = function() {···
return this._processStdin(this.fixString.bind(this));
};
Checker.prototype.fixStdin = function() {
return this._processStdin(this.fixString.bind(this));
};
/**
*
* @param {Function} stdinHandler
* @returns {Promise}
*/
Function (anonymous_27)
✓ Was called
Checker.prototype._processStdin = function(stdinHandler) {···
var stdInput = [];
var deferred = Vow.defer();

process.stdin.setEncoding('utf8');

process.stdin.on('data', function(chunk) {
stdInput.push(chunk);
});

process.stdin.on('end', function() {
deferred.resolve(stdinHandler(stdInput.join('')));
});

return deferred.promise();
};
Checker.prototype._processStdin = function(stdinHandler) {
var stdInput = [];
var deferred = Vow.defer();
process.stdin.setEncoding('utf8');
Function (anonymous_28)
✓ Was called
process.stdin.on('data', function(chunk) {···
stdInput.push(chunk);
});
process.stdin.on('data', function(chunk) {
stdInput.push(chunk);
});
Function (anonymous_29)
✓ Was called
process.stdin.on('end', function() {···
deferred.resolve(stdinHandler(stdInput.join('')));
});
process.stdin.on('end', function() {
deferred.resolve(stdinHandler(stdInput.join('')));
});
return deferred.promise();
};
/**
* Returns new configuration instance.
*
* @protected
* @returns {NodeConfiguration}
*/
Function (anonymous_30)
✓ Was called
Checker.prototype._createConfiguration = function() {···
return new NodeConfiguration();
};
Checker.prototype._createConfiguration = function() {
return new NodeConfiguration();
};
module.exports = Checker;
string-checker.js
var Errors = require('./errors');
var JsFile = require('./js-file');
var TokenIndex = require('./token-index');
var Configuration = require('./config/configuration');
var MAX_FIX_ATTEMPTS = 5;
Function getInternalErrorMessage
✓ Was called
function getInternalErrorMessage(rule, e) {···
return 'Error running rule ' + rule + ': ' +
'This is an issue with JSCS and not your codebase.\n' +
'Please file an issue (with the stack trace below) at: ' +
'https://github.com/jscs-dev/node-jscs/issues/new\n' + e.stack;
}
function getInternalErrorMessage(rule, e) {
return 'Error running rule ' + rule + ': ' +
'This is an issue with JSCS and not your codebase.\n' +
'Please file an issue (with the stack trace below) at: ' +
'https://github.com/jscs-dev/node-jscs/issues/new\n' + e.stack;
}
/**
* Starts Code Style checking process.
*
* @name StringChecker
*/
Function (anonymous_32)
✓ Was called
var StringChecker = function() {···
this._configuredRules = [];

this._errorsFound = 0;
this._maxErrorsExceeded = false;

this._configuration = this._createConfiguration();
this._configuration.registerDefaultPresets();
};
var StringChecker = function() {
this._configuredRules = [];
this._errorsFound = 0;
this._maxErrorsExceeded = false;
this._configuration = this._createConfiguration();
this._configuration.registerDefaultPresets();
};
StringChecker.prototype = {
/**
* Registers single Code Style checking rule.
*
* @param {Rule} rule
*/
Function (anonymous_33)
✓ Was called
registerRule: function(rule) {···
this._configuration.registerRule(rule);
},
registerRule: function(rule) {
this._configuration.registerRule(rule);
},
/**
* Registers built-in Code Style checking rules.
*/
Function (anonymous_34)
✓ Was called
registerDefaultRules: function() {···
this._configuration.registerDefaultRules();
},
registerDefaultRules: function() {
this._configuration.registerDefaultRules();
},
/**
* Get processed config.
*
* @return {Object}
*/
Function (anonymous_35)
✗ Was not called
getProcessedConfig: function() {···
return this._configuration.getProcessedConfig();
},
getProcessedConfig: function() {
return this._configuration.getProcessedConfig();
},
/**
* Loads configuration from JS Object. Activates and configures required rules.
*
* @param {Object} config
*/
Function (anonymous_36)
✓ Was called
configure: function(config) {···
this._configuration.load(config);

this._configuredRules = this._configuration.getConfiguredRules();
this._maxErrors = this._configuration.getMaxErrors();
},
configure: function(config) {
this._configuration.load(config);
this._configuredRules = this._configuration.getConfiguredRules();
this._maxErrors = this._configuration.getMaxErrors();
},
/**
* Checks file provided with a string.
*
* @param {String} source
* @param {String} [filename='input']
* @returns {Errors}
*/
Function (anonymous_37)
✓ Was called
checkString: function(source, filename) {···
filename = filename || 'input';

var file = this._createJsFileInstance(filename, source);

var errors = new Errors(file);

file.getParseErrors().forEach(function(parseError) {
if (!this._maxErrorsExceeded) {
this._addParseError(errors, parseError, file);
}
}, this);

if (!file._program || file._program.firstChild.type === 'EOF') {
return errors;
}

this._checkJsFile(file, errors);

return errors;
},
checkString: function(source, filename) {
Branch LogicalExpression
✓ Was returned
filename = filename || 'input';
✓ Was returned
filename = filename || 'input';
filename = filename || 'input';
var file = this._createJsFileInstance(filename, source);
var errors = new Errors(file);
Function (anonymous_38)
✓ Was called
file.getParseErrors().forEach(function(parseError) {···
if (!this._maxErrorsExceeded) {
this._addParseError(errors, parseError, file);
}
}, this);
file.getParseErrors().forEach(function(parseError) {
Branch IfStatement
✓ Positive was executed (if)
if (!this._maxErrorsExceeded) {···
this._addParseError(errors, parseError, file);
}
✗ Negative was not executed (else)
}···
}, this);
if (!this._maxErrorsExceeded) {
this._addParseError(errors, parseError, file);
}
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (!file._program || file._program.firstChild.type === 'EOF') {···
return errors;
}
✓ Negative was executed (else)
}···

this._checkJsFile(file, errors);
Branch LogicalExpression
✓ Was returned
if (!file._program || file._program.firstChild.type === 'EOF') {
✗ Was not returned
if (!file._program || file._program.firstChild.type === 'EOF') {
if (!file._program || file._program.firstChild.type === 'EOF') {
return errors;
}
this._checkJsFile(file, errors);
return errors;
},
/**
* Apply fix for common errors.
*
* @param {Error} error
* @return {Boolean} whether the correction was carried out
* @private
*/
Function (anonymous_39)
✓ Was called
_fixCommonError: function(error) {···
if (error.fix) {
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
error.fix();
}

return !!error.fixed;
},
_fixCommonError: function(error) {
Branch IfStatement
✓ Positive was executed (if)
if (error.fix) {···
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
error.fix();
}
✓ Negative was executed (else)
}···

return !!error.fixed;
if (error.fix) {
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
error.fix();
}
return !!error.fixed;
},
/**
* Apply fix for specific error.
*
* @param {JsFile} file
* @param {Error} error
* @return {Boolean} whether the correction was carried out
* @private
*/
Function (anonymous_40)
✓ Was called
_fixSpecificError: function(file, error) {···
var configuration = this.getConfiguration();
var instance = configuration.getConfiguredRule(error.rule);

if (instance && instance._fix) {
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
instance._fix(file, error);
}

return !!error.fixed;
},
_fixSpecificError: function(file, error) {
var configuration = this.getConfiguration();
var instance = configuration.getConfiguredRule(error.rule);
Branch IfStatement
✓ Positive was executed (if)
if (instance && instance._fix) {···
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
instance._fix(file, error);
}
✓ Negative was executed (else)
}···

return !!error.fixed;
Branch LogicalExpression
✓ Was returned
if (instance && instance._fix) {
✗ Was not returned
if (instance && instance._fix) {
if (instance && instance._fix) {
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
instance._fix(file, error);
}
return !!error.fixed;
},
/**
* Apply specific and common fixes.
*
* @param {JsFile} file
* @param {Errors} errors
* @protected
*/
Function (anonymous_41)
✓ Was called
_fixJsFile: function(file, errors) {···
errors.getErrorList().forEach(function(error) {
if (error.fixed) {
return;
}

try {
// Try to apply fixes for common errors
var isFixed = this._fixCommonError(error);

// Apply specific fix
if (!isFixed) {
this._fixSpecificError(file, error);
}
} catch (e) {
error.fixed = false;
errors.add(
getInternalErrorMessage(error.rule, e),
file.getProgram()
);
}
}, this);
},
_fixJsFile: function(file, errors) {
Function (anonymous_42)
✓ Was called
errors.getErrorList().forEach(function(error) {···
if (error.fixed) {
return;
}

try {
// Try to apply fixes for common errors
var isFixed = this._fixCommonError(error);

// Apply specific fix
if (!isFixed) {
this._fixSpecificError(file, error);
}
} catch (e) {
error.fixed = false;
errors.add(
getInternalErrorMessage(error.rule, e),
file.getProgram()
);
}
}, this);
errors.getErrorList().forEach(function(error) {
Branch IfStatement
✗ Positive was not executed (if)
if (error.fixed) {···
return;
}
✓ Negative was executed (else)
}···

try {
if (error.fixed) {
return;
}
try {
// Try to apply fixes for common errors
var isFixed = this._fixCommonError(error);
// Apply specific fix
Branch IfStatement
✓ Positive was executed (if)
if (!isFixed) {···
this._fixSpecificError(file, error);
}
✓ Negative was executed (else)
}···
} catch (e) {
if (!isFixed) {
this._fixSpecificError(file, error);
}
} catch (e) {
error.fixed = false;
errors.add(
getInternalErrorMessage(error.rule, e),
file.getProgram()
);
}
}, this);
},
/**
* Checks a file specified using JsFile instance.
* Fills Errors instance with validation errors.
*
* @param {JsFile} file
* @param {Errors} errors
* @protected
*/
Function (anonymous_43)
✓ Was called
_checkJsFile: function(file, errors) {···
if (this._maxErrorsExceeded) {
return;
}

var errorFilter = this._configuration.getErrorFilter();

this._configuredRules.forEach(function(rule) {
errors.setCurrentRule(rule.getOptionName());

try {
rule.check(file, errors);
} catch (e) {
errors.setCurrentRule('internalError');
errors.add(getInternalErrorMessage(rule.getOptionName(), e), file.getProgram());
}
}, this);

this._configuration.getUnsupportedRuleNames().forEach(function(rulename) {
errors.add('Unsupported rule: ' + rulename, file.getProgram());
});

var program = file.getProgram();
var tokenIndex = new TokenIndex(program.getFirstToken());
errors.calculateErrorLocations(tokenIndex);
errors.filter(function(error) {
if (error.element) {
return tokenIndex.isRuleEnabled(error.rule, error.element);
} else {
return true;
}
});

// sort errors list to show errors as they appear in source
errors.getErrorList().sort(function(a, b) {
return (a.line - b.line) || (a.column - b.column);
});

if (errorFilter) {
errors.filter(errorFilter);
}

if (this.maxErrorsEnabled()) {
if (this._maxErrors === -1 || this._maxErrors === null) {
this._maxErrorsExceeded = false;

} else {
this._maxErrorsExceeded = this._errorsFound + errors.getErrorCount() > this._maxErrors;
errors.stripErrorList(Math.max(0, this._maxErrors - this._errorsFound));
}
}

this._errorsFound += errors.getErrorCount();
},
_checkJsFile: function(file, errors) {
Branch IfStatement
✓ Positive was executed (if)
if (this._maxErrorsExceeded) {···
return;
}
✓ Negative was executed (else)
}···

var errorFilter = this._configuration.getErrorFilter();
if (this._maxErrorsExceeded) {
return;
}
var errorFilter = this._configuration.getErrorFilter();
Function (anonymous_44)
✓ Was called
this._configuredRules.forEach(function(rule) {···
errors.setCurrentRule(rule.getOptionName());

try {
rule.check(file, errors);
} catch (e) {
errors.setCurrentRule('internalError');
errors.add(getInternalErrorMessage(rule.getOptionName(), e), file.getProgram());
}
}, this);
this._configuredRules.forEach(function(rule) {
errors.setCurrentRule(rule.getOptionName());
try {
rule.check(file, errors);
} catch (e) {
errors.setCurrentRule('internalError');
errors.add(getInternalErrorMessage(rule.getOptionName(), e), file.getProgram());
}
}, this);
Function (anonymous_45)
✓ Was called
this._configuration.getUnsupportedRuleNames().forEach(function(rulename) {···
errors.add('Unsupported rule: ' + rulename, file.getProgram());
});
this._configuration.getUnsupportedRuleNames().forEach(function(rulename) {
errors.add('Unsupported rule: ' + rulename, file.getProgram());
});
var program = file.getProgram();
var tokenIndex = new TokenIndex(program.getFirstToken());
errors.calculateErrorLocations(tokenIndex);
Function (anonymous_46)
✓ Was called
errors.filter(function(error) {···
if (error.element) {
return tokenIndex.isRuleEnabled(error.rule, error.element);
} else {
return true;
}
});
errors.filter(function(error) {
Branch IfStatement
✓ Positive was executed (if)
if (error.element) {···
return tokenIndex.isRuleEnabled(error.rule, error.element);
} else {
✓ Negative was executed (else)
} else {···
return true;
}
if (error.element) {
return tokenIndex.isRuleEnabled(error.rule, error.element);
} else {
return true;
}
});
// sort errors list to show errors as they appear in source
Function (anonymous_47)
✓ Was called
errors.getErrorList().sort(function(a, b) {···
return (a.line - b.line) || (a.column - b.column);
});
errors.getErrorList().sort(function(a, b) {
Branch LogicalExpression
✓ Was returned
return (a.line - b.line) || (a.column - b.column);
✓ Was returned
return (a.line - b.line) || (a.column - b.column);
return (a.line - b.line) || (a.column - b.column);
});
Branch IfStatement
✓ Positive was executed (if)
if (errorFilter) {···
errors.filter(errorFilter);
}
✓ Negative was executed (else)
}···

if (this.maxErrorsEnabled()) {
if (errorFilter) {
errors.filter(errorFilter);
}
Branch IfStatement
✓ Positive was executed (if)
if (this.maxErrorsEnabled()) {···
if (this._maxErrors === -1 || this._maxErrors === null) {
this._maxErrorsExceeded = false;

} else {
this._maxErrorsExceeded = this._errorsFound + errors.getErrorCount() > this._maxErrors;
errors.stripErrorList(Math.max(0, this._maxErrors - this._errorsFound));
}
}
✓ Negative was executed (else)
}···

this._errorsFound += errors.getErrorCount();
if (this.maxErrorsEnabled()) {
Branch IfStatement
✗ Positive was not executed (if)
if (this._maxErrors === -1 || this._maxErrors === null) {···
this._maxErrorsExceeded = false;

} else {
✓ Negative was executed (else)
} else {···
this._maxErrorsExceeded = this._errorsFound + errors.getErrorCount() > this._maxErrors;
errors.stripErrorList(Math.max(0, this._maxErrors - this._errorsFound));
}
Branch LogicalExpression
✓ Was returned
if (this._maxErrors === -1 || this._maxErrors === null) {
✗ Was not returned
if (this._maxErrors === -1 || this._maxErrors === null) {
if (this._maxErrors === -1 || this._maxErrors === null) {
this._maxErrorsExceeded = false;
} else {
this._maxErrorsExceeded = this._errorsFound + errors.getErrorCount() > this._maxErrors;
errors.stripErrorList(Math.max(0, this._maxErrors - this._errorsFound));
}
}
this._errorsFound += errors.getErrorCount();
},
/**
* Adds parse error to the error list.
*
* @param {Errors} errors
* @param {Error} parseError
* @param {JsFile} file
* @private
*/
Function (anonymous_48)
✓ Was called
_addParseError: function(errors, parseError, file) {···
if (this._maxErrorsExceeded) {
return;
}

errors.add(parseError, file.getProgram());

if (this.maxErrorsEnabled()) {
this._errorsFound += 1;
this._maxErrorsExceeded = this._errorsFound >= this._maxErrors;
}
},
_addParseError: function(errors, parseError, file) {
Branch IfStatement
✗ Positive was not executed (if)
if (this._maxErrorsExceeded) {···
return;
}
✓ Negative was executed (else)
}···

errors.add(parseError, file.getProgram());
if (this._maxErrorsExceeded) {
return;
}
errors.add(parseError, file.getProgram());
Branch IfStatement
✓ Positive was executed (if)
if (this.maxErrorsEnabled()) {···
this._errorsFound += 1;
this._maxErrorsExceeded = this._errorsFound >= this._maxErrors;
}
✗ Negative was not executed (else)
}···
},
if (this.maxErrorsEnabled()) {
this._errorsFound += 1;
this._maxErrorsExceeded = this._errorsFound >= this._maxErrors;
}
},
/**
* Creates configured JsFile instance.
*
* @param {String} filename
* @param {String} source
* @private
*/
Function (anonymous_49)
✓ Was called
_createJsFileInstance: function(filename, source) {···
return new JsFile({
filename: filename,
source: source,
es3: this._configuration.isES3Enabled()
});
},
_createJsFileInstance: function(filename, source) {
return new JsFile({
filename: filename,
source: source,
es3: this._configuration.isES3Enabled()
});
},
/**
* Checks and fix file provided with a string.
*
* @param {String} source
* @param {String} [filename='input']
* @returns {{output: String, errors: Errors}}
*/
Function (anonymous_50)
✓ Was called
fixString: function(source, filename) {···
filename = filename || 'input';

var file = this._createJsFileInstance(filename, source);
var errors = new Errors(file);

var parseErrors = file.getParseErrors();
if (parseErrors.length > 0) {
parseErrors.forEach(function(parseError) {
this._addParseError(errors, parseError, file);
}, this);

return {output: source, errors: errors};
} else {
var attempt = 0;
do {

// Fill in errors list
this._checkJsFile(file, errors);

// Apply fixes
this._fixJsFile(file, errors);

var hasFixes = errors.getErrorList().some(function(err) {
return err.fixed;
});

if (!hasFixes) {
break;
}

file = this._createJsFileInstance(filename, file.render());
errors = new Errors(file);
attempt++;
} while (attempt < MAX_FIX_ATTEMPTS);

return {output: file.getSource(), errors: errors};
}
},
fixString: function(source, filename) {
Branch LogicalExpression
✓ Was returned
filename = filename || 'input';
✓ Was returned
filename = filename || 'input';
filename = filename || 'input';
var file = this._createJsFileInstance(filename, source);
var errors = new Errors(file);
var parseErrors = file.getParseErrors();
Branch IfStatement
✓ Positive was executed (if)
if (parseErrors.length > 0) {···
parseErrors.forEach(function(parseError) {
this._addParseError(errors, parseError, file);
}, this);

return {output: source, errors: errors};
} else {
✓ Negative was executed (else)
} else {···
var attempt = 0;
do {

// Fill in errors list
this._checkJsFile(file, errors);

// Apply fixes
this._fixJsFile(file, errors);

var hasFixes = errors.getErrorList().some(function(err) {
return err.fixed;
});

if (!hasFixes) {
break;
}

file = this._createJsFileInstance(filename, file.render());
errors = new Errors(file);
attempt++;
} while (attempt < MAX_FIX_ATTEMPTS);

return {output: file.getSource(), errors: errors};
}
if (parseErrors.length > 0) {
Function (anonymous_51)
✓ Was called
parseErrors.forEach(function(parseError) {···
this._addParseError(errors, parseError, file);
}, this);
parseErrors.forEach(function(parseError) {
this._addParseError(errors, parseError, file);
}, this);
return {output: source, errors: errors};
} else {
var attempt = 0;
do {
// Fill in errors list
this._checkJsFile(file, errors);
// Apply fixes
this._fixJsFile(file, errors);
Function (anonymous_52)
✓ Was called
var hasFixes = errors.getErrorList().some(function(err) {···
return err.fixed;
});
var hasFixes = errors.getErrorList().some(function(err) {
return err.fixed;
});
Branch IfStatement
✓ Positive was executed (if)
if (!hasFixes) {···
break;
}
✓ Negative was executed (else)
}···

file = this._createJsFileInstance(filename, file.render());
if (!hasFixes) {
break;
}
file = this._createJsFileInstance(filename, file.render());
errors = new Errors(file);
attempt++;
} while (attempt < MAX_FIX_ATTEMPTS);
return {output: file.getSource(), errors: errors};
}
},
/**
* Returns `true` if max erros limit is enabled.
*
* @returns {Boolean}
*/
Function (anonymous_53)
✓ Was called
maxErrorsEnabled: function() {···
return this._maxErrors !== null && this._maxErrors !== -1;
},
maxErrorsEnabled: function() {
Branch LogicalExpression
✓ Was returned
return this._maxErrors !== null && this._maxErrors !== -1;
✓ Was returned
return this._maxErrors !== null && this._maxErrors !== -1;
return this._maxErrors !== null && this._maxErrors !== -1;
},
/**
* Returns `true` if error count exceeded `maxErrors` option value.
*
* @returns {Boolean}
*/
Function (anonymous_54)
✓ Was called
maxErrorsExceeded: function() {···
return this._maxErrorsExceeded;
},
maxErrorsExceeded: function() {
return this._maxErrorsExceeded;
},
/**
* Returns new configuration instance.
*
* @protected
* @returns {Configuration}
*/
Function (anonymous_55)
✓ Was called
_createConfiguration: function() {···
return new Configuration();
},
_createConfiguration: function() {
return new Configuration();
},
/**
* Returns current configuration instance.
*
* @returns {Configuration}
*/
Function (anonymous_56)
✓ Was called
getConfiguration: function() {···
return this._configuration;
}
getConfiguration: function() {
return this._configuration;
}
};
module.exports = StringChecker;
errors.js
var chalk = require('chalk');
var TokenAssert = require('./token-assert');
var LINE_SEPARATOR = /\r\n|\r|\n/g;
var EMPTY_POS = {
line: 1,
column: 0
};
/**
* Set of errors for specified file.
*
* @name Errors
* @param {JsFile} file
*/
Function (anonymous_57)
✓ Was called
var Errors = function(file) {···
this._errorList = [];
this._file = file;
this._currentRule = '';

/**
* @type {TokenAssert}
* @public
*/
this.assert = new TokenAssert(file);
this.assert.on('error', this._addError.bind(this));
};
var Errors = function(file) {
this._errorList = [];
this._file = file;
this._currentRule = '';
/**
* @type {TokenAssert}
* @public
*/
this.assert = new TokenAssert(file);
this.assert.on('error', this._addError.bind(this));
};
Errors.prototype = {
/**
* Adds style error to the list
*
* @param {String | Error} message
* @param {cst.types.Element} element
* @param {Number} [offset] relative offset
*/
Function (anonymous_58)
✓ Was called
add: function(message, element, offset) {···
if (message instanceof Error) {
this._addParseError(message);
return;
}

this._addError({
message: message,
element: element,
offset: offset
});
},
add: function(message, element, offset) {
Branch IfStatement
✓ Positive was executed (if)
if (message instanceof Error) {···
this._addParseError(message);
return;
}
✓ Negative was executed (else)
}···

this._addError({
if (message instanceof Error) {
this._addParseError(message);
return;
}
this._addError({
message: message,
element: element,
offset: offset
});
},
/**
* Adds style error to the list
*
* @param {Object} errorInfo
*/
Function (anonymous_59)
✓ Was called
cast: function(errorInfo) {···
this._addError(errorInfo);
},
cast: function(errorInfo) {
this._addError(errorInfo);
},
/**
* Adds parser error to error list.
*
* @param {Object} errorInfo
* @private
*/
Function (anonymous_60)
✓ Was called
_addParseError: function(errorInfo) {···
this._errorList.push({
filename: this._file.getFilename(),
rule: 'parseError',
message: errorInfo.message,
line: errorInfo.loc ? errorInfo.loc.line : 1,
column: errorInfo.loc ? errorInfo.loc.column : 0
});
},
_addParseError: function(errorInfo) {
this._errorList.push({
filename: this._file.getFilename(),
rule: 'parseError',
message: errorInfo.message,
Branch ConditionalExpression
✓ Positive was returned (? ...)
line: errorInfo.loc ? errorInfo.loc.line : 1,
✓ Negative was returned (: ...)
line: errorInfo.loc ? errorInfo.loc.line : 1,
line: errorInfo.loc ? errorInfo.loc.line : 1,
Branch ConditionalExpression
✓ Positive was returned (? ...)
column: errorInfo.loc ? errorInfo.loc.column : 0
✓ Negative was returned (: ...)
column: errorInfo.loc ? errorInfo.loc.column : 0
column: errorInfo.loc ? errorInfo.loc.column : 0
});
},
/**
* Adds error to error list.
*
* @param {Object} errorInfo
* @private
*/
Function (anonymous_61)
✓ Was called
_addError: function(errorInfo) {···
this._errorList.push({
filename: this._file.getFilename(),
rule: this._currentRule,
message: this._prepareMessage(errorInfo),
element: errorInfo.element,
offset: errorInfo.offset,
additional: errorInfo.additional,
fixed: false,
fix: errorInfo.fix
});
},
_addError: function(errorInfo) {
this._errorList.push({
filename: this._file.getFilename(),
rule: this._currentRule,
message: this._prepareMessage(errorInfo),
element: errorInfo.element,
offset: errorInfo.offset,
additional: errorInfo.additional,
fixed: false,
fix: errorInfo.fix
});
},
/**
* Prepare error message.
*
* @param {Object} errorInfo
* @private
*/
Function (anonymous_62)
✓ Was called
_prepareMessage: function(errorInfo) {···
var rule = errorInfo instanceof Error ? 'parseError' : this._currentRule;

if (rule) {
return rule + ': ' + errorInfo.message;
}

return errorInfo.message;
},
_prepareMessage: function(errorInfo) {
Branch ConditionalExpression
✗ Positive was not returned (? ...)
var rule = errorInfo instanceof Error ? 'parseError' : this._currentRule;
✓ Negative was returned (: ...)
var rule = errorInfo instanceof Error ? 'parseError' : this._currentRule;
var rule = errorInfo instanceof Error ? 'parseError' : this._currentRule;
Branch IfStatement
✓ Positive was executed (if)
if (rule) {···
return rule + ': ' + errorInfo.message;
}
✓ Negative was executed (else)
}···

return errorInfo.message;
if (rule) {
return rule + ': ' + errorInfo.message;
}
return errorInfo.message;
},
/**
* Returns style error list.
*
* @returns {Object[]}
*/
Function (anonymous_63)
✓ Was called
getErrorList: function() {···
return this._errorList;
},
getErrorList: function() {
return this._errorList;
},
/**
* Returns filename of file this error list is for.
*
* @returns {String}
*/
Function (anonymous_64)
✓ Was called
getFilename: function() {···
return this._file.getFilename();
},
getFilename: function() {
return this._file.getFilename();
},
/**
* Returns true if no errors are added.
*
* @returns {Boolean}
*/
Function (anonymous_65)
✗ Was not called
isEmpty: function() {···
return this._errorList.length === 0;
},
isEmpty: function() {
return this._errorList.length === 0;
},
/**
* Returns amount of errors added by the rules.
*
* @returns {Number}
*/
Function (anonymous_66)
✗ Was not called
getValidationErrorCount: function() {···
return this._errorList.filter(function(error) {
return error.rule !== 'parseError' && error.rule !== 'internalError';
});
},
getValidationErrorCount: function() {
Function (anonymous_67)
✗ Was not called
return this._errorList.filter(function(error) {···
return error.rule !== 'parseError' && error.rule !== 'internalError';
});
return this._errorList.filter(function(error) {
Branch LogicalExpression
✗ Was not returned
return error.rule !== 'parseError' && error.rule !== 'internalError';
✗ Was not returned
return error.rule !== 'parseError' && error.rule !== 'internalError';
return error.rule !== 'parseError' && error.rule !== 'internalError';
});
},
/**
* Returns amount of errors added by the rules.
*
* @returns {Number}
*/
Function (anonymous_68)
✓ Was called
getErrorCount: function() {···
return this._errorList.length;
},
getErrorCount: function() {
return this._errorList.length;
},
/**
* Strips error list to the specified length.
*
* @param {Number} length
*/
Function (anonymous_69)
✓ Was called
stripErrorList: function(length) {···
this._errorList.splice(length);
},
stripErrorList: function(length) {
this._errorList.splice(length);
},
/**
* Filters out errors based on the supplied filter function
*
* @param {Function} filter
*/
Function (anonymous_70)
✓ Was called
filter: function(filter) {···
this._errorList = this._errorList.filter(filter);
},
filter: function(filter) {
this._errorList = this._errorList.filter(filter);
},
/**
* @param {TokenIndex} tokenIndex
*/
Function (anonymous_71)
✓ Was called
calculateErrorLocations: function(tokenIndex) {···
this._errorList.forEach(function(error) {
var pos = Errors.getPosition(error, tokenIndex);
error.line = pos.line;
error.column = pos.column;
});
},
calculateErrorLocations: function(tokenIndex) {
Function (anonymous_72)
✓ Was called
this._errorList.forEach(function(error) {···
var pos = Errors.getPosition(error, tokenIndex);
error.line = pos.line;
error.column = pos.column;
});
this._errorList.forEach(function(error) {
var pos = Errors.getPosition(error, tokenIndex);
error.line = pos.line;
error.column = pos.column;
});
},
/**
* Formats error for further output.
*
* @param {Object} error
* @param {Boolean} [colorize = false]
* @returns {String}
*/
Function (anonymous_73)
✓ Was called
explainError: function(error, colorize) {···
var lineNumber = error.line - 1;
var lines = this._file.getLines();
var result = [
renderLine(lineNumber, lines[lineNumber], colorize),
renderPointer(error.column, colorize)
];
var i = lineNumber - 1;
var linesAround = 2;
while (i >= 0 && i >= (lineNumber - linesAround)) {
result.unshift(renderLine(i, lines[i], colorize));
i--;
}
i = lineNumber + 1;
while (i < lines.length && i <= (lineNumber + linesAround)) {
result.push(renderLine(i, lines[i], colorize));
i++;
}
result.unshift(formatErrorMessage(error.message, this.getFilename(), colorize));
return result.join('\n');
},
explainError: function(error, colorize) {
var lineNumber = error.line - 1;
var lines = this._file.getLines();
var result = [
renderLine(lineNumber, lines[lineNumber], colorize),
renderPointer(error.column, colorize)
];
var i = lineNumber - 1;
var linesAround = 2;
Branch LogicalExpression
✓ Was returned
while (i >= 0 && i >= (lineNumber - linesAround)) {
✓ Was returned
while (i >= 0 && i >= (lineNumber - linesAround)) {
while (i >= 0 && i >= (lineNumber - linesAround)) {
result.unshift(renderLine(i, lines[i], colorize));
i--;
}
i = lineNumber + 1;
Branch LogicalExpression
✓ Was returned
while (i < lines.length && i <= (lineNumber + linesAround)) {
✓ Was returned
while (i < lines.length && i <= (lineNumber + linesAround)) {
while (i < lines.length && i <= (lineNumber + linesAround)) {
result.push(renderLine(i, lines[i], colorize));
i++;
}
result.unshift(formatErrorMessage(error.message, this.getFilename(), colorize));
return result.join('\n');
},
/**
* Sets the current rule so that errors are aware
* of which rule triggered them.
*
* @param {String} rule
*/
Function (anonymous_74)
✓ Was called
setCurrentRule: function(rule) {···
this._currentRule = rule;
}
setCurrentRule: function(rule) {
this._currentRule = rule;
}
};
/**
* Formats error message header.
*
* @param {String} message
* @param {String} filename
* @param {Boolean} colorize
* @returns {String}
*/
Function formatErrorMessage
✓ Was called
function formatErrorMessage(message, filename, colorize) {···
return (colorize ? chalk.bold(message) : message) +
' at ' +
(colorize ? chalk.green(filename) : filename) + ' :';
}
function formatErrorMessage(message, filename, colorize) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
return (colorize ? chalk.bold(message) : message) +
✓ Negative was returned (: ...)
return (colorize ? chalk.bold(message) : message) +
return (colorize ? chalk.bold(message) : message) +
' at ' +
Branch ConditionalExpression
✓ Positive was returned (? ...)
(colorize ? chalk.green(filename) : filename) + ' :';
✓ Negative was returned (: ...)
(colorize ? chalk.green(filename) : filename) + ' :';
(colorize ? chalk.green(filename) : filename) + ' :';
}
/**
* Simple util for prepending spaces to the string until it fits specified size.
*
* @param {String} s
* @param {Number} len
* @returns {String}
*/
Function prependSpaces
✓ Was called
function prependSpaces(s, len) {···
while (s.length < len) {
s = ' ' + s;
}
return s;
}
function prependSpaces(s, len) {
while (s.length < len) {
s = ' ' + s;
}
return s;
}
/**
* Renders single line of code in style error formatted output.
*
* @param {Number} n line number
* @param {String} line
* @param {Boolean} [colorize = false]
* @returns {String}
*/
Function renderLine
✓ Was called
function renderLine(n, line, colorize) {···
// Convert tabs to spaces, so errors in code lines with tabs as indention symbol
// could be correctly rendered, plus it will provide less verbose output
line = line.replace(/\t/g, ' ');

// "n + 1" to print lines in human way (counted from 1)
var lineNumber = prependSpaces((n + 1).toString(), 5) + ' |';
return ' ' + (colorize ? chalk.grey(lineNumber) : lineNumber) + line;
}
function renderLine(n, line, colorize) {
// Convert tabs to spaces, so errors in code lines with tabs as indention symbol
// could be correctly rendered, plus it will provide less verbose output
line = line.replace(/\t/g, ' ');
// "n + 1" to print lines in human way (counted from 1)
var lineNumber = prependSpaces((n + 1).toString(), 5) + ' |';
Branch ConditionalExpression
✓ Positive was returned (? ...)
return ' ' + (colorize ? chalk.grey(lineNumber) : lineNumber) + line;
✓ Negative was returned (: ...)
return ' ' + (colorize ? chalk.grey(lineNumber) : lineNumber) + line;
return ' ' + (colorize ? chalk.grey(lineNumber) : lineNumber) + line;
}
/**
* Renders pointer:
* ---------------^
*
* @param {Number} column
* @param {Boolean} [colorize = false]
* @returns {String}
*/
Function renderPointer
✓ Was called
function renderPointer(column, colorize) {···
var res = (new Array(column + 9)).join('-') + '^';
return colorize ? chalk.grey(res) : res;
}
function renderPointer(column, colorize) {
var res = (new Array(column + 9)).join('-') + '^';
Branch ConditionalExpression
✓ Positive was returned (? ...)
return colorize ? chalk.grey(res) : res;
✓ Negative was returned (: ...)
return colorize ? chalk.grey(res) : res;
return colorize ? chalk.grey(res) : res;
}
/**
* Get position of the element
*
* @param {Error} [error]
* @param {TokenIndex} [tokenIndex]
* @return {Object}
*/
Function (anonymous_79)
✓ Was called
Errors.getPosition = function(error, tokenIndex) {···
var element = error.element;
var offset = error.offset;
var rule = error.rule;

if (!element) {
return EMPTY_POS;
}

if (offset === undefined) {
// TODO: probably should be generalized
if (rule === 'validateQuoteMarks') {
offset = 0;
} else if (element.getSourceCodeLength() === 1) {
offset = 0;
} else {
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
}
}

var pos = tokenIndex ? tokenIndex.getElementLoc(element) : element.getLoc().start;
if (!pos) {
return EMPTY_POS;
}

if (offset === 0) {
return pos;
}

var newlineCount = element.getNewlineCount();
if (newlineCount > 0) {
var code = element.getSourceCode();
LINE_SEPARATOR.lastIndex = 0;
var lineOffset = 0;
var match;
var previousOffset = 0;
var firstLineColumnOffset = pos.column;
while ((match = LINE_SEPARATOR.exec(code)) !== null) {
var currentOffset = match.index;
if (offset <= currentOffset) {
return {
line: pos.line + lineOffset,
column: firstLineColumnOffset + offset - previousOffset
};
}
previousOffset = currentOffset + match[0].length;
firstLineColumnOffset = 0;
lineOffset++;
}
return {
line: pos.line + newlineCount,
column: offset - previousOffset
};
} else {
return {
line: pos.line,
column: pos.column + offset
};
}
};
Errors.getPosition = function(error, tokenIndex) {
var element = error.element;
var offset = error.offset;
var rule = error.rule;
Branch IfStatement
✗ Positive was not executed (if)
if (!element) {···
return EMPTY_POS;
}
✓ Negative was executed (else)
}···

if (offset === undefined) {
if (!element) {
return EMPTY_POS;
}
Branch IfStatement
✓ Positive was executed (if)
if (offset === undefined) {···
// TODO: probably should be generalized
if (rule === 'validateQuoteMarks') {
offset = 0;
} else if (element.getSourceCodeLength() === 1) {
offset = 0;
} else {
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
}
}
✗ Negative was not executed (else)
}···

var pos = tokenIndex ? tokenIndex.getElementLoc(element) : element.getLoc().start;
if (offset === undefined) {
// TODO: probably should be generalized
Branch IfStatement
✓ Positive was executed (if)
if (rule === 'validateQuoteMarks') {···
offset = 0;
} else if (element.getSourceCodeLength() === 1) {
✓ Negative was executed (else)
} else if (element.getSourceCodeLength() === 1) {···
offset = 0;
} else {
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
}
if (rule === 'validateQuoteMarks') {
offset = 0;
Branch IfStatement
✓ Positive was executed (if)
} else if (element.getSourceCodeLength() === 1) {···
offset = 0;
} else {
✓ Negative was executed (else)
} else {···
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
}
} else if (element.getSourceCodeLength() === 1) {
offset = 0;
} else {
Branch LogicalExpression
✗ Was not returned
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
✓ Was returned
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
Branch LogicalExpression
✓ Was returned
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
✗ Was not returned
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
offset = (element.getNewlineCount() === 0 && Math.ceil(element.getSourceCodeLength() / 2)) || 0;
}
}
Branch ConditionalExpression
✓ Positive was returned (? ...)
var pos = tokenIndex ? tokenIndex.getElementLoc(element) : element.getLoc().start;
✓ Negative was returned (: ...)
var pos = tokenIndex ? tokenIndex.getElementLoc(element) : element.getLoc().start;
var pos = tokenIndex ? tokenIndex.getElementLoc(element) : element.getLoc().start;
Branch IfStatement
✗ Positive was not executed (if)
if (!pos) {···
return EMPTY_POS;
}
✓ Negative was executed (else)
}···

if (offset === 0) {
if (!pos) {
return EMPTY_POS;
}
Branch IfStatement
✓ Positive was executed (if)
if (offset === 0) {···
return pos;
}
✓ Negative was executed (else)
}···

var newlineCount = element.getNewlineCount();
if (offset === 0) {
return pos;
}
var newlineCount = element.getNewlineCount();
Branch IfStatement
✗ Positive was not executed (if)
if (newlineCount > 0) {···
var code = element.getSourceCode();
LINE_SEPARATOR.lastIndex = 0;
var lineOffset = 0;
var match;
var previousOffset = 0;
var firstLineColumnOffset = pos.column;
while ((match = LINE_SEPARATOR.exec(code)) !== null) {
var currentOffset = match.index;
if (offset <= currentOffset) {
return {
line: pos.line + lineOffset,
column: firstLineColumnOffset + offset - previousOffset
};
}
previousOffset = currentOffset + match[0].length;
firstLineColumnOffset = 0;
lineOffset++;
}
return {
line: pos.line + newlineCount,
column: offset - previousOffset
};
} else {
✓ Negative was executed (else)
} else {···
return {
line: pos.line,
column: pos.column + offset
};
}
if (newlineCount > 0) {
var code = element.getSourceCode();
LINE_SEPARATOR.lastIndex = 0;
var lineOffset = 0;
var match;
var previousOffset = 0;
var firstLineColumnOffset = pos.column;
while ((match = LINE_SEPARATOR.exec(code)) !== null) {
var currentOffset = match.index;
Branch IfStatement
✗ Positive was not executed (if)
if (offset <= currentOffset) {···
return {
line: pos.line + lineOffset,
column: firstLineColumnOffset + offset - previousOffset
};
}
✗ Negative was not executed (else)
}···
previousOffset = currentOffset + match[0].length;
if (offset <= currentOffset) {
return {
line: pos.line + lineOffset,
column: firstLineColumnOffset + offset - previousOffset
};
}
previousOffset = currentOffset + match[0].length;
firstLineColumnOffset = 0;
lineOffset++;
}
return {
line: pos.line + newlineCount,
column: offset - previousOffset
};
} else {
return {
line: pos.line,
column: pos.column + offset
};
}
};
module.exports = Errors;
token-assert.js
var utils = require('util');
var EventEmitter = require('events').EventEmitter;
var Token = require('cst').Token;
/**
* Token assertions class.
*
* @name {TokenAssert}
* @param {JsFile} file
*/
Function TokenAssert
✓ Was called
function TokenAssert(file) {···
EventEmitter.call(this);

this._file = file;
}
function TokenAssert(file) {
EventEmitter.call(this);
this._file = file;
}
utils.inherits(TokenAssert, EventEmitter);
/**
* Requires to have whitespace between specified tokens. Ignores newlines.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {String} [options.message]
* @param {Number} [options.spaces] Amount of spaces between tokens.
* @return {Boolean} whether an error was found
*/
Function (anonymous_81)
✓ Was called
TokenAssert.prototype.whitespaceBetween = function(options) {···
options.atLeast = 1;
return this.spacesBetween(options);
};
TokenAssert.prototype.whitespaceBetween = function(options) {
options.atLeast = 1;
return this.spacesBetween(options);
};
/**
* Requires to have no whitespace between specified tokens.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {String} [options.message]
* @param {Boolean} [options.disallowNewLine=false]
* @return {Boolean} whether an error was found
*/
Function (anonymous_82)
✓ Was called
TokenAssert.prototype.noWhitespaceBetween = function(options) {···
options.exactly = 0;
return this.spacesBetween(options);
};
TokenAssert.prototype.noWhitespaceBetween = function(options) {
options.exactly = 0;
return this.spacesBetween(options);
};
/**
* Requires to have the whitespace between specified tokens with the provided options.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {String} [options.message]
* @param {Object} [options.atLeast] At least how many spaces the tokens are apart
* @param {Object} [options.atMost] At most how many spaces the tokens are apart
* @param {Object} [options.exactly] Exactly how many spaces the tokens are apart
* @param {Boolean} [options.disallowNewLine=false]
* @return {Boolean} whether an error was found
*/
Function (anonymous_83)
✓ Was called
TokenAssert.prototype.spacesBetween = function(options) {···
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;

if (!token || !nextToken) {
return false;
}

this._validateOptions(options);

if (!options.disallowNewLine && !this._file.isOnTheSameLine(token, nextToken)) {
return false;
}

// Only attempt to remove or add lines if there are no comments between the two nodes
// as this prevents accidentally moving a valid token onto a line comment ed line
var fixed = !options.token.getNextNonWhitespaceToken().isComment;

var emitError = function(countPrefix, spaceCount) {
var fix = function() {
this._file.setWhitespaceBefore(nextToken, new Array(spaceCount + 1).join(' '));
}.bind(this);

var msgPostfix = token.value + ' and ' + nextToken.value;

if (!options.message) {
if (exactly === 0) {
// support noWhitespaceBetween
options.message = 'Unexpected whitespace between ' + msgPostfix;
} else if (exactly !== undefined) {
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
} else if (atLeast === 1 && atMost === undefined) {
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
}

this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
fix: fixed ? fix : undefined
});
}.bind(this);

var spacesBetween = this._file.getDistanceBetween(token, nextToken);

if (atLeast !== undefined && spacesBetween < atLeast) {
emitError('at least', atLeast);
return true;
}

if (atMost !== undefined && spacesBetween > atMost) {
emitError('at most', atMost);
return true;
}

if (exactly !== undefined && spacesBetween !== exactly) {
emitError('exactly', exactly);
return true;
}

return false;
};
TokenAssert.prototype.spacesBetween = function(options) {
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;
Branch IfStatement
✓ Positive was executed (if)
if (!token || !nextToken) {···
return false;
}
✓ Negative was executed (else)
}···

this._validateOptions(options);
Branch LogicalExpression
✓ Was returned
if (!token || !nextToken) {
✓ Was returned
if (!token || !nextToken) {
if (!token || !nextToken) {
return false;
}
this._validateOptions(options);
Branch IfStatement
✓ Positive was executed (if)
if (!options.disallowNewLine && !this._file.isOnTheSameLine(token, nextToken)) {···
return false;
}
✓ Negative was executed (else)
}···

// Only attempt to remove or add lines if there are no comments between the two nodes
Branch LogicalExpression
✓ Was returned
if (!options.disallowNewLine && !this._file.isOnTheSameLine(token, nextToken)) {
✓ Was returned
if (!options.disallowNewLine && !this._file.isOnTheSameLine(token, nextToken)) {
if (!options.disallowNewLine && !this._file.isOnTheSameLine(token, nextToken)) {
return false;
}
// Only attempt to remove or add lines if there are no comments between the two nodes
// as this prevents accidentally moving a valid token onto a line comment ed line
var fixed = !options.token.getNextNonWhitespaceToken().isComment;
Function (anonymous_84)
✓ Was called
var emitError = function(countPrefix, spaceCount) {···
var fix = function() {
this._file.setWhitespaceBefore(nextToken, new Array(spaceCount + 1).join(' '));
}.bind(this);

var msgPostfix = token.value + ' and ' + nextToken.value;

if (!options.message) {
if (exactly === 0) {
// support noWhitespaceBetween
options.message = 'Unexpected whitespace between ' + msgPostfix;
} else if (exactly !== undefined) {
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
} else if (atLeast === 1 && atMost === undefined) {
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
}

this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
fix: fixed ? fix : undefined
});
}.bind(this);
var emitError = function(countPrefix, spaceCount) {
Function (anonymous_85)
✗ Was not called
var fix = function() {···
this._file.setWhitespaceBefore(nextToken, new Array(spaceCount + 1).join(' '));
}.bind(this);
var fix = function() {
this._file.setWhitespaceBefore(nextToken, new Array(spaceCount + 1).join(' '));
}.bind(this);
var msgPostfix = token.value + ' and ' + nextToken.value;
Branch IfStatement
✓ Positive was executed (if)
if (!options.message) {···
if (exactly === 0) {
// support noWhitespaceBetween
options.message = 'Unexpected whitespace between ' + msgPostfix;
} else if (exactly !== undefined) {
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
} else if (atLeast === 1 && atMost === undefined) {
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
}
✓ Negative was executed (else)
}···

this.emit('error', {
if (!options.message) {
Branch IfStatement
✓ Positive was executed (if)
if (exactly === 0) {···
// support noWhitespaceBetween
options.message = 'Unexpected whitespace between ' + msgPostfix;
} else if (exactly !== undefined) {
✓ Negative was executed (else)
} else if (exactly !== undefined) {···
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
} else if (atLeast === 1 && atMost === undefined) {
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
if (exactly === 0) {
// support noWhitespaceBetween
options.message = 'Unexpected whitespace between ' + msgPostfix;
Branch IfStatement
✓ Positive was executed (if)
} else if (exactly !== undefined) {···
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
} else if (atLeast === 1 && atMost === undefined) {
✓ Negative was executed (else)
} else if (atLeast === 1 && atMost === undefined) {···
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
} else if (exactly !== undefined) {
// support whitespaceBetween (spaces option)
options.message = spaceCount + ' spaces required between ' + msgPostfix;
Branch IfStatement
✓ Positive was executed (if)
} else if (atLeast === 1 && atMost === undefined) {···
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
✓ Negative was executed (else)
} else {···
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
Branch LogicalExpression
✓ Was returned
} else if (atLeast === 1 && atMost === undefined) {
✓ Was returned
} else if (atLeast === 1 && atMost === undefined) {
} else if (atLeast === 1 && atMost === undefined) {
// support whitespaceBetween (no spaces option)
options.message = 'Missing space between ' + msgPostfix;
} else {
options.message = countPrefix + ' ' + spaceCount + ' spaces required between ' + msgPostfix;
}
}
this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
Branch ConditionalExpression
✓ Positive was returned (? ...)
fix: fixed ? fix : undefined
✓ Negative was returned (: ...)
fix: fixed ? fix : undefined
fix: fixed ? fix : undefined
});
}.bind(this);
var spacesBetween = this._file.getDistanceBetween(token, nextToken);
Branch IfStatement
✓ Positive was executed (if)
if (atLeast !== undefined && spacesBetween < atLeast) {···
emitError('at least', atLeast);
return true;
}
✓ Negative was executed (else)
}···

if (atMost !== undefined && spacesBetween > atMost) {
Branch LogicalExpression
✓ Was returned
if (atLeast !== undefined && spacesBetween < atLeast) {
✓ Was returned
if (atLeast !== undefined && spacesBetween < atLeast) {
if (atLeast !== undefined && spacesBetween < atLeast) {
emitError('at least', atLeast);
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (atMost !== undefined && spacesBetween > atMost) {···
emitError('at most', atMost);
return true;
}
✓ Negative was executed (else)
}···

if (exactly !== undefined && spacesBetween !== exactly) {
Branch LogicalExpression
✓ Was returned
if (atMost !== undefined && spacesBetween > atMost) {
✓ Was returned
if (atMost !== undefined && spacesBetween > atMost) {
if (atMost !== undefined && spacesBetween > atMost) {
emitError('at most', atMost);
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (exactly !== undefined && spacesBetween !== exactly) {···
emitError('exactly', exactly);
return true;
}
✓ Negative was executed (else)
}···

return false;
Branch LogicalExpression
✓ Was returned
if (exactly !== undefined && spacesBetween !== exactly) {
✓ Was returned
if (exactly !== undefined && spacesBetween !== exactly) {
if (exactly !== undefined && spacesBetween !== exactly) {
emitError('exactly', exactly);
return true;
}
return false;
};
/**
* Requires the specified line to have the expected indentation.
*
* @param {Object} options
* @param {Number} options.actual
* @param {Number} options.expected
* @param {String} options.indentChar
* @param {String} options.token
* @return {Boolean} whether an error was found
*/
Function (anonymous_86)
✓ Was called
TokenAssert.prototype.indentation = function(options) {···
var token = options.token;
var lineNumber = options.lineNumber;
var actual = options.actual;
var expected = options.expected;
var indentChar = options.indentChar;

if (actual === expected) {
return false;
}

this.emit('error', {
message: 'Expected indentation of ' + expected + ' characters',
line: lineNumber,
column: expected,
fix: function() {
var newWhitespace = (new Array(expected + 1)).join(indentChar);

this._updateWhitespaceByLine(token, function(lines) {
lines[lines.length - 1] = newWhitespace;
return lines;
});

if (token.isComment) {
this._updateCommentWhitespace(token, indentChar, actual, expected);
}
}.bind(this)
});

return true;
};
TokenAssert.prototype.indentation = function(options) {
var token = options.token;
var lineNumber = options.lineNumber;
var actual = options.actual;
var expected = options.expected;
var indentChar = options.indentChar;
Branch IfStatement
✓ Positive was executed (if)
if (actual === expected) {···
return false;
}
✓ Negative was executed (else)
}···

this.emit('error', {
if (actual === expected) {
return false;
}
this.emit('error', {
message: 'Expected indentation of ' + expected + ' characters',
line: lineNumber,
column: expected,
Function (anonymous_87)
✓ Was called
fix: function() {···
var newWhitespace = (new Array(expected + 1)).join(indentChar);

this._updateWhitespaceByLine(token, function(lines) {
lines[lines.length - 1] = newWhitespace;
return lines;
});

if (token.isComment) {
this._updateCommentWhitespace(token, indentChar, actual, expected);
}
}.bind(this)
fix: function() {
var newWhitespace = (new Array(expected + 1)).join(indentChar);
Function (anonymous_88)
✓ Was called
this._updateWhitespaceByLine(token, function(lines) {···
lines[lines.length - 1] = newWhitespace;
return lines;
});
this._updateWhitespaceByLine(token, function(lines) {
lines[lines.length - 1] = newWhitespace;
return lines;
});
Branch IfStatement
✓ Positive was executed (if)
if (token.isComment) {···
this._updateCommentWhitespace(token, indentChar, actual, expected);
}
✗ Negative was not executed (else)
}···
}.bind(this)
if (token.isComment) {
this._updateCommentWhitespace(token, indentChar, actual, expected);
}
}.bind(this)
});
return true;
};
/**
* Updates the whitespace of a line by passing split lines to a callback function
* for editing.
*
* @param {Object} token
* @param {Function} callback
*/
Function (anonymous_89)
✓ Was called
TokenAssert.prototype._updateWhitespaceByLine = function(token, callback) {···
var lineBreak = this._file.getLineBreakStyle();
var lines = this._file.getWhitespaceBefore(token).split(/\r\n|\r|\n/);

lines = callback(lines);
this._file.setWhitespaceBefore(token, lines.join(lineBreak));
};
TokenAssert.prototype._updateWhitespaceByLine = function(token, callback) {
var lineBreak = this._file.getLineBreakStyle();
var lines = this._file.getWhitespaceBefore(token).split(/\r\n|\r|\n/);
lines = callback(lines);
this._file.setWhitespaceBefore(token, lines.join(lineBreak));
};
/**
* Updates the whitespace of a line by passing split lines to a callback function
* for editing.
*
* @param {Object} token
* @param {Function} indentChar
* @param {Number} actual
* @param {Number} expected
*/
Function (anonymous_90)
✓ Was called
TokenAssert.prototype._updateCommentWhitespace = function(token, indentChar, actual, expected) {···
var difference = expected - actual;
var tokenLines = token.value.split(/\r\n|\r|\n/);
var i = 1;
if (difference >= 0) {
var lineWhitespace = (new Array(difference + 1)).join(indentChar);
for (; i < tokenLines.length; i++) {
tokenLines[i] = tokenLines[i] === '' ? '' : lineWhitespace + tokenLines[i];
}
} else {
for (; i < tokenLines.length; i++) {
tokenLines[i] = tokenLines[i].substring(-difference);
}
}

var newComment = new Token('CommentBlock', tokenLines.join(this._file.getLineBreakStyle()));
token.parentElement.replaceChild(newComment, token);
};
TokenAssert.prototype._updateCommentWhitespace = function(token, indentChar, actual, expected) {
var difference = expected - actual;
var tokenLines = token.value.split(/\r\n|\r|\n/);
var i = 1;
Branch IfStatement
✓ Positive was executed (if)
if (difference >= 0) {···
var lineWhitespace = (new Array(difference + 1)).join(indentChar);
for (; i < tokenLines.length; i++) {
tokenLines[i] = tokenLines[i] === '' ? '' : lineWhitespace + tokenLines[i];
}
} else {
✓ Negative was executed (else)
} else {···
for (; i < tokenLines.length; i++) {
tokenLines[i] = tokenLines[i].substring(-difference);
}
}
if (difference >= 0) {
var lineWhitespace = (new Array(difference + 1)).join(indentChar);
for (; i < tokenLines.length; i++) {
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenLines[i] = tokenLines[i] === '' ? '' : lineWhitespace + tokenLines[i];
✓ Negative was returned (: ...)
tokenLines[i] = tokenLines[i] === '' ? '' : lineWhitespace + tokenLines[i];
tokenLines[i] = tokenLines[i] === '' ? '' : lineWhitespace + tokenLines[i];
}
} else {
for (; i < tokenLines.length; i++) {
tokenLines[i] = tokenLines[i].substring(-difference);
}
}
var newComment = new Token('CommentBlock', tokenLines.join(this._file.getLineBreakStyle()));
token.parentElement.replaceChild(newComment, token);
};
/**
* Requires tokens to be on the same line.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {Boolean} [options.stickToPreviousToken]
* @param {String} [options.message]
* @return {Boolean} whether an error was found
*/
Function (anonymous_91)
✓ Was called
TokenAssert.prototype.sameLine = function(options) {···
options.exactly = 0;

return this.linesBetween(options);
};
TokenAssert.prototype.sameLine = function(options) {
options.exactly = 0;
return this.linesBetween(options);
};
/**
* Requires tokens to be on different lines.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {Object} [options.message]
* @return {Boolean} whether an error was found
*/
Function (anonymous_92)
✓ Was called
TokenAssert.prototype.differentLine = function(options) {···
options.atLeast = 1;

return this.linesBetween(options);
};
TokenAssert.prototype.differentLine = function(options) {
options.atLeast = 1;
return this.linesBetween(options);
};
/**
* Requires tokens to have a certain amount of lines between them.
* Set at least one of atLeast or atMost OR set exactly.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {Object} [options.message]
* @param {Object} [options.atLeast] At least how many lines the tokens are apart
* @param {Object} [options.atMost] At most how many lines the tokens are apart
* @param {Object} [options.exactly] Exactly how many lines the tokens are apart
* @param {Boolean} [options.stickToPreviousToken] When auto-fixing stick the
* nextToken onto the previous token.
* @return {Boolean} whether an error was found
*/
Function (anonymous_93)
✓ Was called
TokenAssert.prototype.linesBetween = function(options) {···
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;

if (!token || !nextToken) {
return false;
}

this._validateOptions(options);

// Only attempt to remove or add lines if there are no comments between the two nodes
// as this prevents accidentally moving a valid token onto a line comment ed line
var fixed = !options.token.getNextNonWhitespaceToken().isComment;

var linesBetween = this._file.getLineCountBetween(token, nextToken);

var emitError = function(countPrefix, lineCount) {
var msgPrefix = token.value + ' and ' + nextToken.value;

var fix = function() {
this._augmentLineCount(options, lineCount);
}.bind(this);

if (!options.message) {
if (exactly === 0) {
// support sameLine
options.message = msgPrefix + ' should be on the same line';
} else if (atLeast === 1 && atMost === undefined) {
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
}

this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
fix: fixed ? fix : undefined
});
}.bind(this);

if (atLeast !== undefined && linesBetween < atLeast) {
emitError('at least', atLeast);
return true;
}

if (atMost !== undefined && linesBetween > atMost) {
emitError('at most', atMost);
return true;
}

if (exactly !== undefined && linesBetween !== exactly) {
emitError('exactly', exactly);
return true;
}

return false;
};
TokenAssert.prototype.linesBetween = function(options) {
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;
Branch IfStatement
✓ Positive was executed (if)
if (!token || !nextToken) {···
return false;
}
✓ Negative was executed (else)
}···

this._validateOptions(options);
Branch LogicalExpression
✓ Was returned
if (!token || !nextToken) {
✓ Was returned
if (!token || !nextToken) {
if (!token || !nextToken) {
return false;
}
this._validateOptions(options);
// Only attempt to remove or add lines if there are no comments between the two nodes
// as this prevents accidentally moving a valid token onto a line comment ed line
var fixed = !options.token.getNextNonWhitespaceToken().isComment;
var linesBetween = this._file.getLineCountBetween(token, nextToken);
Function (anonymous_94)
✓ Was called
var emitError = function(countPrefix, lineCount) {···
var msgPrefix = token.value + ' and ' + nextToken.value;

var fix = function() {
this._augmentLineCount(options, lineCount);
}.bind(this);

if (!options.message) {
if (exactly === 0) {
// support sameLine
options.message = msgPrefix + ' should be on the same line';
} else if (atLeast === 1 && atMost === undefined) {
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
}

this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
fix: fixed ? fix : undefined
});
}.bind(this);
var emitError = function(countPrefix, lineCount) {
var msgPrefix = token.value + ' and ' + nextToken.value;
Function (anonymous_95)
✓ Was called
var fix = function() {···
this._augmentLineCount(options, lineCount);
}.bind(this);
var fix = function() {
this._augmentLineCount(options, lineCount);
}.bind(this);
Branch IfStatement
✓ Positive was executed (if)
if (!options.message) {···
if (exactly === 0) {
// support sameLine
options.message = msgPrefix + ' should be on the same line';
} else if (atLeast === 1 && atMost === undefined) {
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
}
✓ Negative was executed (else)
}···

this.emit('error', {
if (!options.message) {
Branch IfStatement
✓ Positive was executed (if)
if (exactly === 0) {···
// support sameLine
options.message = msgPrefix + ' should be on the same line';
} else if (atLeast === 1 && atMost === undefined) {
✓ Negative was executed (else)
} else if (atLeast === 1 && atMost === undefined) {···
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
if (exactly === 0) {
// support sameLine
options.message = msgPrefix + ' should be on the same line';
Branch IfStatement
✓ Positive was executed (if)
} else if (atLeast === 1 && atMost === undefined) {···
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
✓ Negative was executed (else)
} else {···
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
Branch LogicalExpression
✓ Was returned
} else if (atLeast === 1 && atMost === undefined) {
✓ Was returned
} else if (atLeast === 1 && atMost === undefined) {
} else if (atLeast === 1 && atMost === undefined) {
// support differentLine
options.message = msgPrefix + ' should be on different lines';
} else {
// support linesBetween
options.message = msgPrefix + ' should have ' + countPrefix + ' ' + lineCount + ' line(s) between them';
}
}
this.emit('error', {
message: options.message,
element: token,
offset: token.getSourceCodeLength(),
Branch ConditionalExpression
✓ Positive was returned (? ...)
fix: fixed ? fix : undefined
✓ Negative was returned (: ...)
fix: fixed ? fix : undefined
fix: fixed ? fix : undefined
});
}.bind(this);
Branch IfStatement
✓ Positive was executed (if)
if (atLeast !== undefined && linesBetween < atLeast) {···
emitError('at least', atLeast);
return true;
}
✓ Negative was executed (else)
}···

if (atMost !== undefined && linesBetween > atMost) {
Branch LogicalExpression
✓ Was returned
if (atLeast !== undefined && linesBetween < atLeast) {
✓ Was returned
if (atLeast !== undefined && linesBetween < atLeast) {
if (atLeast !== undefined && linesBetween < atLeast) {
emitError('at least', atLeast);
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (atMost !== undefined && linesBetween > atMost) {···
emitError('at most', atMost);
return true;
}
✓ Negative was executed (else)
}···

if (exactly !== undefined && linesBetween !== exactly) {
Branch LogicalExpression
✓ Was returned
if (atMost !== undefined && linesBetween > atMost) {
✓ Was returned
if (atMost !== undefined && linesBetween > atMost) {
if (atMost !== undefined && linesBetween > atMost) {
emitError('at most', atMost);
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (exactly !== undefined && linesBetween !== exactly) {···
emitError('exactly', exactly);
return true;
}
✓ Negative was executed (else)
}···

return false;
Branch LogicalExpression
✓ Was returned
if (exactly !== undefined && linesBetween !== exactly) {
✓ Was returned
if (exactly !== undefined && linesBetween !== exactly) {
if (exactly !== undefined && linesBetween !== exactly) {
emitError('exactly', exactly);
return true;
}
return false;
};
/**
* Throws errors if atLeast, atMost, and exactly options don't mix together properly or
* if the tokens provided are equivalent.
*
* @param {Object} options
* @param {Object} options.token
* @param {Object} options.nextToken
* @param {Object} [options.atLeast] At least how many spaces the tokens are apart
* @param {Object} [options.atMost] At most how many spaces the tokens are apart
* @param {Object} [options.exactly] Exactly how many spaces the tokens are apart
* @throws {Error} If the options are non-sensical
* @private
*/
Function (anonymous_96)
✓ Was called
TokenAssert.prototype._validateOptions = function(options) {···
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;

if (token === nextToken) {
throw new Error('You cannot specify the same token as both token and nextToken');
}

if (atLeast === undefined &&
atMost === undefined &&
exactly === undefined) {
throw new Error('You must specify at least one option');
}

if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
throw new Error('You cannot specify atLeast or atMost with exactly');
}

if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
throw new Error('atLeast and atMost are in conflict');
}
};
TokenAssert.prototype._validateOptions = function(options) {
var token = options.token;
var nextToken = options.nextToken;
var atLeast = options.atLeast;
var atMost = options.atMost;
var exactly = options.exactly;
Branch IfStatement
✓ Positive was executed (if)
if (token === nextToken) {···
throw new Error('You cannot specify the same token as both token and nextToken');
}
✓ Negative was executed (else)
}···

if (atLeast === undefined &&
if (token === nextToken) {
throw new Error('You cannot specify the same token as both token and nextToken');
}
Branch IfStatement
✓ Positive was executed (if)
exactly === undefined) {···
throw new Error('You must specify at least one option');
}
✓ Negative was executed (else)
}···

if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
Branch LogicalExpression
✓ Was returned
exactly === undefined) {
✓ Was returned
if (atLeast === undefined &&···
atMost === undefined &&
Branch LogicalExpression
✓ Was returned
atMost === undefined &&
✓ Was returned
if (atLeast === undefined &&
if (atLeast === undefined &&
atMost === undefined &&
exactly === undefined) {
throw new Error('You must specify at least one option');
}
Branch IfStatement
✓ Positive was executed (if)
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {···
throw new Error('You cannot specify atLeast or atMost with exactly');
}
✓ Negative was executed (else)
}···

if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
Branch LogicalExpression
✓ Was returned
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
✓ Was returned
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
Branch LogicalExpression
✓ Was returned
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
✓ Was returned
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
if (exactly !== undefined && (atLeast !== undefined || atMost !== undefined)) {
throw new Error('You cannot specify atLeast or atMost with exactly');
}
Branch IfStatement
✓ Positive was executed (if)
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {···
throw new Error('atLeast and atMost are in conflict');
}
✓ Negative was executed (else)
}···
};
Branch LogicalExpression
✓ Was returned
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
✓ Was returned
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
Branch LogicalExpression
✓ Was returned
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
✓ Was returned
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
if (atLeast !== undefined && atMost !== undefined && atMost < atLeast) {
throw new Error('atLeast and atMost are in conflict');
}
};
/**
* Augments token whitespace to contain the correct number of newlines while preserving indentation
*
* @param {Object} options
* @param {Object} options.nextToken
* @param {Boolean} [options.stickToPreviousToken]
* @param {Number} lineCount
* @private
*/
Function (anonymous_97)
✓ Was called
TokenAssert.prototype._augmentLineCount = function(options, lineCount) {···
var token = options.nextToken;
if (lineCount === 0) {
if (options.stickToPreviousToken) {
var nextToken = this._file.getNextToken(token, {
includeComments: true
});
this._file.setWhitespaceBefore(nextToken, this._file.getWhitespaceBefore(token));
}

this._file.setWhitespaceBefore(token, ' ');
return;
}

this._updateWhitespaceByLine(token, function(lines) {
var currentLineCount = lines.length;
var lastLine = lines[lines.length - 1];

if (currentLineCount <= lineCount) {
// add additional lines that maintain the same indentation as the former last line
for (; currentLineCount <= lineCount; currentLineCount++) {
lines[lines.length - 1] = '';
lines.push(lastLine);
}
} else {
// remove lines and then ensure that the new last line maintains the previous indentation
lines = lines.slice(0, lineCount + 1);
lines[lines.length - 1] = lastLine;
}

return lines;
});
};
TokenAssert.prototype._augmentLineCount = function(options, lineCount) {
var token = options.nextToken;
Branch IfStatement
✓ Positive was executed (if)
if (lineCount === 0) {···
if (options.stickToPreviousToken) {
var nextToken = this._file.getNextToken(token, {
includeComments: true
});
this._file.setWhitespaceBefore(nextToken, this._file.getWhitespaceBefore(token));
}

this._file.setWhitespaceBefore(token, ' ');
return;
}
✓ Negative was executed (else)
}···

this._updateWhitespaceByLine(token, function(lines) {
if (lineCount === 0) {
Branch IfStatement
✓ Positive was executed (if)
if (options.stickToPreviousToken) {···
var nextToken = this._file.getNextToken(token, {
includeComments: true
});
this._file.setWhitespaceBefore(nextToken, this._file.getWhitespaceBefore(token));
}
✗ Negative was not executed (else)
}···

this._file.setWhitespaceBefore(token, ' ');
if (options.stickToPreviousToken) {
var nextToken = this._file.getNextToken(token, {
includeComments: true
});
this._file.setWhitespaceBefore(nextToken, this._file.getWhitespaceBefore(token));
}
this._file.setWhitespaceBefore(token, ' ');
return;
}
Function (anonymous_98)
✓ Was called
this._updateWhitespaceByLine(token, function(lines) {···
var currentLineCount = lines.length;
var lastLine = lines[lines.length - 1];

if (currentLineCount <= lineCount) {
// add additional lines that maintain the same indentation as the former last line
for (; currentLineCount <= lineCount; currentLineCount++) {
lines[lines.length - 1] = '';
lines.push(lastLine);
}
} else {
// remove lines and then ensure that the new last line maintains the previous indentation
lines = lines.slice(0, lineCount + 1);
lines[lines.length - 1] = lastLine;
}

return lines;
});
this._updateWhitespaceByLine(token, function(lines) {
var currentLineCount = lines.length;
var lastLine = lines[lines.length - 1];
Branch IfStatement
✓ Positive was executed (if)
if (currentLineCount <= lineCount) {···
// add additional lines that maintain the same indentation as the former last line
for (; currentLineCount <= lineCount; currentLineCount++) {
lines[lines.length - 1] = '';
lines.push(lastLine);
}
} else {
✓ Negative was executed (else)
} else {···
// remove lines and then ensure that the new last line maintains the previous indentation
lines = lines.slice(0, lineCount + 1);
lines[lines.length - 1] = lastLine;
}
if (currentLineCount <= lineCount) {
// add additional lines that maintain the same indentation as the former last line
for (; currentLineCount <= lineCount; currentLineCount++) {
lines[lines.length - 1] = '';
lines.push(lastLine);
}
} else {
// remove lines and then ensure that the new last line maintains the previous indentation
lines = lines.slice(0, lineCount + 1);
lines[lines.length - 1] = lastLine;
}
return lines;
});
};
module.exports = TokenAssert;
js-file.js
// var assert = require('assert');
var cst = require('cst');
var Parser = cst.Parser;
var Token = cst.Token;
var Program = cst.types.Program;
var Fragment = cst.Fragment;
var ScopesApi = cst.api.ScopesApi;
var treeIterator = require('./tree-iterator');
// var Program = cst.types.Program;
/**
* Operator list which are represented as keywords in token list.
*/
var KEYWORD_OPERATORS = {
'instanceof': true,
'in': true
};
/**
* File representation for JSCS.
*
* @name JsFile
* @param {Object} params
* @param {String} params.filename
* @param {String} params.source
* @param {Boolean} [params.es3]
*/
Function (anonymous_99)
✓ Was called
var JsFile = function(params) {···
params = params || {};
this._parseErrors = [];
this._filename = params.filename;
this._source = params.source;

this._es3 = params.es3 || false;

this._lineBreaks = null;
this._lines = this._source.split(/\r\n|\r|\n/);

var parser = new Parser({
strictMode: false,
languageExtensions: {
gritDirectives: true,
appleInstrumentationDirectives: true
}
});

try {
this._program = parser.parse(this._source);
} catch (e) {
this._parseErrors.push(e);
this._program = new Program([
new Token('EOF', '')
]);
}

// Lazy initialization
this._scopes = null;
};
var JsFile = function(params) {
Branch LogicalExpression
✗ Was not returned
params = params || {};
✓ Was returned
params = params || {};
params = params || {};
this._parseErrors = [];
this._filename = params.filename;
this._source = params.source;
Branch LogicalExpression
✓ Was returned
this._es3 = params.es3 || false;
✓ Was returned
this._es3 = params.es3 || false;
this._es3 = params.es3 || false;
this._lineBreaks = null;
this._lines = this._source.split(/\r\n|\r|\n/);
var parser = new Parser({
strictMode: false,
languageExtensions: {
gritDirectives: true,
appleInstrumentationDirectives: true
}
});
try {
this._program = parser.parse(this._source);
} catch (e) {
this._parseErrors.push(e);
this._program = new Program([
new Token('EOF', '')
]);
}
// Lazy initialization
this._scopes = null;
};
JsFile.prototype = {
/**
* @returns {cst.types.Program}
*/
Function (anonymous_100)
✗ Was not called
getProgram: function() {···
return this._program;
},
getProgram: function() {
return this._program;
},
/**
* Returns the first line break character encountered in the file.
* Assumes LF if the file is only one line.
*
* @returns {String}
*/
Function (anonymous_101)
✓ Was called
getLineBreakStyle: function() {···
var lineBreaks = this.getLineBreaks();
return lineBreaks.length ? lineBreaks[0] : '\n';
},
getLineBreakStyle: function() {
var lineBreaks = this.getLineBreaks();
Branch ConditionalExpression
✓ Positive was returned (? ...)
return lineBreaks.length ? lineBreaks[0] : '\n';
✓ Negative was returned (: ...)
return lineBreaks.length ? lineBreaks[0] : '\n';
return lineBreaks.length ? lineBreaks[0] : '\n';
},
/**
* Returns all line break characters from the file.
*
* @returns {String[]}
*/
Function (anonymous_102)
✓ Was called
getLineBreaks: function() {···
if (this._lineBreaks === null) {
this._lineBreaks = this._source.match(/\r\n|\r|\n/g) || [];
}
return this._lineBreaks;
},
getLineBreaks: function() {
Branch IfStatement
✓ Positive was executed (if)
if (this._lineBreaks === null) {···
this._lineBreaks = this._source.match(/\r\n|\r|\n/g) || [];
}
✓ Negative was executed (else)
}···
return this._lineBreaks;
if (this._lineBreaks === null) {
Branch LogicalExpression
✓ Was returned
this._lineBreaks = this._source.match(/\r\n|\r|\n/g) || [];
✓ Was returned
this._lineBreaks = this._source.match(/\r\n|\r|\n/g) || [];
this._lineBreaks = this._source.match(/\r\n|\r|\n/g) || [];
}
return this._lineBreaks;
},
/**
* Sets whitespace before specified token.
*
* @param {Object} token - in front of which we will add/remove/replace the whitespace token
* @param {String} whitespace - value of the whitespace token - `\n`, `\s`, `\t`
*/
Function (anonymous_103)
✓ Was called
setWhitespaceBefore: function(token, whitespace) {···
var prevToken = token.getPreviousToken();
var ws = new Token('Whitespace', whitespace);
var fragment = new Fragment(ws);

if (prevToken && prevToken.isWhitespace) {
if (whitespace === '') {
prevToken.remove();
return;
}

prevToken.parentElement.replaceChild(fragment, prevToken);
return;
}

this._setTokenBefore(token, fragment);
},
setWhitespaceBefore: function(token, whitespace) {
var prevToken = token.getPreviousToken();
var ws = new Token('Whitespace', whitespace);
var fragment = new Fragment(ws);
Branch IfStatement
✓ Positive was executed (if)
if (prevToken && prevToken.isWhitespace) {···
if (whitespace === '') {
prevToken.remove();
return;
}

prevToken.parentElement.replaceChild(fragment, prevToken);
return;
}
✓ Negative was executed (else)
}···

this._setTokenBefore(token, fragment);
Branch LogicalExpression
✓ Was returned
if (prevToken && prevToken.isWhitespace) {
✓ Was returned
if (prevToken && prevToken.isWhitespace) {
if (prevToken && prevToken.isWhitespace) {
Branch IfStatement
✓ Positive was executed (if)
if (whitespace === '') {···
prevToken.remove();
return;
}
✓ Negative was executed (else)
}···

prevToken.parentElement.replaceChild(fragment, prevToken);
if (whitespace === '') {
prevToken.remove();
return;
}
prevToken.parentElement.replaceChild(fragment, prevToken);
return;
}
this._setTokenBefore(token, fragment);
},
Function (anonymous_104)
✓ Was called
_setTokenBefore: function(token, fragment) {···
var parent = token;
var grandpa = parent.parentElement;

while (grandpa) {
try {
grandpa.insertChildBefore(fragment, parent);
break;
} catch (e) {}

parent = grandpa;
grandpa = parent.parentElement;
}
},
_setTokenBefore: function(token, fragment) {
var parent = token;
var grandpa = parent.parentElement;
while (grandpa) {
try {
grandpa.insertChildBefore(fragment, parent);
break;
} catch (e) {}
parent = grandpa;
grandpa = parent.parentElement;
}
},
/**
* Returns whitespace before specified token.
*
* @param {Object} token
* @returns {String}
*/
Function (anonymous_105)
✓ Was called
getWhitespaceBefore: function(token) {···
if (!token.getPreviousToken) {
console.log(token);
}
var prev = token.getPreviousToken();

if (prev && prev.isWhitespace) {
return prev.getSourceCode();
}

return '';
},
getWhitespaceBefore: function(token) {
Branch IfStatement
✗ Positive was not executed (if)
if (!token.getPreviousToken) {···
console.log(token);
}
✓ Negative was executed (else)
}···
var prev = token.getPreviousToken();
if (!token.getPreviousToken) {
console.log(token);
}
var prev = token.getPreviousToken();
Branch IfStatement
✓ Positive was executed (if)
if (prev && prev.isWhitespace) {···
return prev.getSourceCode();
}
✓ Negative was executed (else)
}···

return '';
Branch LogicalExpression
✓ Was returned
if (prev && prev.isWhitespace) {
✓ Was returned
if (prev && prev.isWhitespace) {
if (prev && prev.isWhitespace) {
return prev.getSourceCode();
}
return '';
},
/**
* Returns the first token for the node from the AST.
*
* @param {Object} node
* @returns {Object}
*/
Function (anonymous_106)
✓ Was called
getFirstNodeToken: function(node) {···
return node.getFirstToken();
},
getFirstNodeToken: function(node) {
return node.getFirstToken();
},
/**
* Returns the last token for the node from the AST.
*
* @param {Object} node
* @returns {Object}
*/
Function (anonymous_107)
✓ Was called
getLastNodeToken: function(node) {···
return node.getLastToken();
},
getLastNodeToken: function(node) {
return node.getLastToken();
},
/**
* Returns the first token for the file.
*
* @param {Option} [options]
* @param {Boolean} [options.includeComments=false]
* @param {Boolean} [options.includeWhitespace=false]
* @returns {Object}
*/
Function (anonymous_108)
✓ Was called
getFirstToken: function(/*options*/) {···
return this._program.getFirstToken();
},
getFirstToken: function(/*options*/) {
return this._program.getFirstToken();
},
/**
* Returns the last token for the file.
*
* @param {Option} [options]
* @param {Boolean} [options.includeComments=false]
* @param {Boolean} [options.includeWhitespace=false]
* @returns {Object}
*/
Function (anonymous_109)
✓ Was called
getLastToken: function(/*options*/) {···
return this._program.getLastToken();
},
getLastToken: function(/*options*/) {
return this._program.getLastToken();
},
/**
* Returns the first token before the given.
*
* @param {Object} token
* @param {Object} [options]
* @param {Boolean} [options.includeComments=false]
* @returns {Object|undefined}
*/
Function (anonymous_110)
✓ Was called
getPrevToken: function(token, options) {···
if (options && options.includeComments) {
return token.getPreviousNonWhitespaceToken();
}

return token.getPreviousCodeToken();
},
getPrevToken: function(token, options) {
Branch IfStatement
✓ Positive was executed (if)
if (options && options.includeComments) {···
return token.getPreviousNonWhitespaceToken();
}
✓ Negative was executed (else)
}···

return token.getPreviousCodeToken();
Branch LogicalExpression
✓ Was returned
if (options && options.includeComments) {
✓ Was returned
if (options && options.includeComments) {
if (options && options.includeComments) {
return token.getPreviousNonWhitespaceToken();
}
return token.getPreviousCodeToken();
},
/**
* Returns the first token after the given.
*
* @param {Object} token
* @param {Object} [options]
* @param {Boolean} [options.includeComments=false]
* @returns {Object|undefined}
*/
Function (anonymous_111)
✓ Was called
getNextToken: function(token, options) {···
if (options && options.includeComments) {
return token.getNextNonWhitespaceToken();
} else {
return token.getNextCodeToken();
}
},
getNextToken: function(token, options) {
Branch IfStatement
✓ Positive was executed (if)
if (options && options.includeComments) {···
return token.getNextNonWhitespaceToken();
} else {
✓ Negative was executed (else)
} else {···
return token.getNextCodeToken();
}
Branch LogicalExpression
✓ Was returned
if (options && options.includeComments) {
✓ Was returned
if (options && options.includeComments) {
if (options && options.includeComments) {
return token.getNextNonWhitespaceToken();
} else {
return token.getNextCodeToken();
}
},
/**
* Returns the first token before the given which matches type (and value).
*
* @param {Object} token
* @param {String} type
* @param {String} [value]
* @returns {Object|null}
*/
Function (anonymous_112)
✓ Was called
findPrevToken: function(token, type, value) {···
var prevToken = this.getPrevToken(token);
while (prevToken) {
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
return prevToken;
}

prevToken = this.getPrevToken(prevToken);
}
return prevToken;
},
findPrevToken: function(token, type, value) {
var prevToken = this.getPrevToken(token);
while (prevToken) {
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {···
return prevToken;
}
✓ Negative was executed (else)
}···

prevToken = this.getPrevToken(prevToken);
Branch LogicalExpression
✓ Was returned
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
✓ Was returned
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
Branch LogicalExpression
✓ Was returned
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
✓ Was returned
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
if (prevToken.type === type && (value === undefined || prevToken.value === value)) {
return prevToken;
}
prevToken = this.getPrevToken(prevToken);
}
return prevToken;
},
/**
* Returns the first token after the given which matches type (and value).
*
* @param {Object} token
* @param {String} type
* @param {String} [value]
* @returns {Object|null}
*/
Function (anonymous_113)
✓ Was called
findNextToken: function(token, type, value) {···
var nextToken = token.getNextToken();

while (nextToken) {
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
return nextToken;
}

nextToken = nextToken.getNextToken();
}
return nextToken;
},
findNextToken: function(token, type, value) {
var nextToken = token.getNextToken();
while (nextToken) {
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {···
return nextToken;
}
✓ Negative was executed (else)
}···

nextToken = nextToken.getNextToken();
Branch LogicalExpression
✓ Was returned
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
✓ Was returned
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
Branch LogicalExpression
✓ Was returned
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
✓ Was returned
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
if (nextToken.type === type && (value === undefined || nextToken.value === value)) {
return nextToken;
}
nextToken = nextToken.getNextToken();
}
return nextToken;
},
/**
* Returns the first token before the given which matches type (and value).
*
* @param {Object} token
* @param {String} value
* @returns {Object|null}
*/
Function (anonymous_114)
✓ Was called
findPrevOperatorToken: function(token, value) {···
return this.findPrevToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
},
findPrevOperatorToken: function(token, value) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
return this.findPrevToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
✓ Negative was returned (: ...)
return this.findPrevToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
return this.findPrevToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
},
/**
* Returns the first token after the given which matches type (and value).
*
* @param {Object} token
* @param {String} value
* @returns {Object|null}
*/
Function (anonymous_115)
✓ Was called
findNextOperatorToken: function(token, value) {···
return this.findNextToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
},
findNextOperatorToken: function(token, value) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
return this.findNextToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
✓ Negative was returned (: ...)
return this.findNextToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
return this.findNextToken(token, value in KEYWORD_OPERATORS ? 'Keyword' : 'Punctuator', value);
},
/**
* Iterates through the token tree using tree iterator.
* Calls passed function for every token.
*
* @param {Function} cb
* @param {Object} [tree]
*/
Function (anonymous_116)
✓ Was called
iterate: function(cb, tree) {···
return treeIterator.iterate(tree || this._program, cb);
},
iterate: function(cb, tree) {
Branch LogicalExpression
✓ Was returned
return treeIterator.iterate(tree || this._program, cb);
✓ Was returned
return treeIterator.iterate(tree || this._program, cb);
return treeIterator.iterate(tree || this._program, cb);
},
/**
* Returns nodes by type(s) from earlier built index.
*
* @param {String|String[]} type
* @returns {Object[]}
*/
Function (anonymous_117)
✓ Was called
getNodesByType: function(type) {···
type = Array.isArray(type) ? type : [type];
var result = [];

for (var i = 0, l = type.length; i < l; i++) {
var nodes = this._program.selectNodesByType(type[i]);

if (nodes) {
result = result.concat(nodes);
}
}

return result;
},
getNodesByType: function(type) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
type = Array.isArray(type) ? type : [type];
✓ Negative was returned (: ...)
type = Array.isArray(type) ? type : [type];
type = Array.isArray(type) ? type : [type];
var result = [];
for (var i = 0, l = type.length; i < l; i++) {
var nodes = this._program.selectNodesByType(type[i]);
Branch IfStatement
✓ Positive was executed (if)
if (nodes) {···
result = result.concat(nodes);
}
✗ Negative was not executed (else)
}···
}
if (nodes) {
result = result.concat(nodes);
}
}
return result;
},
/**
* Iterates nodes by type(s) from earlier built index.
* Calls passed function for every matched node.
*
* @param {String|String[]} type
* @param {Function} cb
* @param {Object} context
*/
Function (anonymous_118)
✓ Was called
iterateNodesByType: function(type, cb, context) {···
return this.getNodesByType(type).forEach(cb, context || this);
},
iterateNodesByType: function(type, cb, context) {
Branch LogicalExpression
✓ Was returned
return this.getNodesByType(type).forEach(cb, context || this);
✗ Was not returned
return this.getNodesByType(type).forEach(cb, context || this);
return this.getNodesByType(type).forEach(cb, context || this);
},
/**
* Iterates tokens by type(s) from the token array.
* Calls passed function for every matched token.
*
* @param {String|String[]} type
* @param {Function} cb
*/
Function (anonymous_119)
✓ Was called
iterateTokensByType: function(type, cb) {···
var tokens;

if (Array.isArray(type)) {
tokens = [];
for (var i = 0; i < type.length; i++) {
var items = this._program.selectTokensByType(type[i]);
tokens = tokens.concat(items);
}
} else {
tokens = this._program.selectTokensByType(type);
}

tokens.forEach(cb);
},
iterateTokensByType: function(type, cb) {
var tokens;
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(type)) {···
tokens = [];
for (var i = 0; i < type.length; i++) {
var items = this._program.selectTokensByType(type[i]);
tokens = tokens.concat(items);
}
} else {
✓ Negative was executed (else)
} else {···
tokens = this._program.selectTokensByType(type);
}
if (Array.isArray(type)) {
tokens = [];
for (var i = 0; i < type.length; i++) {
var items = this._program.selectTokensByType(type[i]);
tokens = tokens.concat(items);
}
} else {
tokens = this._program.selectTokensByType(type);
}
tokens.forEach(cb);
},
/**
* Iterates tokens by type and value(s) from the token array.
* Calls passed function for every matched token.
*
* @param {String} type
* @param {String|String[]} value
* @param {Function} cb
*/
Function (anonymous_120)
✓ Was called
iterateTokensByTypeAndValue: function(type, value, cb) {···
var values = (typeof value === 'string') ? [value] : value;
var valueIndex = {};
values.forEach(function(type) {
valueIndex[type] = true;
});

this.iterateTokensByType(type, function(token) {
if (valueIndex[token.value]) {
cb(token);
}
});
},
iterateTokensByTypeAndValue: function(type, value, cb) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
var values = (typeof value === 'string') ? [value] : value;
✓ Negative was returned (: ...)
var values = (typeof value === 'string') ? [value] : value;
var values = (typeof value === 'string') ? [value] : value;
var valueIndex = {};
Function (anonymous_121)
✓ Was called
values.forEach(function(type) {···
valueIndex[type] = true;
});
values.forEach(function(type) {
valueIndex[type] = true;
});
Function (anonymous_122)
✓ Was called
this.iterateTokensByType(type, function(token) {···
if (valueIndex[token.value]) {
cb(token);
}
});
this.iterateTokensByType(type, function(token) {
Branch IfStatement
✓ Positive was executed (if)
if (valueIndex[token.value]) {···
cb(token);
}
✗ Negative was not executed (else)
}···
});
if (valueIndex[token.value]) {
cb(token);
}
});
},
Function (anonymous_123)
✗ Was not called
getFirstTokenOnLineWith: function(element, options) {···
options = options || {};
var firstToken = element;

if (element.isComment && !options.includeComments) {
firstToken = null;
}

if (element.isWhitespace && !options.includeWhitespace) {
firstToken = null;
}

var currentToken = element.getPreviousToken();
while (currentToken) {
if (currentToken.isWhitespace) {
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
} else if (currentToken.isComment) {
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}

currentToken = currentToken.getPreviousToken();
}

if (firstToken) {
return firstToken;
}

currentToken = element.getNextToken();
while (currentToken) {
if (currentToken.isWhitespace) {
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
} else if (currentToken.isComment) {
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}

currentToken = currentToken.getNextToken();
}

return firstToken;
},
getFirstTokenOnLineWith: function(element, options) {
Branch LogicalExpression
✗ Was not returned
options = options || {};
✗ Was not returned
options = options || {};
options = options || {};
var firstToken = element;
Branch IfStatement
✗ Positive was not executed (if)
if (element.isComment && !options.includeComments) {···
firstToken = null;
}
✗ Negative was not executed (else)
}···

if (element.isWhitespace && !options.includeWhitespace) {
Branch LogicalExpression
✗ Was not returned
if (element.isComment && !options.includeComments) {
✗ Was not returned
if (element.isComment && !options.includeComments) {
if (element.isComment && !options.includeComments) {
firstToken = null;
}
Branch IfStatement
✗ Positive was not executed (if)
if (element.isWhitespace && !options.includeWhitespace) {···
firstToken = null;
}
✗ Negative was not executed (else)
}···

var currentToken = element.getPreviousToken();
Branch LogicalExpression
✗ Was not returned
if (element.isWhitespace && !options.includeWhitespace) {
✗ Was not returned
if (element.isWhitespace && !options.includeWhitespace) {
if (element.isWhitespace && !options.includeWhitespace) {
firstToken = null;
}
var currentToken = element.getPreviousToken();
while (currentToken) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.isWhitespace) {···
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
} else if (currentToken.isComment) {
✗ Negative was not executed (else)
} else if (currentToken.isComment) {···
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}
if (currentToken.isWhitespace) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {···
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
✗ Negative was not executed (else)
}···
} else if (currentToken.isComment) {
Branch LogicalExpression
✗ Was not returned
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {
✗ Was not returned
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {
if (currentToken.getNewlineCount() > 0 || !currentToken.getPreviousToken()) {
Branch IfStatement
✗ Positive was not executed (if)
if (options.includeWhitespace) {···
firstToken = currentToken;
}
✗ Negative was not executed (else)
}···
break;
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
Branch IfStatement
✗ Positive was not executed (if)
} else if (currentToken.isComment) {···
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
✗ Negative was not executed (else)
} else {···
firstToken = currentToken;
}
} else if (currentToken.isComment) {
Branch IfStatement
✗ Positive was not executed (if)
if (options.includeComments) {···
firstToken = currentToken;
break;
}
✗ Negative was not executed (else)
}···
if (currentToken.getNewlineCount() > 0) {
if (options.includeComments) {
firstToken = currentToken;
break;
}
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.getNewlineCount() > 0) {···
break;
}
✗ Negative was not executed (else)
}···
} else {
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}
currentToken = currentToken.getPreviousToken();
}
Branch IfStatement
✗ Positive was not executed (if)
if (firstToken) {···
return firstToken;
}
✗ Negative was not executed (else)
}···

currentToken = element.getNextToken();
if (firstToken) {
return firstToken;
}
currentToken = element.getNextToken();
while (currentToken) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.isWhitespace) {···
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
} else if (currentToken.isComment) {
✗ Negative was not executed (else)
} else if (currentToken.isComment) {···
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}
if (currentToken.isWhitespace) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {···
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
✗ Negative was not executed (else)
}···
} else if (currentToken.isComment) {
Branch LogicalExpression
✗ Was not returned
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {
✗ Was not returned
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {
if (currentToken.getNewlineCount() > 0 || !currentToken.getNextToken()) {
Branch IfStatement
✗ Positive was not executed (if)
if (options.includeWhitespace) {···
firstToken = currentToken;
}
✗ Negative was not executed (else)
}···
break;
if (options.includeWhitespace) {
firstToken = currentToken;
}
break;
}
Branch IfStatement
✗ Positive was not executed (if)
} else if (currentToken.isComment) {···
if (options.includeComments) {
firstToken = currentToken;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
✗ Negative was not executed (else)
} else {···
firstToken = currentToken;
}
} else if (currentToken.isComment) {
Branch IfStatement
✗ Positive was not executed (if)
if (options.includeComments) {···
firstToken = currentToken;
break;
}
✗ Negative was not executed (else)
}···
if (currentToken.getNewlineCount() > 0) {
if (options.includeComments) {
firstToken = currentToken;
break;
}
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken.getNewlineCount() > 0) {···
break;
}
✗ Negative was not executed (else)
}···
} else {
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
firstToken = currentToken;
}
currentToken = currentToken.getNextToken();
}
return firstToken;
},
/**
* Returns last token for the specified line.
* Line numbers start with 1.
*
* @param {Number} lineNumber
* @param {Object} [options]
* @param {Boolean} [options.includeComments = false]
* @param {Boolean} [options.includeWhitespace = false]
* @returns {Object|null}
*/
Function (anonymous_124)
✓ Was called
getLastTokenOnLine: function(lineNumber, options) {···
options = options || {};

var loc;
var token = this._program.getLastToken();
var currentToken;

while (token) {
loc = token.getLoc();
currentToken = token;
token = token.getPreviousToken();

if (loc.start.line <= lineNumber && loc.end.line >= lineNumber) {

// Since whitespace tokens can contain newlines we need to check
// if position is in the range, not exact match
if (currentToken.isWhitespace && !options.includeWhitespace) {
continue;
}
}

if (loc.start.line === lineNumber || loc.end.line === lineNumber) {
if (currentToken.isComment && !options.includeComments) {
continue;
}

return currentToken;
}
}

return null;
},
getLastTokenOnLine: function(lineNumber, options) {
Branch LogicalExpression
✓ Was returned
options = options || {};
✓ Was returned
options = options || {};
options = options || {};
var loc;
var token = this._program.getLastToken();
var currentToken;
while (token) {
loc = token.getLoc();
currentToken = token;
token = token.getPreviousToken();
Branch IfStatement
✓ Positive was executed (if)
if (loc.start.line <= lineNumber && loc.end.line >= lineNumber) {···

// Since whitespace tokens can contain newlines we need to check
// if position is in the range, not exact match
if (currentToken.isWhitespace && !options.includeWhitespace) {
continue;
}
}
✓ Negative was executed (else)
}···

if (loc.start.line === lineNumber || loc.end.line === lineNumber) {
Branch LogicalExpression
✓ Was returned
if (loc.start.line <= lineNumber && loc.end.line >= lineNumber) {
✓ Was returned
if (loc.start.line <= lineNumber && loc.end.line >= lineNumber) {
if (loc.start.line <= lineNumber && loc.end.line >= lineNumber) {
// Since whitespace tokens can contain newlines we need to check
// if position is in the range, not exact match
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isWhitespace && !options.includeWhitespace) {···
continue;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (currentToken.isWhitespace && !options.includeWhitespace) {
✓ Was returned
if (currentToken.isWhitespace && !options.includeWhitespace) {
if (currentToken.isWhitespace && !options.includeWhitespace) {
continue;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (loc.start.line === lineNumber || loc.end.line === lineNumber) {···
if (currentToken.isComment && !options.includeComments) {
continue;
}

return currentToken;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (loc.start.line === lineNumber || loc.end.line === lineNumber) {
✓ Was returned
if (loc.start.line === lineNumber || loc.end.line === lineNumber) {
if (loc.start.line === lineNumber || loc.end.line === lineNumber) {
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isComment && !options.includeComments) {···
continue;
}
✓ Negative was executed (else)
}···

return currentToken;
Branch LogicalExpression
✓ Was returned
if (currentToken.isComment && !options.includeComments) {
✓ Was returned
if (currentToken.isComment && !options.includeComments) {
if (currentToken.isComment && !options.includeComments) {
continue;
}
return currentToken;
}
}
return null;
},
/**
* Returns which dialect of JS this file supports.
*
* @returns {String}
*/
Function (anonymous_125)
✓ Was called
getDialect: function() {···
if (this._es3) {
return 'es3';
}

return 'es6';
},
getDialect: function() {
Branch IfStatement
✓ Positive was executed (if)
if (this._es3) {···
return 'es3';
}
✓ Negative was executed (else)
}···

return 'es6';
if (this._es3) {
return 'es3';
}
return 'es6';
},
/**
* Returns string representing contents of the file.
*
* @returns {String}
*/
Function (anonymous_126)
✓ Was called
getSource: function() {···
return this._source;
},
getSource: function() {
return this._source;
},
/**
* Returns token program.
*
* @returns {Object}
*/
Function (anonymous_127)
✓ Was called
getTree: function() {···
return this._program || {};
},
getTree: function() {
Branch LogicalExpression
✗ Was not returned
return this._program || {};
✓ Was returned
return this._program || {};
return this._program || {};
},
/**
* Returns comment token list.
*/
Function (anonymous_128)
✓ Was called
getComments: function() {···
var comments = [];
var token = this._program.getFirstToken();
while (token) {
if (token.isComment) {
comments[comments.length] = token;
}
token = token.getNextToken();
}
return comments;
},
getComments: function() {
var comments = [];
var token = this._program.getFirstToken();
while (token) {
Branch IfStatement
✓ Positive was executed (if)
if (token.isComment) {···
comments[comments.length] = token;
}
✓ Negative was executed (else)
}···
token = token.getNextToken();
if (token.isComment) {
comments[comments.length] = token;
}
token = token.getNextToken();
}
return comments;
},
/**
* Returns source filename for this object representation.
*
* @returns {String}
*/
Function (anonymous_129)
✓ Was called
getFilename: function() {···
return this._filename;
},
getFilename: function() {
return this._filename;
},
/**
* Returns array of source lines for the file.
*
* @returns {String[]}
*/
Function (anonymous_130)
✓ Was called
getLines: function() {···
return this._lines;
},
getLines: function() {
return this._lines;
},
/**
* Returns analyzed scope.
*
* @returns {Object}
*/
Function (anonymous_131)
✓ Was called
getScopes: function() {···
if (!this._scopes) {
this._scopes = new ScopesApi(this._program);
}

return this._scopes;
},
getScopes: function() {
Branch IfStatement
✓ Positive was executed (if)
if (!this._scopes) {···
this._scopes = new ScopesApi(this._program);
}
✗ Negative was not executed (else)
}···

return this._scopes;
if (!this._scopes) {
this._scopes = new ScopesApi(this._program);
}
return this._scopes;
},
/**
* Are tokens on the same line.
*
* @param {Element} tokenBefore
* @param {Element} tokenAfter
* @return {Boolean}
*/
Function (anonymous_132)
✗ Was not called
isOnTheSameLine: function(tokenBefore, tokenAfter) {···
if (tokenBefore === tokenAfter) {
return true;
}
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
var currentToken = tokenBefore;
while (currentToken) {
if (currentToken === tokenAfter) {
return true;
}
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {
return false;
}
currentToken = currentToken.getNextToken();
}
return false;
},
isOnTheSameLine: function(tokenBefore, tokenAfter) {
Branch IfStatement
✗ Positive was not executed (if)
if (tokenBefore === tokenAfter) {···
return true;
}
✗ Negative was not executed (else)
}···
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
if (tokenBefore === tokenAfter) {
return true;
}
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
✗ Negative was not returned (: ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
✗ Negative was not returned (: ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
var currentToken = tokenBefore;
while (currentToken) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken === tokenAfter) {···
return true;
}
✗ Negative was not executed (else)
}···
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {
if (currentToken === tokenAfter) {
return true;
}
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {···
return false;
}
✗ Negative was not executed (else)
}···
currentToken = currentToken.getNextToken();
Branch LogicalExpression
✗ Was not returned
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {
✗ Was not returned
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {
if (currentToken !== tokenBefore && currentToken.getNewlineCount() > 0) {
return false;
}
currentToken = currentToken.getNextToken();
}
return false;
},
Function (anonymous_133)
✗ Was not called
getDistanceBetween: function(tokenBefore, tokenAfter) {···
if (tokenBefore === tokenAfter) {
return 0;
}
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
var currentToken = tokenBefore.getNextToken();
var distance = 0;
while (currentToken) {
if (currentToken === tokenAfter) {
break;
}

distance += currentToken.getSourceCodeLength();
currentToken = currentToken.getNextToken();
}
return distance;
},
getDistanceBetween: function(tokenBefore, tokenAfter) {
Branch IfStatement
✗ Positive was not executed (if)
if (tokenBefore === tokenAfter) {···
return 0;
}
✗ Negative was not executed (else)
}···
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
if (tokenBefore === tokenAfter) {
return 0;
}
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
✗ Negative was not returned (: ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
✗ Negative was not returned (: ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
var currentToken = tokenBefore.getNextToken();
var distance = 0;
while (currentToken) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken === tokenAfter) {···
break;
}
✗ Negative was not executed (else)
}···

distance += currentToken.getSourceCodeLength();
if (currentToken === tokenAfter) {
break;
}
distance += currentToken.getSourceCodeLength();
currentToken = currentToken.getNextToken();
}
return distance;
},
Function (anonymous_134)
✗ Was not called
getLineCountBetween: function(tokenBefore, tokenAfter) {···
if (tokenBefore === tokenAfter) {
return 0;
}
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();

var currentToken = tokenBefore.getNextToken();
var lineCount = 0;
while (currentToken) {
if (currentToken === tokenAfter) {
break;
}

lineCount += currentToken.getNewlineCount();
currentToken = currentToken.getNextToken();
}
return lineCount;
},
getLineCountBetween: function(tokenBefore, tokenAfter) {
Branch IfStatement
✗ Positive was not executed (if)
if (tokenBefore === tokenAfter) {···
return 0;
}
✗ Negative was not executed (else)
}···
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
if (tokenBefore === tokenAfter) {
return 0;
}
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
✗ Negative was not returned (: ...)
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
tokenBefore = tokenBefore instanceof Token ? tokenBefore : tokenBefore.getLastToken();
Branch ConditionalExpression
✗ Positive was not returned (? ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
✗ Negative was not returned (: ...)
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
tokenAfter = tokenAfter instanceof Token ? tokenAfter : tokenAfter.getFirstToken();
var currentToken = tokenBefore.getNextToken();
var lineCount = 0;
while (currentToken) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentToken === tokenAfter) {···
break;
}
✗ Negative was not executed (else)
}···

lineCount += currentToken.getNewlineCount();
if (currentToken === tokenAfter) {
break;
}
lineCount += currentToken.getNewlineCount();
currentToken = currentToken.getNextToken();
}
return lineCount;
},
/**
* Returns array of source lines for the file with comments removed.
*
* @returns {Array}
*/
Function (anonymous_135)
✓ Was called
getLinesWithCommentsRemoved: function() {···
var lines = this.getLines().concat();

this.getComments().concat().reverse().forEach(function(comment) {
var loc = comment.getLoc();
var startLine = loc.start.line;
var startCol = loc.start.column;
var endLine = loc.end.line;
var endCol = loc.end.column;
var i = startLine - 1;

if (startLine === endLine) {
// Remove tralling spaces (see gh-1968)
lines[i] = lines[i].replace(/\*\/\s+/, '\*\/');
lines[i] = lines[i].substring(0, startCol) + lines[i].substring(endCol);
} else {
lines[i] = lines[i].substring(0, startCol);
for (var x = i + 1; x < endLine - 1; x++) {
lines[x] = '';
}

lines[x] = lines[x].substring(endCol);
}
});

return lines;
},
getLinesWithCommentsRemoved: function() {
var lines = this.getLines().concat();
Function (anonymous_136)
✓ Was called
this.getComments().concat().reverse().forEach(function(comment) {···
var loc = comment.getLoc();
var startLine = loc.start.line;
var startCol = loc.start.column;
var endLine = loc.end.line;
var endCol = loc.end.column;
var i = startLine - 1;

if (startLine === endLine) {
// Remove tralling spaces (see gh-1968)
lines[i] = lines[i].replace(/\*\/\s+/, '\*\/');
lines[i] = lines[i].substring(0, startCol) + lines[i].substring(endCol);
} else {
lines[i] = lines[i].substring(0, startCol);
for (var x = i + 1; x < endLine - 1; x++) {
lines[x] = '';
}

lines[x] = lines[x].substring(endCol);
}
});
this.getComments().concat().reverse().forEach(function(comment) {
var loc = comment.getLoc();
var startLine = loc.start.line;
var startCol = loc.start.column;
var endLine = loc.end.line;
var endCol = loc.end.column;
var i = startLine - 1;
Branch IfStatement
✓ Positive was executed (if)
if (startLine === endLine) {···
// Remove tralling spaces (see gh-1968)
lines[i] = lines[i].replace(/\*\/\s+/, '\*\/');
lines[i] = lines[i].substring(0, startCol) + lines[i].substring(endCol);
} else {
✓ Negative was executed (else)
} else {···
lines[i] = lines[i].substring(0, startCol);
for (var x = i + 1; x < endLine - 1; x++) {
lines[x] = '';
}

lines[x] = lines[x].substring(endCol);
}
if (startLine === endLine) {
// Remove tralling spaces (see gh-1968)
lines[i] = lines[i].replace(/\*\/\s+/, '\*\/');
lines[i] = lines[i].substring(0, startCol) + lines[i].substring(endCol);
} else {
lines[i] = lines[i].substring(0, startCol);
for (var x = i + 1; x < endLine - 1; x++) {
lines[x] = '';
}
lines[x] = lines[x].substring(endCol);
}
});
return lines;
},
/**
* Renders JS-file sources using token list.
*
* @returns {String}
*/
Function (anonymous_137)
✓ Was called
render: function() {···
return this._program.getSourceCode();
},
render: function() {
return this._program.getSourceCode();
},
/**
* Returns list of parse errors.
*
* @returns {Error[]}
*/
Function (anonymous_138)
✓ Was called
getParseErrors: function() {···
return this._parseErrors;
}
getParseErrors: function() {
return this._parseErrors;
}
};
module.exports = JsFile;
tree-iterator.js
var estraverse = require('estraverse');
var VISITOR_KEYS = require('cst').visitorKeys;
Function iterate
✓ Was called
module.exports.iterate = function iterate(node, cb) {···
if ('type' in node) {
estraverse.traverse(node, {
enter: function(node, parent) {
var parentCollection = [];

// parentCollection support
var path = this.path();
if (path) {
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}

parentCollection = parent[collectionKey];
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}

if (cb(node, parent, parentCollection) === false) {
return estraverse.VisitorOption.Skip;
}
},
keys: VISITOR_KEYS
});
}
};
module.exports.iterate = function iterate(node, cb) {
Branch IfStatement
✓ Positive was executed (if)
if ('type' in node) {···
estraverse.traverse(node, {
enter: function(node, parent) {
var parentCollection = [];

// parentCollection support
var path = this.path();
if (path) {
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}

parentCollection = parent[collectionKey];
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}

if (cb(node, parent, parentCollection) === false) {
return estraverse.VisitorOption.Skip;
}
},
keys: VISITOR_KEYS
});
}
✓ Negative was executed (else)
}···
};
if ('type' in node) {
estraverse.traverse(node, {
Function (anonymous_140)
✓ Was called
enter: function(node, parent) {···
var parentCollection = [];

// parentCollection support
var path = this.path();
if (path) {
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}

parentCollection = parent[collectionKey];
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}

if (cb(node, parent, parentCollection) === false) {
return estraverse.VisitorOption.Skip;
}
},
enter: function(node, parent) {
var parentCollection = [];
// parentCollection support
var path = this.path();
Branch IfStatement
✓ Positive was executed (if)
if (path) {···
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}

parentCollection = parent[collectionKey];
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}
✓ Negative was executed (else)
}···

if (cb(node, parent, parentCollection) === false) {
if (path) {
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
Branch IfStatement
✓ Positive was executed (if)
if (typeof pathElement === 'string') {···
collectionKey = pathElement;
break;
}
✓ Negative was executed (else)
}···
}
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}
parentCollection = parent[collectionKey];
Branch IfStatement
✓ Positive was executed (if)
if (!Array.isArray(parentCollection)) {···
parentCollection = [parentCollection];
}
✓ Negative was executed (else)
}···
}
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}
Branch IfStatement
✓ Positive was executed (if)
if (cb(node, parent, parentCollection) === false) {···
return estraverse.VisitorOption.Skip;
}
✓ Negative was executed (else)
}···
},
if (cb(node, parent, parentCollection) === false) {
return estraverse.VisitorOption.Skip;
}
},
keys: VISITOR_KEYS
});
}
};
token-index.js
var assign = require('lodash').assign;
var BLOCK_REGEXP = /^\s*(?:jscs\s*:\s*(en|dis)able)(.*)/;
var LINE_REGEXP = /^\s*(?:jscs\s*:\s*ignore)(.*)/;
/**
* Parses rule names in enable/disable/ignore statements.
*
* @param {String} text
* @param {Boolean} enabled
* @returns {Object}
*/
Function parseRuleNames
✓ Was called
function parseRuleNames(text, enabled) {···
text = text.trim();

if (!text) {
return {'*': enabled};
}

return text.split(',').reduce(function(result, ruleName) {
ruleName = ruleName.trim();
if (ruleName) {
result[ruleName] = enabled;
}
return result;
}, {});
}
function parseRuleNames(text, enabled) {
text = text.trim();
Branch IfStatement
✓ Positive was executed (if)
if (!text) {···
return {'*': enabled};
}
✓ Negative was executed (else)
}···

return text.split(',').reduce(function(result, ruleName) {
if (!text) {
return {'*': enabled};
}
Function (anonymous_142)
✓ Was called
return text.split(',').reduce(function(result, ruleName) {···
ruleName = ruleName.trim();
if (ruleName) {
result[ruleName] = enabled;
}
return result;
}, {});
return text.split(',').reduce(function(result, ruleName) {
ruleName = ruleName.trim();
Branch IfStatement
✓ Positive was executed (if)
if (ruleName) {···
result[ruleName] = enabled;
}
✓ Negative was executed (else)
}···
return result;
if (ruleName) {
result[ruleName] = enabled;
}
return result;
}, {});
}
/**
* Pragma index implementation.
* Checks if rule is enabled or disabled for the specified element.
*
* @param {Element} firstToken
* @constructor
*/
Function TokenIndex
✓ Was called
function TokenIndex(firstToken) {···
this._buildIndex(firstToken);
}
function TokenIndex(firstToken) {
this._buildIndex(firstToken);
}
/**
* Builds pragma index.
*
* @param {Element} firstToken
* @private
*/
Function (anonymous_144)
✓ Was called
TokenIndex.prototype._buildIndex = function(firstToken) {···
this._hasPragmas = false;

var tokens = [];
var index = [];
var positions = [];
var currentPosition = 0;
var currentToken = firstToken;
var lastBlockState = {'*': true};
var tokenState;
var previousLoc = {line: 1, column: 0};

while (currentToken) {
tokens.push(currentToken);
currentToken.__loc = previousLoc;

var newlineCount = currentToken.getNewlineCount();
if (newlineCount > 0) {
var lines = currentToken.getSourceCodeLines();
previousLoc = {
line: previousLoc.line + newlineCount,
column: lines[lines.length - 1].length
};
} else {
previousLoc = {
line: previousLoc.line,
column: previousLoc.column + currentToken.getSourceCodeLength()
};
}

if (currentToken.isComment) {
var value = currentToken.value;
var blockMatch = BLOCK_REGEXP.exec(value);
if (blockMatch) {
this._hasPragmas = true;
lastBlockState = assign({}, lastBlockState, parseRuleNames(blockMatch[2], blockMatch[1] === 'en'));
tokenState = lastBlockState;
} else {
var lineMatch = LINE_REGEXP.exec(value);
if (lineMatch) {
this._hasPragmas = true;
var ignoreState = parseRuleNames(lineMatch[1], false);
index.push(null);
var ignoreToken = currentToken.getPreviousToken();
var i = index.length - 1;
while (ignoreToken) {
i--;
index[i] = assign({}, index[i], ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getPreviousToken();
}
ignoreToken = currentToken.getNextToken();
while (ignoreToken) {
index.push(ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getNextToken();
}
tokenState = assign({}, lastBlockState, ignoreState);
} else {
tokenState = lastBlockState;
}
}
} else {
tokenState = lastBlockState;
}

if (index[currentPosition]) {
tokenState = assign({}, tokenState, index[currentPosition]);
}

index[currentPosition] = tokenState;
currentPosition++;

currentToken = currentToken.getNextToken();
}
this._tokens = tokens;
this._index = index;
this._positions = positions;
};
TokenIndex.prototype._buildIndex = function(firstToken) {
this._hasPragmas = false;
var tokens = [];
var index = [];
var positions = [];
var currentPosition = 0;
var currentToken = firstToken;
var lastBlockState = {'*': true};
var tokenState;
var previousLoc = {line: 1, column: 0};
while (currentToken) {
tokens.push(currentToken);
currentToken.__loc = previousLoc;
var newlineCount = currentToken.getNewlineCount();
Branch IfStatement
✓ Positive was executed (if)
if (newlineCount > 0) {···
var lines = currentToken.getSourceCodeLines();
previousLoc = {
line: previousLoc.line + newlineCount,
column: lines[lines.length - 1].length
};
} else {
✓ Negative was executed (else)
} else {···
previousLoc = {
line: previousLoc.line,
column: previousLoc.column + currentToken.getSourceCodeLength()
};
}
if (newlineCount > 0) {
var lines = currentToken.getSourceCodeLines();
previousLoc = {
line: previousLoc.line + newlineCount,
column: lines[lines.length - 1].length
};
} else {
previousLoc = {
line: previousLoc.line,
column: previousLoc.column + currentToken.getSourceCodeLength()
};
}
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isComment) {···
var value = currentToken.value;
var blockMatch = BLOCK_REGEXP.exec(value);
if (blockMatch) {
this._hasPragmas = true;
lastBlockState = assign({}, lastBlockState, parseRuleNames(blockMatch[2], blockMatch[1] === 'en'));
tokenState = lastBlockState;
} else {
var lineMatch = LINE_REGEXP.exec(value);
if (lineMatch) {
this._hasPragmas = true;
var ignoreState = parseRuleNames(lineMatch[1], false);
index.push(null);
var ignoreToken = currentToken.getPreviousToken();
var i = index.length - 1;
while (ignoreToken) {
i--;
index[i] = assign({}, index[i], ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getPreviousToken();
}
ignoreToken = currentToken.getNextToken();
while (ignoreToken) {
index.push(ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getNextToken();
}
tokenState = assign({}, lastBlockState, ignoreState);
} else {
tokenState = lastBlockState;
}
}
} else {
✓ Negative was executed (else)
} else {···
tokenState = lastBlockState;
}
if (currentToken.isComment) {
var value = currentToken.value;
var blockMatch = BLOCK_REGEXP.exec(value);
Branch IfStatement
✓ Positive was executed (if)
if (blockMatch) {···
this._hasPragmas = true;
lastBlockState = assign({}, lastBlockState, parseRuleNames(blockMatch[2], blockMatch[1] === 'en'));
tokenState = lastBlockState;
} else {
✓ Negative was executed (else)
} else {···
var lineMatch = LINE_REGEXP.exec(value);
if (lineMatch) {
this._hasPragmas = true;
var ignoreState = parseRuleNames(lineMatch[1], false);
index.push(null);
var ignoreToken = currentToken.getPreviousToken();
var i = index.length - 1;
while (ignoreToken) {
i--;
index[i] = assign({}, index[i], ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getPreviousToken();
}
ignoreToken = currentToken.getNextToken();
while (ignoreToken) {
index.push(ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getNextToken();
}
tokenState = assign({}, lastBlockState, ignoreState);
} else {
tokenState = lastBlockState;
}
}
if (blockMatch) {
this._hasPragmas = true;
lastBlockState = assign({}, lastBlockState, parseRuleNames(blockMatch[2], blockMatch[1] === 'en'));
tokenState = lastBlockState;
} else {
var lineMatch = LINE_REGEXP.exec(value);
Branch IfStatement
✓ Positive was executed (if)
if (lineMatch) {···
this._hasPragmas = true;
var ignoreState = parseRuleNames(lineMatch[1], false);
index.push(null);
var ignoreToken = currentToken.getPreviousToken();
var i = index.length - 1;
while (ignoreToken) {
i--;
index[i] = assign({}, index[i], ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getPreviousToken();
}
ignoreToken = currentToken.getNextToken();
while (ignoreToken) {
index.push(ignoreState);
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getNextToken();
}
tokenState = assign({}, lastBlockState, ignoreState);
} else {
✓ Negative was executed (else)
} else {···
tokenState = lastBlockState;
}
if (lineMatch) {
this._hasPragmas = true;
var ignoreState = parseRuleNames(lineMatch[1], false);
index.push(null);
var ignoreToken = currentToken.getPreviousToken();
var i = index.length - 1;
while (ignoreToken) {
i--;
index[i] = assign({}, index[i], ignoreState);
Branch IfStatement
✓ Positive was executed (if)
if (ignoreToken.getNewlineCount() > 0) {···
break;
}
✓ Negative was executed (else)
}···
ignoreToken = ignoreToken.getPreviousToken();
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getPreviousToken();
}
ignoreToken = currentToken.getNextToken();
while (ignoreToken) {
index.push(ignoreState);
Branch IfStatement
✓ Positive was executed (if)
if (ignoreToken.getNewlineCount() > 0) {···
break;
}
✓ Negative was executed (else)
}···
ignoreToken = ignoreToken.getNextToken();
if (ignoreToken.getNewlineCount() > 0) {
break;
}
ignoreToken = ignoreToken.getNextToken();
}
tokenState = assign({}, lastBlockState, ignoreState);
} else {
tokenState = lastBlockState;
}
}
} else {
tokenState = lastBlockState;
}
Branch IfStatement
✓ Positive was executed (if)
if (index[currentPosition]) {···
tokenState = assign({}, tokenState, index[currentPosition]);
}
✓ Negative was executed (else)
}···

index[currentPosition] = tokenState;
if (index[currentPosition]) {
tokenState = assign({}, tokenState, index[currentPosition]);
}
index[currentPosition] = tokenState;
currentPosition++;
currentToken = currentToken.getNextToken();
}
this._tokens = tokens;
this._index = index;
this._positions = positions;
};
/**
* Checks if rule whether rule is enabled for the specified element.
*
* @param {String} ruleName
* @param {Element} element
* @returns {Boolean}
*/
Function (anonymous_145)
✓ Was called
TokenIndex.prototype.isRuleEnabled = function(ruleName, element) {···
if (!this._hasPragmas) {
return true;
}
var pos = this._tokens.indexOf(element.getFirstToken());
if (pos !== -1) {
var state = this._index[pos];
if (ruleName in state) {
return state[ruleName];
}

return state['*'];
}

return true;
};
TokenIndex.prototype.isRuleEnabled = function(ruleName, element) {
Branch IfStatement
✓ Positive was executed (if)
if (!this._hasPragmas) {···
return true;
}
✓ Negative was executed (else)
}···
var pos = this._tokens.indexOf(element.getFirstToken());
if (!this._hasPragmas) {
return true;
}
var pos = this._tokens.indexOf(element.getFirstToken());
Branch IfStatement
✓ Positive was executed (if)
if (pos !== -1) {···
var state = this._index[pos];
if (ruleName in state) {
return state[ruleName];
}

return state['*'];
}
✗ Negative was not executed (else)
}···

return true;
if (pos !== -1) {
var state = this._index[pos];
Branch IfStatement
✓ Positive was executed (if)
if (ruleName in state) {···
return state[ruleName];
}
✓ Negative was executed (else)
}···

return state['*'];
if (ruleName in state) {
return state[ruleName];
}
return state['*'];
}
return true;
};
/**
* Return calculated element location.
*
* @param {Element} element
* @returns {Object}
*/
Function (anonymous_146)
✗ Was not called
TokenIndex.prototype.getElementLoc = function(element) {···
return element.getFirstToken().__loc || {
line: 1,
column: 0
};
};
TokenIndex.prototype.getElementLoc = function(element) {
Branch LogicalExpression
✗ Was not returned
return element.getFirstToken().__loc || {···
line: 1,
column: 0
};
✗ Was not returned
return element.getFirstToken().__loc || {
return element.getFirstToken().__loc || {
line: 1,
column: 0
};
};
module.exports = TokenIndex;
configuration.js
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var minimatch = require('minimatch');
var defaults = {
cwd: '.',
maxErrors: 50
};
var _ = require('lodash');
var BUILTIN_OPTIONS = {
plugins: true,
preset: true,
excludeFiles: true,
additionalRules: true,
fileExtensions: true,
extract: true,
maxErrors: true,
configPath: true,
es3: true,
errorFilter: true,
fix: true
};
/**
* JSCS Configuration.
* Browser/Rhino-compatible.
*
* @name Configuration
*/
Function Configuration
✓ Was called
function Configuration() {···
/**
* List of the registered (not used) presets.
*
* @protected
* @type {Object}
*/
this._presets = {};

/**
* Name of the preset (if used).
*
* @protected
* @type {String|null}
*/
this._presetName = null;

/**
* List of loaded presets.
*
* @protected
* @type {String|null}
*/
this._loadedPresets = [];

/**
* List of rules instances.
*
* @protected
* @type {Object}
*/
this._rules = {};

/**
* List of configurated rule instances.
*
* @protected
* @type {Object}
*/
this._ruleSettings = {};

/**
* List of configured rules.
*
* @protected
* @type {Array}
*/
this._configuredRules = [];

/**
* List of unsupported rules.
*
* @protected
* @type {Array}
*/
this._unsupportedRuleNames = [];

/**
* File extensions that would be checked.
*
* @protected
* @type {Array}
*/
this._fileExtensions = [];

/**
* List of defined options (not complete).
*
* @protected
* @type {Array}
*/
this._definedOptions = [];

/**
* Default file extensions that would be checked.
*
* @protected
* @type {Array}
*/
this._defaultFileExtensions = ['.js'];

/**
* Exclusion masks.
*
* @protected
* @type {Array}
*/
this._excludedFileMasks = [];

/**
* Default exclusion masks, will be rewritten if user has their own masks.
*
* @protected
* @type {Array}
*/
this._defaultExcludedFileMasks = ['.git/**', 'node_modules/**'];

/**
* List of existing files that falls under exclusion masks.
*
* @protected
* @type {Array}
*/
this._excludedFileMatchers = [];

/**
* Extraction masks.
*
* @protected
* @type {Array}
*/
this._extractFileMasks = [];

/**
* Default extractions masks.
*
* @protected
* @type {Array}
*/
this._defaultExtractFileMasks = ['**/*.+(htm|html|xhtml)'];

/**
* List of file matchers from which to extract JavaScript.
*
* @protected
* @type {Array}
*/
this._extractFileMatchers = [];

/**
* Maxixum amount of error that would be reportered.
*
* @protected
* @type {Number}
*/
this._maxErrors = defaults.maxErrors;

/**
* JSCS CWD.
*
* @protected
* @type {String}
*/
this._basePath = defaults.cwd;

/**
* List of overrided options (usually from CLI).
*
* @protected
* @type {Object}
*/
this._overrides = {};

/**
* Is "ES3" mode enabled?.
*
* @protected
* @type {Boolean}
*/
this._es3Enabled = false;

/**
* A filter function that determines whether or not to report an error.
*
* @protected
* @type {Function|null}
*/
this._errorFilter = null;
}
function Configuration() {
/**
* List of the registered (not used) presets.
*
* @protected
* @type {Object}
*/
this._presets = {};
/**
* Name of the preset (if used).
*
* @protected
* @type {String|null}
*/
this._presetName = null;
/**
* List of loaded presets.
*
* @protected
* @type {String|null}
*/
this._loadedPresets = [];
/**
* List of rules instances.
*
* @protected
* @type {Object}
*/
this._rules = {};
/**
* List of configurated rule instances.
*
* @protected
* @type {Object}
*/
this._ruleSettings = {};
/**
* List of configured rules.
*
* @protected
* @type {Array}
*/
this._configuredRules = [];
/**
* List of unsupported rules.
*
* @protected
* @type {Array}
*/
this._unsupportedRuleNames = [];
/**
* File extensions that would be checked.
*
* @protected
* @type {Array}
*/
this._fileExtensions = [];
/**
* List of defined options (not complete).
*
* @protected
* @type {Array}
*/
this._definedOptions = [];
/**
* Default file extensions that would be checked.
*
* @protected
* @type {Array}
*/
this._defaultFileExtensions = ['.js'];
/**
* Exclusion masks.
*
* @protected
* @type {Array}
*/
this._excludedFileMasks = [];
/**
* Default exclusion masks, will be rewritten if user has their own masks.
*
* @protected
* @type {Array}
*/
this._defaultExcludedFileMasks = ['.git/**', 'node_modules/**'];
/**
* List of existing files that falls under exclusion masks.
*
* @protected
* @type {Array}
*/
this._excludedFileMatchers = [];
/**
* Extraction masks.
*
* @protected
* @type {Array}
*/
this._extractFileMasks = [];
/**
* Default extractions masks.
*
* @protected
* @type {Array}
*/
this._defaultExtractFileMasks = ['**/*.+(htm|html|xhtml)'];
/**
* List of file matchers from which to extract JavaScript.
*
* @protected
* @type {Array}
*/
this._extractFileMatchers = [];
/**
* Maxixum amount of error that would be reportered.
*
* @protected
* @type {Number}
*/
this._maxErrors = defaults.maxErrors;
/**
* JSCS CWD.
*
* @protected
* @type {String}
*/
this._basePath = defaults.cwd;
/**
* List of overrided options (usually from CLI).
*
* @protected
* @type {Object}
*/
this._overrides = {};
/**
* Is "ES3" mode enabled?.
*
* @protected
* @type {Boolean}
*/
this._es3Enabled = false;
/**
* A filter function that determines whether or not to report an error.
*
* @protected
* @type {Function|null}
*/
this._errorFilter = null;
}
/**
* Load settings from a configuration.
*
* @param {Object} config
*/
Function (anonymous_148)
✓ Was called
Configuration.prototype.load = function(config) {···

// Load all the options
this._processConfig(config);

// Load defaults if they weren't set
this._loadDefaults(config);

// Load and apply all the rules
this._useRules();
};
Configuration.prototype.load = function(config) {
// Load all the options
this._processConfig(config);
// Load defaults if they weren't set
this._loadDefaults(config);
// Load and apply all the rules
this._useRules();
};
/**
* Load default values for options which were not defined
*
* @private
*/
Function (anonymous_149)
✓ Was called
Configuration.prototype._loadDefaults = function() {···
if (!this._isDefined('excludeFiles')) {
this._loadExcludedFiles(this._defaultExcludedFileMasks);
}

if (!this._isDefined('fileExtensions')) {
this._loadFileExtensions(this._defaultFileExtensions);
}
};
Configuration.prototype._loadDefaults = function() {
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('excludeFiles')) {···
this._loadExcludedFiles(this._defaultExcludedFileMasks);
}
✓ Negative was executed (else)
}···

if (!this._isDefined('fileExtensions')) {
if (!this._isDefined('excludeFiles')) {
this._loadExcludedFiles(this._defaultExcludedFileMasks);
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('fileExtensions')) {···
this._loadFileExtensions(this._defaultFileExtensions);
}
✓ Negative was executed (else)
}···
};
if (!this._isDefined('fileExtensions')) {
this._loadFileExtensions(this._defaultFileExtensions);
}
};
/**
* Returns resulting configuration after preset is applied and options are processed.
*
* @return {Object}
*/
Function (anonymous_150)
✓ Was called
Configuration.prototype.getProcessedConfig = function() {···
var result = {};
Object.keys(this._ruleSettings).forEach(function(key) {
result[key] = this._ruleSettings[key];
}, this);
result.excludeFiles = this._excludedFileMasks;
result.fileExtensions = this._fileExtensions;
result.extract = this._extractFileMasks;
result.maxErrors = this._maxErrors;
result.preset = this._presetName;
result.es3 = this._es3Enabled;
result.errorFilter = this._errorFilter;
return result;
};
Configuration.prototype.getProcessedConfig = function() {
var result = {};
Function (anonymous_151)
✓ Was called
Object.keys(this._ruleSettings).forEach(function(key) {···
result[key] = this._ruleSettings[key];
}, this);
Object.keys(this._ruleSettings).forEach(function(key) {
result[key] = this._ruleSettings[key];
}, this);
result.excludeFiles = this._excludedFileMasks;
result.fileExtensions = this._fileExtensions;
result.extract = this._extractFileMasks;
result.maxErrors = this._maxErrors;
result.preset = this._presetName;
result.es3 = this._es3Enabled;
result.errorFilter = this._errorFilter;
return result;
};
/**
* Returns list of configured rules.
*
* @returns {Rule[]}
*/
Function (anonymous_152)
✓ Was called
Configuration.prototype.getConfiguredRules = function() {···
return this._configuredRules;
};
Configuration.prototype.getConfiguredRules = function() {
return this._configuredRules;
};
/**
* Returns configured rule.
*
* @returns {Rule | null}
*/
Function (anonymous_153)
✓ Was called
Configuration.prototype.getConfiguredRule = function(name) {···
return this._configuredRules.filter(function(rule) {
return rule.getOptionName() === name;
})[0] || null;
};
Configuration.prototype.getConfiguredRule = function(name) {
Function (anonymous_154)
✓ Was called
return this._configuredRules.filter(function(rule) {···
return rule.getOptionName() === name;
})[0] || null;
Branch LogicalExpression
✓ Was returned
})[0] || null;
✓ Was returned
return this._configuredRules.filter(function(rule) {···
return rule.getOptionName() === name;
})[0] || null;
return this._configuredRules.filter(function(rule) {
return rule.getOptionName() === name;
})[0] || null;
};
/**
* Returns the list of unsupported rule names.
*
* @return {String[]}
*/
Function (anonymous_155)
✓ Was called
Configuration.prototype.getUnsupportedRuleNames = function() {···
return this._unsupportedRuleNames;
};
Configuration.prototype.getUnsupportedRuleNames = function() {
return this._unsupportedRuleNames;
};
/**
* Returns excluded file mask list.
*
* @returns {String[]}
*/
Function (anonymous_156)
✓ Was called
Configuration.prototype.getExcludedFileMasks = function() {···
return this._excludedFileMasks;
};
Configuration.prototype.getExcludedFileMasks = function() {
return this._excludedFileMasks;
};
/**
* Returns `true` if specified file path is excluded.
*
* @param {String} filePath
* @returns {Boolean}
*/
Function (anonymous_157)
✓ Was called
Configuration.prototype.isFileExcluded = function(filePath) {···
filePath = path.resolve(filePath);

return this._excludedFileMatchers.some(function(matcher) {
return matcher.match(filePath);
});
};
Configuration.prototype.isFileExcluded = function(filePath) {
filePath = path.resolve(filePath);
Function (anonymous_158)
✓ Was called
return this._excludedFileMatchers.some(function(matcher) {···
return matcher.match(filePath);
});
return this._excludedFileMatchers.some(function(matcher) {
return matcher.match(filePath);
});
};
/**
* Returns true if the file extension matches a file extension to process.
*
* @returns {Boolean}
*/
Function (anonymous_159)
✗ Was not called
Configuration.prototype.hasCorrectExtension = function(testPath) {···
var extension = path.extname(testPath).toLowerCase();
var basename = path.basename(testPath).toLowerCase();
var fileExtensions = this.getFileExtensions();

return !(
fileExtensions.indexOf(extension) < 0 &&
fileExtensions.indexOf(basename) < 0 &&
fileExtensions.indexOf('*') < 0
);
};
Configuration.prototype.hasCorrectExtension = function(testPath) {
var extension = path.extname(testPath).toLowerCase();
var basename = path.basename(testPath).toLowerCase();
var fileExtensions = this.getFileExtensions();
return !(
Branch LogicalExpression
✗ Was not returned
fileExtensions.indexOf('*') < 0
✗ Was not returned
fileExtensions.indexOf(extension) < 0 &&···
fileExtensions.indexOf(basename) < 0 &&
Branch LogicalExpression
✗ Was not returned
fileExtensions.indexOf(basename) < 0 &&
✗ Was not returned
fileExtensions.indexOf(extension) < 0 &&
fileExtensions.indexOf(extension) < 0 &&
fileExtensions.indexOf(basename) < 0 &&
fileExtensions.indexOf('*') < 0
);
};
/**
* Returns file extension list.
*
* @returns {String[]}
*/
Function (anonymous_160)
✓ Was called
Configuration.prototype.getFileExtensions = function() {···
return this._fileExtensions;
};
Configuration.prototype.getFileExtensions = function() {
return this._fileExtensions;
};
/**
* Returns extract file masks.
*
* @returns {String[]}
*/
Function (anonymous_161)
✓ Was called
Configuration.prototype.getExtractFileMasks = function() {···
return this._extractFileMasks;
};
Configuration.prototype.getExtractFileMasks = function() {
return this._extractFileMasks;
};
/**
* Should filePath to be extracted?
*
* @returns {Boolean}
*/
Function (anonymous_162)
✓ Was called
Configuration.prototype.shouldExtractFile = function(filePath) {···
filePath = path.resolve(filePath);
return this._extractFileMatchers.some(function(matcher) {
return matcher.match(filePath);
});
};
Configuration.prototype.shouldExtractFile = function(filePath) {
filePath = path.resolve(filePath);
Function (anonymous_163)
✓ Was called
return this._extractFileMatchers.some(function(matcher) {···
return matcher.match(filePath);
});
return this._extractFileMatchers.some(function(matcher) {
return matcher.match(filePath);
});
};
/**
* Returns maximal error count.
*
* @returns {Number|null}
*/
Function (anonymous_164)
✓ Was called
Configuration.prototype.getMaxErrors = function() {···
return this._maxErrors;
};
Configuration.prototype.getMaxErrors = function() {
return this._maxErrors;
};
/**
* Getter "fix" option value.
*
* @return {Boolean}
*/
Function (anonymous_165)
✓ Was called
Configuration.prototype.getFix = function() {···
return !!this._fix;
};
Configuration.prototype.getFix = function() {
return !!this._fix;
};
/**
* Returns `true` if `es3` option is enabled.
*
* @returns {Boolean}
*/
Function (anonymous_166)
✓ Was called
Configuration.prototype.isES3Enabled = function() {···
return this._es3Enabled;
};
Configuration.prototype.isES3Enabled = function() {
return this._es3Enabled;
};
/**
* Returns the loaded error filter.
*
* @returns {Function|null}
*/
Function (anonymous_167)
✓ Was called
Configuration.prototype.getErrorFilter = function() {···
return this._errorFilter;
};
Configuration.prototype.getErrorFilter = function() {
return this._errorFilter;
};
/**
* Returns base path.
*
* @returns {String}
*/
Function (anonymous_168)
✓ Was called
Configuration.prototype.getBasePath = function() {···
return this._basePath;
};
Configuration.prototype.getBasePath = function() {
return this._basePath;
};
/**
* Overrides specified settings.
*
* @param {String} overrides
*/
Function (anonymous_169)
✓ Was called
Configuration.prototype.override = function(overrides) {···
Object.keys(overrides).forEach(function(key) {
this._overrides[key] = overrides[key];
}, this);
};
Configuration.prototype.override = function(overrides) {
Function (anonymous_170)
✓ Was called
Object.keys(overrides).forEach(function(key) {···
this._overrides[key] = overrides[key];
}, this);
Object.keys(overrides).forEach(function(key) {
this._overrides[key] = overrides[key];
}, this);
};
/**
* returns options, but not rules, from the provided config
*
* @param {Object} config
* @returns {Object}
*/
Function (anonymous_171)
✓ Was called
Configuration.prototype._getOptionsFromConfig = function(config) {···
return Object.keys(config).reduce(function(options, key) {
if (BUILTIN_OPTIONS[key]) {
options[key] = config[key];
}
return options;
}, {});
};
Configuration.prototype._getOptionsFromConfig = function(config) {
Function (anonymous_172)
✓ Was called
return Object.keys(config).reduce(function(options, key) {···
if (BUILTIN_OPTIONS[key]) {
options[key] = config[key];
}
return options;
}, {});
return Object.keys(config).reduce(function(options, key) {
Branch IfStatement
✓ Positive was executed (if)
if (BUILTIN_OPTIONS[key]) {···
options[key] = config[key];
}
✓ Negative was executed (else)
}···
return options;
if (BUILTIN_OPTIONS[key]) {
options[key] = config[key];
}
return options;
}, {});
};
Function (anonymous_173)
✓ Was called
Configuration.prototype._errorOnRemovedOptions = function(config) {···
var errors = ['Config values to remove in 3.0:'];

if (config.hasOwnProperty('esprima')) {
errors.push('The `esprima` option since CST uses babylon (the babel parser) under the hood');
}

if (config.hasOwnProperty('esprimaOptions')) {
errors.push('The `esprimaOptions` option.');
}

if (config.hasOwnProperty('esnext')) {
errors.push('The `esnext` option is enabled by default.');
}

if (config.hasOwnProperty('verbose')) {
errors.push('The `verbose` option is enabled by default.');
}

if (errors.length > 1) {
throw new Error(errors.join('\n'));
}
};
Configuration.prototype._errorOnRemovedOptions = function(config) {
var errors = ['Config values to remove in 3.0:'];
Branch IfStatement
✓ Positive was executed (if)
if (config.hasOwnProperty('esprima')) {···
errors.push('The `esprima` option since CST uses babylon (the babel parser) under the hood');
}
✓ Negative was executed (else)
}···

if (config.hasOwnProperty('esprimaOptions')) {
if (config.hasOwnProperty('esprima')) {
errors.push('The `esprima` option since CST uses babylon (the babel parser) under the hood');
}
Branch IfStatement
✓ Positive was executed (if)
if (config.hasOwnProperty('esprimaOptions')) {···
errors.push('The `esprimaOptions` option.');
}
✓ Negative was executed (else)
}···

if (config.hasOwnProperty('esnext')) {
if (config.hasOwnProperty('esprimaOptions')) {
errors.push('The `esprimaOptions` option.');
}
Branch IfStatement
✓ Positive was executed (if)
if (config.hasOwnProperty('esnext')) {···
errors.push('The `esnext` option is enabled by default.');
}
✓ Negative was executed (else)
}···

if (config.hasOwnProperty('verbose')) {
if (config.hasOwnProperty('esnext')) {
errors.push('The `esnext` option is enabled by default.');
}
Branch IfStatement
✓ Positive was executed (if)
if (config.hasOwnProperty('verbose')) {···
errors.push('The `verbose` option is enabled by default.');
}
✓ Negative was executed (else)
}···

if (errors.length > 1) {
if (config.hasOwnProperty('verbose')) {
errors.push('The `verbose` option is enabled by default.');
}
Branch IfStatement
✓ Positive was executed (if)
if (errors.length > 1) {···
throw new Error(errors.join('\n'));
}
✓ Negative was executed (else)
}···
};
if (errors.length > 1) {
throw new Error(errors.join('\n'));
}
};
/**
* Processes configuration and returns config options.
*
* @param {Object} config
*/
Function (anonymous_174)
✓ Was called
Configuration.prototype._processConfig = function(config) {···
var overrides = this._overrides;
var currentConfig = {};

// Copy configuration so original config would be intact
copyConfiguration(config, currentConfig);

// Override the properties
copyConfiguration(overrides, currentConfig);

this._errorOnRemovedOptions(currentConfig);

// NOTE: options is a separate object to ensure that future options must be added
// to BUILTIN_OPTIONS to work, which also assures they aren't mistaken for a rule
var options = this._getOptionsFromConfig(currentConfig);

// Base path
if (this._basePath === defaults.cwd && options.configPath) {
assert(
typeof options.configPath === 'string',
'`configPath` option requires string value'
);
this._basePath = path.dirname(options.configPath);
}

if (options.hasOwnProperty('plugins')) {
assert(Array.isArray(options.plugins), '`plugins` option requires array value');
options.plugins.forEach(function(plugin) {
this._loadPlugin(plugin, options.configPath);
}, this);

if (!this._isDefined('plugins')) {
this._definedOptions.push('plugins');
}
}

if (options.hasOwnProperty('additionalRules')) {
assert(Array.isArray(options.additionalRules), '`additionalRules` option requires array value');
options.additionalRules.forEach(function(rule) {
this._loadAdditionalRule(rule, options.configPath);
}, this);

if (!this._isDefined('additionalRules')) {
this._definedOptions.push('additionalRules');
}
}

if (options.hasOwnProperty('extract')) {
this._loadExtract(options.extract);
}

if (options.hasOwnProperty('fileExtensions')) {
this._loadFileExtensions(options.fileExtensions);
}

if (options.hasOwnProperty('excludeFiles')) {
this._loadExcludedFiles(options.excludeFiles);
}

if (options.hasOwnProperty('fix')) {
this._loadFix(options.fix);
}

this._loadMaxError(options);

if (options.hasOwnProperty('es3')) {
this._loadES3(options.es3);
}

if (options.hasOwnProperty('errorFilter')) {
this._loadErrorFilter(options.errorFilter, options.configPath);
}

// Apply presets
if (options.hasOwnProperty('preset')) {
this._loadPreset(options.preset, options.configPath);
}

this._loadRules(currentConfig);
};
Configuration.prototype._processConfig = function(config) {
var overrides = this._overrides;
var currentConfig = {};
// Copy configuration so original config would be intact
copyConfiguration(config, currentConfig);
// Override the properties
copyConfiguration(overrides, currentConfig);
this._errorOnRemovedOptions(currentConfig);
// NOTE: options is a separate object to ensure that future options must be added
// to BUILTIN_OPTIONS to work, which also assures they aren't mistaken for a rule
var options = this._getOptionsFromConfig(currentConfig);
// Base path
Branch IfStatement
✓ Positive was executed (if)
if (this._basePath === defaults.cwd && options.configPath) {···
assert(
typeof options.configPath === 'string',
'`configPath` option requires string value'
);
this._basePath = path.dirname(options.configPath);
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('plugins')) {
Branch LogicalExpression
✓ Was returned
if (this._basePath === defaults.cwd && options.configPath) {
✓ Was returned
if (this._basePath === defaults.cwd && options.configPath) {
if (this._basePath === defaults.cwd && options.configPath) {
assert(
typeof options.configPath === 'string',
'`configPath` option requires string value'
);
this._basePath = path.dirname(options.configPath);
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('plugins')) {···
assert(Array.isArray(options.plugins), '`plugins` option requires array value');
options.plugins.forEach(function(plugin) {
this._loadPlugin(plugin, options.configPath);
}, this);

if (!this._isDefined('plugins')) {
this._definedOptions.push('plugins');
}
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('additionalRules')) {
if (options.hasOwnProperty('plugins')) {
assert(Array.isArray(options.plugins), '`plugins` option requires array value');
Function (anonymous_175)
✓ Was called
options.plugins.forEach(function(plugin) {···
this._loadPlugin(plugin, options.configPath);
}, this);
options.plugins.forEach(function(plugin) {
this._loadPlugin(plugin, options.configPath);
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('plugins')) {···
this._definedOptions.push('plugins');
}
✗ Negative was not executed (else)
}···
}
if (!this._isDefined('plugins')) {
this._definedOptions.push('plugins');
}
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('additionalRules')) {···
assert(Array.isArray(options.additionalRules), '`additionalRules` option requires array value');
options.additionalRules.forEach(function(rule) {
this._loadAdditionalRule(rule, options.configPath);
}, this);

if (!this._isDefined('additionalRules')) {
this._definedOptions.push('additionalRules');
}
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('extract')) {
if (options.hasOwnProperty('additionalRules')) {
assert(Array.isArray(options.additionalRules), '`additionalRules` option requires array value');
Function (anonymous_176)
✓ Was called
options.additionalRules.forEach(function(rule) {···
this._loadAdditionalRule(rule, options.configPath);
}, this);
options.additionalRules.forEach(function(rule) {
this._loadAdditionalRule(rule, options.configPath);
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('additionalRules')) {···
this._definedOptions.push('additionalRules');
}
✗ Negative was not executed (else)
}···
}
if (!this._isDefined('additionalRules')) {
this._definedOptions.push('additionalRules');
}
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('extract')) {···
this._loadExtract(options.extract);
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('fileExtensions')) {
if (options.hasOwnProperty('extract')) {
this._loadExtract(options.extract);
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('fileExtensions')) {···
this._loadFileExtensions(options.fileExtensions);
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('excludeFiles')) {
if (options.hasOwnProperty('fileExtensions')) {
this._loadFileExtensions(options.fileExtensions);
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('excludeFiles')) {···
this._loadExcludedFiles(options.excludeFiles);
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('fix')) {
if (options.hasOwnProperty('excludeFiles')) {
this._loadExcludedFiles(options.excludeFiles);
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('fix')) {···
this._loadFix(options.fix);
}
✓ Negative was executed (else)
}···

this._loadMaxError(options);
if (options.hasOwnProperty('fix')) {
this._loadFix(options.fix);
}
this._loadMaxError(options);
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('es3')) {···
this._loadES3(options.es3);
}
✓ Negative was executed (else)
}···

if (options.hasOwnProperty('errorFilter')) {
if (options.hasOwnProperty('es3')) {
this._loadES3(options.es3);
}
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('errorFilter')) {···
this._loadErrorFilter(options.errorFilter, options.configPath);
}
✓ Negative was executed (else)
}···

// Apply presets
if (options.hasOwnProperty('errorFilter')) {
this._loadErrorFilter(options.errorFilter, options.configPath);
}
// Apply presets
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('preset')) {···
this._loadPreset(options.preset, options.configPath);
}
✓ Negative was executed (else)
}···

this._loadRules(currentConfig);
if (options.hasOwnProperty('preset')) {
this._loadPreset(options.preset, options.configPath);
}
this._loadRules(currentConfig);
};
/**
* Loads plugin data.
*
* @param {function(Configuration)} plugin
* @protected
*/
Function (anonymous_177)
✓ Was called
Configuration.prototype._loadPlugin = function(plugin) {···
assert(typeof plugin === 'function', '`plugin` should be a function');
plugin(this);
};
Configuration.prototype._loadPlugin = function(plugin) {
assert(typeof plugin === 'function', '`plugin` should be a function');
plugin(this);
};
/**
* Load rules.
*
* @param {Object} config
* @protected
*/
Function (anonymous_178)
✓ Was called
Configuration.prototype._loadRules = function(config) {···
Object.keys(config).forEach(function(key) {

// Only rules should be processed
if (BUILTIN_OPTIONS[key]) {
return;
}

if (this._rules[key]) {
var optionValue = config[key];

// Disable rule it it equals "false" or "null"
if (optionValue === null || optionValue === false) {
delete this._ruleSettings[key];

} else {
this._ruleSettings[key] = config[key];
}

} else if (this._unsupportedRuleNames.indexOf(key) === -1) {
this._unsupportedRuleNames.push(key);
}
}, this);
};
Configuration.prototype._loadRules = function(config) {
Function (anonymous_179)
✓ Was called
Object.keys(config).forEach(function(key) {···

// Only rules should be processed
if (BUILTIN_OPTIONS[key]) {
return;
}

if (this._rules[key]) {
var optionValue = config[key];

// Disable rule it it equals "false" or "null"
if (optionValue === null || optionValue === false) {
delete this._ruleSettings[key];

} else {
this._ruleSettings[key] = config[key];
}

} else if (this._unsupportedRuleNames.indexOf(key) === -1) {
this._unsupportedRuleNames.push(key);
}
}, this);
Object.keys(config).forEach(function(key) {
// Only rules should be processed
Branch IfStatement
✓ Positive was executed (if)
if (BUILTIN_OPTIONS[key]) {···
return;
}
✓ Negative was executed (else)
}···

if (this._rules[key]) {
if (BUILTIN_OPTIONS[key]) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (this._rules[key]) {···
var optionValue = config[key];

// Disable rule it it equals "false" or "null"
if (optionValue === null || optionValue === false) {
delete this._ruleSettings[key];

} else {
this._ruleSettings[key] = config[key];
}

} else if (this._unsupportedRuleNames.indexOf(key) === -1) {
✓ Negative was executed (else)
} else if (this._unsupportedRuleNames.indexOf(key) === -1) {···
this._unsupportedRuleNames.push(key);
}
if (this._rules[key]) {
var optionValue = config[key];
// Disable rule it it equals "false" or "null"
Branch IfStatement
✓ Positive was executed (if)
if (optionValue === null || optionValue === false) {···
delete this._ruleSettings[key];

} else {
✓ Negative was executed (else)
} else {···
this._ruleSettings[key] = config[key];
}
Branch LogicalExpression
✓ Was returned
if (optionValue === null || optionValue === false) {
✓ Was returned
if (optionValue === null || optionValue === false) {
if (optionValue === null || optionValue === false) {
delete this._ruleSettings[key];
} else {
this._ruleSettings[key] = config[key];
}
Branch IfStatement
✓ Positive was executed (if)
} else if (this._unsupportedRuleNames.indexOf(key) === -1) {···
this._unsupportedRuleNames.push(key);
}
✓ Negative was executed (else)
}···
}, this);
} else if (this._unsupportedRuleNames.indexOf(key) === -1) {
this._unsupportedRuleNames.push(key);
}
}, this);
};
/**
* Loads an error filter.
*
* @param {Function|null} errorFilter
* @protected
*/
Function (anonymous_180)
✓ Was called
Configuration.prototype._loadErrorFilter = function(errorFilter) {···
assert(
typeof errorFilter === 'function' ||
errorFilter === null,
'`errorFilter` option requires a function or null value'
);
this._errorFilter = errorFilter;

if (!this._isDefined('errorFilter')) {
this._definedOptions.push('errorFilter');
}
};
Configuration.prototype._loadErrorFilter = function(errorFilter) {
assert(
Branch LogicalExpression
✗ Was not returned
errorFilter === null,
✓ Was returned
typeof errorFilter === 'function' ||
typeof errorFilter === 'function' ||
errorFilter === null,
'`errorFilter` option requires a function or null value'
);
this._errorFilter = errorFilter;
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('errorFilter')) {···
this._definedOptions.push('errorFilter');
}
✗ Negative was not executed (else)
}···
};
if (!this._isDefined('errorFilter')) {
this._definedOptions.push('errorFilter');
}
};
/**
* Load "es3" option.
*
* @param {Boolean} es3
* @protected
*/
Function (anonymous_181)
✓ Was called
Configuration.prototype._loadES3 = function(es3) {···
assert(
typeof es3 === 'boolean' || es3 === null,
'`es3` option requires boolean or null value'
);
this._es3Enabled = Boolean(es3);

if (!this._isDefined('es3')) {
this._definedOptions.push('es3');
}
};
Configuration.prototype._loadES3 = function(es3) {
assert(
Branch LogicalExpression
✓ Was returned
typeof es3 === 'boolean' || es3 === null,
✓ Was returned
typeof es3 === 'boolean' || es3 === null,
typeof es3 === 'boolean' || es3 === null,
'`es3` option requires boolean or null value'
);
this._es3Enabled = Boolean(es3);
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('es3')) {···
this._definedOptions.push('es3');
}
✗ Negative was not executed (else)
}···
};
if (!this._isDefined('es3')) {
this._definedOptions.push('es3');
}
};
/**
* Load "maxError" option.
*
* @param {Object} options
* @protected
*/
Function (anonymous_182)
✓ Was called
Configuration.prototype._loadMaxError = function(options) {···

// If "fix" option is enabled, set to Inifinity, otherwise this option
// doesn't make sense with "fix" conjunction
if (this._fix === true) {
this._maxErrors = Infinity;

return;
}

if (!options.hasOwnProperty('maxErrors')) {
return;
}

var maxErrors = options.maxErrors === null ? null : Number(options.maxErrors);

assert(
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
'`maxErrors` option requires -1, null value or positive number'
);

this._maxErrors = maxErrors;

if (!this._isDefined('fix')) {
this._definedOptions.push('fix');
}
};
Configuration.prototype._loadMaxError = function(options) {
// If "fix" option is enabled, set to Inifinity, otherwise this option
// doesn't make sense with "fix" conjunction
Branch IfStatement
✓ Positive was executed (if)
if (this._fix === true) {···
this._maxErrors = Infinity;

return;
}
✓ Negative was executed (else)
}···

if (!options.hasOwnProperty('maxErrors')) {
if (this._fix === true) {
this._maxErrors = Infinity;
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!options.hasOwnProperty('maxErrors')) {···
return;
}
✓ Negative was executed (else)
}···

var maxErrors = options.maxErrors === null ? null : Number(options.maxErrors);
if (!options.hasOwnProperty('maxErrors')) {
return;
}
Branch ConditionalExpression
✓ Positive was returned (? ...)
var maxErrors = options.maxErrors === null ? null : Number(options.maxErrors);
✓ Negative was returned (: ...)
var maxErrors = options.maxErrors === null ? null : Number(options.maxErrors);
var maxErrors = options.maxErrors === null ? null : Number(options.maxErrors);
assert(
Branch LogicalExpression
✓ Was returned
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
✓ Was returned
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
Branch LogicalExpression
✓ Was returned
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
✗ Was not returned
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
maxErrors === -1 || maxErrors > 0 || maxErrors === null,
'`maxErrors` option requires -1, null value or positive number'
);
this._maxErrors = maxErrors;
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('fix')) {···
this._definedOptions.push('fix');
}
✓ Negative was executed (else)
}···
};
if (!this._isDefined('fix')) {
this._definedOptions.push('fix');
}
};
/**
* Load "fix" option.
*
* @param {Boolean|null} fix
* @protected
*/
Function (anonymous_183)
✓ Was called
Configuration.prototype._loadFix = function(fix) {···
fix = fix === null ? false : fix;

assert(
typeof fix === 'boolean',
'`fix` option requires boolean or null value'
);

this._fix = fix;

if (!this._isDefined('fix')) {
this._definedOptions.push('fix');
}
};
Configuration.prototype._loadFix = function(fix) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
fix = fix === null ? false : fix;
✓ Negative was returned (: ...)
fix = fix === null ? false : fix;
fix = fix === null ? false : fix;
assert(
typeof fix === 'boolean',
'`fix` option requires boolean or null value'
);
this._fix = fix;
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('fix')) {···
this._definedOptions.push('fix');
}
✗ Negative was not executed (else)
}···
};
if (!this._isDefined('fix')) {
this._definedOptions.push('fix');
}
};
/**
* Load preset.
*
* @param {Object} preset
* @protected
*/
Function (anonymous_184)
✓ Was called
Configuration.prototype._loadPreset = function(preset) {···
if (this._loadedPresets.indexOf(preset) > -1) {
return;
}

// Do not keep adding preset from CLI (#2087)
delete this._overrides.preset;

this._loadedPresets.push(preset);

// If preset is loaded from another preset - preserve the original name
if (!this._presetName) {
this._presetName = preset;
}
assert(typeof preset === 'string', '`preset` option requires string value');

var presetData = this._presets[preset];
assert(Boolean(presetData), 'Preset "' + preset + '" does not exist');

if (!this._isDefined('preset')) {
this._definedOptions.push('preset');
}

// Process config from the preset
this._processConfig(this._presets[preset]);
};
Configuration.prototype._loadPreset = function(preset) {
Branch IfStatement
✓ Positive was executed (if)
if (this._loadedPresets.indexOf(preset) > -1) {···
return;
}
✓ Negative was executed (else)
}···

// Do not keep adding preset from CLI (#2087)
if (this._loadedPresets.indexOf(preset) > -1) {
return;
}
// Do not keep adding preset from CLI (#2087)
delete this._overrides.preset;
this._loadedPresets.push(preset);
// If preset is loaded from another preset - preserve the original name
Branch IfStatement
✓ Positive was executed (if)
if (!this._presetName) {···
this._presetName = preset;
}
✓ Negative was executed (else)
}···
assert(typeof preset === 'string', '`preset` option requires string value');
if (!this._presetName) {
this._presetName = preset;
}
assert(typeof preset === 'string', '`preset` option requires string value');
var presetData = this._presets[preset];
assert(Boolean(presetData), 'Preset "' + preset + '" does not exist');
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('preset')) {···
this._definedOptions.push('preset');
}
✓ Negative was executed (else)
}···

// Process config from the preset
if (!this._isDefined('preset')) {
this._definedOptions.push('preset');
}
// Process config from the preset
this._processConfig(this._presets[preset]);
};
/**
* Load file extensions.
*
* @param {String|Array} extensions
* @protected
*/
Function (anonymous_185)
✓ Was called
Configuration.prototype._loadFileExtensions = function(extensions) {···
assert(
typeof extensions === 'string' || Array.isArray(extensions),
'`fileExtensions` option requires string or array value'
);

this._fileExtensions = this._fileExtensions.concat(extensions).map(function(ext) {
return ext.toLowerCase();
});

if (!this._isDefined('fileExtensions')) {
this._definedOptions.push('fileExtensions');
}
};
Configuration.prototype._loadFileExtensions = function(extensions) {
assert(
Branch LogicalExpression
✓ Was returned
typeof extensions === 'string' || Array.isArray(extensions),
✓ Was returned
typeof extensions === 'string' || Array.isArray(extensions),
typeof extensions === 'string' || Array.isArray(extensions),
'`fileExtensions` option requires string or array value'
);
Function (anonymous_186)
✓ Was called
this._fileExtensions = this._fileExtensions.concat(extensions).map(function(ext) {···
return ext.toLowerCase();
});
this._fileExtensions = this._fileExtensions.concat(extensions).map(function(ext) {
return ext.toLowerCase();
});
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('fileExtensions')) {···
this._definedOptions.push('fileExtensions');
}
✓ Negative was executed (else)
}···
};
if (!this._isDefined('fileExtensions')) {
this._definedOptions.push('fileExtensions');
}
};
/**
* Is option defined?
*
* @param {String} name - name of the option
*
* @return {Boolean}
*/
Function (anonymous_187)
✓ Was called
Configuration.prototype._isDefined = function(name) {···
return this._definedOptions.indexOf(name) > -1;
};
Configuration.prototype._isDefined = function(name) {
return this._definedOptions.indexOf(name) > -1;
};
/**
* Load excluded paths.
*
* @param {Array} masks
* @protected
*/
Function (anonymous_188)
✓ Was called
Configuration.prototype._loadExcludedFiles = function(masks) {···
assert(Array.isArray(masks), '`excludeFiles` option requires array value');

this._excludedFileMasks = this._excludedFileMasks.concat(masks);
this._excludedFileMatchers = this._excludedFileMasks.map(function(fileMask) {
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);

if (!this._isDefined('excludeFiles')) {
this._definedOptions.push('excludeFiles');
}
};
Configuration.prototype._loadExcludedFiles = function(masks) {
assert(Array.isArray(masks), '`excludeFiles` option requires array value');
this._excludedFileMasks = this._excludedFileMasks.concat(masks);
Function (anonymous_189)
✓ Was called
this._excludedFileMatchers = this._excludedFileMasks.map(function(fileMask) {···
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);
this._excludedFileMatchers = this._excludedFileMasks.map(function(fileMask) {
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('excludeFiles')) {···
this._definedOptions.push('excludeFiles');
}
✓ Negative was executed (else)
}···
};
if (!this._isDefined('excludeFiles')) {
this._definedOptions.push('excludeFiles');
}
};
/**
* Load paths for extract.
*
* @param {Array} masks
* @protected
*/
Function (anonymous_190)
✓ Was called
Configuration.prototype._loadExtract = function(masks) {···
if (masks === true) {
masks = this._defaultExtractFileMasks;
} else if (masks === false) {
masks = [];
}

assert(Array.isArray(masks), '`extract` option should be array of strings');
this._extractFileMasks = masks.slice();
this._extractFileMatchers = this._extractFileMasks.map(function(fileMask) {
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);

if (!this._isDefined('extract')) {
this._definedOptions.push('extract');
}
};
Configuration.prototype._loadExtract = function(masks) {
Branch IfStatement
✓ Positive was executed (if)
if (masks === true) {···
masks = this._defaultExtractFileMasks;
} else if (masks === false) {
✓ Negative was executed (else)
} else if (masks === false) {···
masks = [];
}
if (masks === true) {
masks = this._defaultExtractFileMasks;
Branch IfStatement
✓ Positive was executed (if)
} else if (masks === false) {···
masks = [];
}
✓ Negative was executed (else)
}···

assert(Array.isArray(masks), '`extract` option should be array of strings');
} else if (masks === false) {
masks = [];
}
assert(Array.isArray(masks), '`extract` option should be array of strings');
this._extractFileMasks = masks.slice();
Function (anonymous_191)
✓ Was called
this._extractFileMatchers = this._extractFileMasks.map(function(fileMask) {···
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);
this._extractFileMatchers = this._extractFileMasks.map(function(fileMask) {
return new minimatch.Minimatch(path.resolve(this._basePath, fileMask), {
dot: true
});
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (!this._isDefined('extract')) {···
this._definedOptions.push('extract');
}
✗ Negative was not executed (else)
}···
};
if (!this._isDefined('extract')) {
this._definedOptions.push('extract');
}
};
/**
* Loads additional rule.
*
* @param {Rule} additionalRule
* @protected
*/
Function (anonymous_192)
✓ Was called
Configuration.prototype._loadAdditionalRule = function(additionalRule) {···
assert(typeof additionalRule === 'object', '`additionalRule` should be an object');
this.registerRule(additionalRule);
};
Configuration.prototype._loadAdditionalRule = function(additionalRule) {
assert(typeof additionalRule === 'object', '`additionalRule` should be an object');
this.registerRule(additionalRule);
};
/**
* Includes plugin in the configuration environment.
*
* @param {function(Configuration)|*} plugin
*/
Function (anonymous_193)
✓ Was called
Configuration.prototype.usePlugin = function(plugin) {···
this._loadPlugin(plugin);
};
Configuration.prototype.usePlugin = function(plugin) {
this._loadPlugin(plugin);
};
/**
* Apply the rules.
*
* @protected
*/
Function (anonymous_194)
✓ Was called
Configuration.prototype._useRules = function() {···
this._configuredRules = [];

Object.keys(this._ruleSettings).forEach(function(optionName) {
var rule = this._rules[optionName];
rule.configure(this._ruleSettings[optionName]);
this._configuredRules.push(rule);
}, this);
};
Configuration.prototype._useRules = function() {
this._configuredRules = [];
Function (anonymous_195)
✓ Was called
Object.keys(this._ruleSettings).forEach(function(optionName) {···
var rule = this._rules[optionName];
rule.configure(this._ruleSettings[optionName]);
this._configuredRules.push(rule);
}, this);
Object.keys(this._ruleSettings).forEach(function(optionName) {
var rule = this._rules[optionName];
rule.configure(this._ruleSettings[optionName]);
this._configuredRules.push(rule);
}, this);
};
/**
* Adds rule to the collection.
*
* @param {Rule|Function} rule Rule instance or rule class.
*/
Function (anonymous_196)
✓ Was called
Configuration.prototype.registerRule = function(rule) {···
if (typeof rule === 'function') {
var RuleClass = rule;
rule = new RuleClass();
}

var optionName = rule.getOptionName();
assert(!this._rules.hasOwnProperty(optionName), 'Rule "' + optionName + '" is already registered');
this._rules[optionName] = rule;
};
Configuration.prototype.registerRule = function(rule) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof rule === 'function') {···
var RuleClass = rule;
rule = new RuleClass();
}
✓ Negative was executed (else)
}···

var optionName = rule.getOptionName();
if (typeof rule === 'function') {
var RuleClass = rule;
rule = new RuleClass();
}
var optionName = rule.getOptionName();
assert(!this._rules.hasOwnProperty(optionName), 'Rule "' + optionName + '" is already registered');
this._rules[optionName] = rule;
};
/**
* Returns list of registered rules.
*
* @returns {Rule[]}
*/
Function (anonymous_197)
✓ Was called
Configuration.prototype.getRegisteredRules = function() {···
var rules = this._rules;
return Object.keys(rules).map(function(ruleOptionName) {
return rules[ruleOptionName];
});
};
Configuration.prototype.getRegisteredRules = function() {
var rules = this._rules;
Function (anonymous_198)
✓ Was called
return Object.keys(rules).map(function(ruleOptionName) {···
return rules[ruleOptionName];
});
return Object.keys(rules).map(function(ruleOptionName) {
return rules[ruleOptionName];
});
};
/**
* Adds preset to the collection.
*
* @param {String} presetName
* @param {Object} presetConfig
*/
Function (anonymous_199)
✓ Was called
Configuration.prototype.registerPreset = function(presetName, presetConfig) {···
assert(_.isPlainObject(presetConfig), 'Preset should be an object');

for (var key in presetConfig) {
assert(typeof presetConfig[key] !== 'function', 'Preset should be an JSON object');
}

this._presets[presetName] = presetConfig;
};
Configuration.prototype.registerPreset = function(presetName, presetConfig) {
assert(_.isPlainObject(presetConfig), 'Preset should be an object');
for (var key in presetConfig) {
assert(typeof presetConfig[key] !== 'function', 'Preset should be an JSON object');
}
this._presets[presetName] = presetConfig;
};
/**
* Returns registered presets object (key - preset name, value - preset content).
*
* @returns {Object}
*/
Function (anonymous_200)
✓ Was called
Configuration.prototype.getRegisteredPresets = function() {···
return this._presets;
};
Configuration.prototype.getRegisteredPresets = function() {
return this._presets;
};
/**
* Returns `true` if preset with specified name exists.
*
* @param {String} presetName
* @return {Boolean}
*/
Function (anonymous_201)
✓ Was called
Configuration.prototype.hasPreset = function(presetName) {···
return this._presets.hasOwnProperty(presetName);
};
Configuration.prototype.hasPreset = function(presetName) {
return this._presets.hasOwnProperty(presetName);
};
/**
* Returns name of the active preset.
*
* @return {String}
*/
Function (anonymous_202)
✓ Was called
Configuration.prototype.getPresetName = function() {···
return this._presetName;
};
Configuration.prototype.getPresetName = function() {
return this._presetName;
};
/**
* Registers built-in Code Style cheking rules.
*/
Function (anonymous_203)
✓ Was called
Configuration.prototype.registerDefaultRules = function() {···
var dir = path.join(__dirname, '../rules');

fs.readdirSync(dir).forEach(function(rule) {
this.registerRule(
require(path.join(dir, rule))
);
}, this);
};
Configuration.prototype.registerDefaultRules = function() {
var dir = path.join(__dirname, '../rules');
Function (anonymous_204)
✓ Was called
fs.readdirSync(dir).forEach(function(rule) {···
this.registerRule(
require(path.join(dir, rule))
);
}, this);
fs.readdirSync(dir).forEach(function(rule) {
this.registerRule(
require(path.join(dir, rule))
);
}, this);
};
/**
* Registers built-in Code Style cheking presets.
*/
Function (anonymous_205)
✓ Was called
Configuration.prototype.registerDefaultPresets = function() {···
var dir = path.join(__dirname, '../../presets/');

fs.readdirSync(dir).forEach(function(preset) {
var name = preset.split('.')[0];
var p = path.join(dir, preset);

this.registerPreset(name, require(p));
}, this);

this.registerPreset('wikimedia', require('jscs-preset-wikimedia'));
};
Configuration.prototype.registerDefaultPresets = function() {
var dir = path.join(__dirname, '../../presets/');
Function (anonymous_206)
✓ Was called
fs.readdirSync(dir).forEach(function(preset) {···
var name = preset.split('.')[0];
var p = path.join(dir, preset);

this.registerPreset(name, require(p));
}, this);
fs.readdirSync(dir).forEach(function(preset) {
var name = preset.split('.')[0];
var p = path.join(dir, preset);
this.registerPreset(name, require(p));
}, this);
this.registerPreset('wikimedia', require('jscs-preset-wikimedia'));
};
module.exports = Configuration;
Function copyConfiguration
✓ Was called
function copyConfiguration(source, dest) {···
Object.keys(source).forEach(function(key) {
dest[key] = source[key];
});
if (source.configPath) {
dest.configPath = source.configPath;
}
}
function copyConfiguration(source, dest) {
Function (anonymous_208)
✓ Was called
Object.keys(source).forEach(function(key) {···
dest[key] = source[key];
});
Object.keys(source).forEach(function(key) {
dest[key] = source[key];
});
Branch IfStatement
✓ Positive was executed (if)
if (source.configPath) {···
dest.configPath = source.configPath;
}
✓ Negative was executed (else)
}···
}
if (source.configPath) {
dest.configPath = source.configPath;
}
}
extract-js.js
var htmlparser = require('htmlparser2');
var Errors = require('./errors');
var rLineSplit = /\r\n|\r|\n/;
var rHasNonWhitespace = /\S/;
/**
* Html file representation (needed for errors output).
*
* @name HtmlFile
* @param {Object} params
* @param {String} params.filename
* @param {String} params.source
*/
Function (anonymous_209)
✓ Was called
var HtmlFile = function(params) {···
this._filename = params.filename;
this._lines = params.source.split(rLineSplit);
};
var HtmlFile = function(params) {
this._filename = params.filename;
this._lines = params.source.split(rLineSplit);
};
HtmlFile.prototype = {
/**
* Returns source filename for this object representation.
*
* @returns {String}
*/
Function (anonymous_210)
✓ Was called
getFilename: function() {···
return this._filename;
},
getFilename: function() {
return this._filename;
},
/**
* Returns array of source lines for the file.
*
* @returns {String[]}
*/
Function (anonymous_211)
✓ Was called
getLines: function() {···
return this._lines;
}
getLines: function() {
return this._lines;
}
};
/**
* Parse html and retrieve script sources.
*
* @param {String} html
* @returns {Object[]}
*/
Function getScripts
✓ Was called
function getScripts(html) {···
function onopen(name, attrs) {
// tag should be a <script>
if (name !== 'script' ||
// ignore scripts with src attribute
attrs.src ||
// script tag should has no type attribute or attribute should be equal to text/javascript
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
return;
}

// store script content start pos
scriptStartPos = parser.endIndex + 1;
}

function onclose() {
if (!scriptStartPos) {
return;
}

// get script content
var scriptEndPos = parser.startIndex;
var source = html.substring(scriptStartPos, scriptEndPos);

// store script content only if it contains non-whitespace characters
if (rHasNonWhitespace.test(source)) {
scripts.push({
source: source,
start: scriptStartPos,
end: scriptEndPos
});
}

// reset script start position
scriptStartPos = 0;
}

var scriptStartPos = 0;
var scripts = [];
var parser = new htmlparser.Parser({
onopentag: onopen,
onclosetag: onclose
});

parser.parseComplete(html);

return scripts;
}
function getScripts(html) {
Function onopen
✓ Was called
function onopen(name, attrs) {···
// tag should be a <script>
if (name !== 'script' ||
// ignore scripts with src attribute
attrs.src ||
// script tag should has no type attribute or attribute should be equal to text/javascript
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
return;
}

// store script content start pos
scriptStartPos = parser.endIndex + 1;
}
function onopen(name, attrs) {
// tag should be a <script>
Branch IfStatement
✓ Positive was executed (if)
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {···
return;
}
✓ Negative was executed (else)
}···

// store script content start pos
Branch LogicalExpression
✓ Was returned
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
✓ Was returned
if (name !== 'script' ||···
// ignore scripts with src attribute
attrs.src ||
Branch LogicalExpression
✓ Was returned
attrs.src ||
✓ Was returned
if (name !== 'script' ||
if (name !== 'script' ||
// ignore scripts with src attribute
attrs.src ||
// script tag should has no type attribute or attribute should be equal to text/javascript
Branch LogicalExpression
✓ Was returned
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
✓ Was returned
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
(attrs.type && attrs.type.toLowerCase() !== 'text/javascript')) {
return;
}
// store script content start pos
scriptStartPos = parser.endIndex + 1;
}
Function onclose
✓ Was called
function onclose() {···
if (!scriptStartPos) {
return;
}

// get script content
var scriptEndPos = parser.startIndex;
var source = html.substring(scriptStartPos, scriptEndPos);

// store script content only if it contains non-whitespace characters
if (rHasNonWhitespace.test(source)) {
scripts.push({
source: source,
start: scriptStartPos,
end: scriptEndPos
});
}

// reset script start position
scriptStartPos = 0;
}
function onclose() {
Branch IfStatement
✓ Positive was executed (if)
if (!scriptStartPos) {···
return;
}
✓ Negative was executed (else)
}···

// get script content
if (!scriptStartPos) {
return;
}
// get script content
var scriptEndPos = parser.startIndex;
var source = html.substring(scriptStartPos, scriptEndPos);
// store script content only if it contains non-whitespace characters
Branch IfStatement
✓ Positive was executed (if)
if (rHasNonWhitespace.test(source)) {···
scripts.push({
source: source,
start: scriptStartPos,
end: scriptEndPos
});
}
✓ Negative was executed (else)
}···

// reset script start position
if (rHasNonWhitespace.test(source)) {
scripts.push({
source: source,
start: scriptStartPos,
end: scriptEndPos
});
}
// reset script start position
scriptStartPos = 0;
}
var scriptStartPos = 0;
var scripts = [];
var parser = new htmlparser.Parser({
onopentag: onopen,
onclosetag: onclose
});
parser.parseComplete(html);
return scripts;
}
/**
* JavaScript in HTML usually shifted based on first JS line. For example
* if first line of fragment is offset by 4 spaces, each line in this
* fragment will have offset 4 to restore the original column.
* This function trim script source and normalize lines offset.
*
* @param {String} source
* @returns {Object[]}
*/
Function normalizeSource
✓ Was called
function normalizeSource(source) {···
var lines = source.split(rLineSplit);
var lineCount = lines.length;
var tabOnlyOffset = false;
var spaceOnlyOffset = false;
var offset;

// remove first list if it's an empty string
// usually <script> starts with new line
if (!rHasNonWhitespace.test(lines[0])) {
lines.shift();
}

// replace last line by empty string if it contains only whitespaces
// it helps avoid disallowTrailingWhitespace errors on last line
if (!rHasNonWhitespace.test(lines[lines.length - 1])) {
lines[lines.length - 1] = '';
}

// calculate min line offset
offset = Math.min.apply(null, lines.map(function(line) {
// skip empty lines
if (!line) {
return Infinity;
}

// fetch whitespaces at the line beginning
var offsetStr = line.match(/^\s*/)[0];
var tabCount = offsetStr.match(/\t*/)[0].length;

if (offsetStr.length === line.length) {
return 0;
}

// mixed spaces and tabs in one offset -> don't remove offsets
if (tabCount && tabCount !== offsetStr.length) {
return 0;
}

if (tabCount) {
if (spaceOnlyOffset) {
// no spaces, but previous offset has ony spaces -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only tabs
tabOnlyOffset = true;
}
} else {
if (tabOnlyOffset) {
// no tabs, but previous offset has only tabs -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only spaces
spaceOnlyOffset = true;
}
}

return offsetStr.length;
}));

// remove common offsets if possible
if (offset) {
lines = lines.map(function(line) {
return line.substr(offset);
});
}

return {
source: lines.join('\n'),
offset: offset,
lineCount: lineCount
};
}
function normalizeSource(source) {
var lines = source.split(rLineSplit);
var lineCount = lines.length;
var tabOnlyOffset = false;
var spaceOnlyOffset = false;
var offset;
// remove first list if it's an empty string
// usually <script> starts with new line
Branch IfStatement
✓ Positive was executed (if)
if (!rHasNonWhitespace.test(lines[0])) {···
lines.shift();
}
✓ Negative was executed (else)
}···

// replace last line by empty string if it contains only whitespaces
if (!rHasNonWhitespace.test(lines[0])) {
lines.shift();
}
// replace last line by empty string if it contains only whitespaces
// it helps avoid disallowTrailingWhitespace errors on last line
Branch IfStatement
✓ Positive was executed (if)
if (!rHasNonWhitespace.test(lines[lines.length - 1])) {···
lines[lines.length - 1] = '';
}
✓ Negative was executed (else)
}···

// calculate min line offset
if (!rHasNonWhitespace.test(lines[lines.length - 1])) {
lines[lines.length - 1] = '';
}
// calculate min line offset
Function (anonymous_216)
✓ Was called
offset = Math.min.apply(null, lines.map(function(line) {···
// skip empty lines
if (!line) {
return Infinity;
}

// fetch whitespaces at the line beginning
var offsetStr = line.match(/^\s*/)[0];
var tabCount = offsetStr.match(/\t*/)[0].length;

if (offsetStr.length === line.length) {
return 0;
}

// mixed spaces and tabs in one offset -> don't remove offsets
if (tabCount && tabCount !== offsetStr.length) {
return 0;
}

if (tabCount) {
if (spaceOnlyOffset) {
// no spaces, but previous offset has ony spaces -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only tabs
tabOnlyOffset = true;
}
} else {
if (tabOnlyOffset) {
// no tabs, but previous offset has only tabs -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only spaces
spaceOnlyOffset = true;
}
}

return offsetStr.length;
}));
offset = Math.min.apply(null, lines.map(function(line) {
// skip empty lines
Branch IfStatement
✓ Positive was executed (if)
if (!line) {···
return Infinity;
}
✓ Negative was executed (else)
}···

// fetch whitespaces at the line beginning
if (!line) {
return Infinity;
}
// fetch whitespaces at the line beginning
var offsetStr = line.match(/^\s*/)[0];
var tabCount = offsetStr.match(/\t*/)[0].length;
Branch IfStatement
✓ Positive was executed (if)
if (offsetStr.length === line.length) {···
return 0;
}
✓ Negative was executed (else)
}···

// mixed spaces and tabs in one offset -> don't remove offsets
if (offsetStr.length === line.length) {
return 0;
}
// mixed spaces and tabs in one offset -> don't remove offsets
Branch IfStatement
✓ Positive was executed (if)
if (tabCount && tabCount !== offsetStr.length) {···
return 0;
}
✓ Negative was executed (else)
}···

if (tabCount) {
Branch LogicalExpression
✓ Was returned
if (tabCount && tabCount !== offsetStr.length) {
✓ Was returned
if (tabCount && tabCount !== offsetStr.length) {
if (tabCount && tabCount !== offsetStr.length) {
return 0;
}
Branch IfStatement
✓ Positive was executed (if)
if (tabCount) {···
if (spaceOnlyOffset) {
// no spaces, but previous offset has ony spaces -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only tabs
tabOnlyOffset = true;
}
} else {
✓ Negative was executed (else)
} else {···
if (tabOnlyOffset) {
// no tabs, but previous offset has only tabs -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only spaces
spaceOnlyOffset = true;
}
}
if (tabCount) {
Branch IfStatement
✓ Positive was executed (if)
if (spaceOnlyOffset) {···
// no spaces, but previous offset has ony spaces -> mixed spaces and tabs
return 0;
} else {
✓ Negative was executed (else)
} else {···
// remember offset contains only tabs
tabOnlyOffset = true;
}
if (spaceOnlyOffset) {
// no spaces, but previous offset has ony spaces -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only tabs
tabOnlyOffset = true;
}
} else {
Branch IfStatement
✓ Positive was executed (if)
if (tabOnlyOffset) {···
// no tabs, but previous offset has only tabs -> mixed spaces and tabs
return 0;
} else {
✓ Negative was executed (else)
} else {···
// remember offset contains only spaces
spaceOnlyOffset = true;
}
if (tabOnlyOffset) {
// no tabs, but previous offset has only tabs -> mixed spaces and tabs
return 0;
} else {
// remember offset contains only spaces
spaceOnlyOffset = true;
}
}
return offsetStr.length;
}));
// remove common offsets if possible
Branch IfStatement
✓ Positive was executed (if)
if (offset) {···
lines = lines.map(function(line) {
return line.substr(offset);
});
}
✓ Negative was executed (else)
}···

return {
if (offset) {
Function (anonymous_217)
✓ Was called
lines = lines.map(function(line) {···
return line.substr(offset);
});
lines = lines.map(function(line) {
return line.substr(offset);
});
}
return {
source: lines.join('\n'),
offset: offset,
lineCount: lineCount
};
}
/**
* Parse HTML and search for <script> sources. Each script source also normalize
* by line offset. Result contains script sources with information about line
* offset (that was removed for each line) and lines count before script source.
* This information helps restore absolute positions in html file for errors.
*
* @param {String} filename
* @param {String} data
* @returns {Object[]}
*/
Function extractJs
✓ Was called
function extractJs(filename, data) {···
var errors = new Errors(new HtmlFile({
filename: filename,
source: data
}));
var scripts = getScripts(data);
var sources = [];
var line = 1;
var lastHtmlPos = 0;

scripts.forEach(function(scriptInfo) {
// fetch script source and normalize it
var normalized = normalizeSource(scriptInfo.source);

// add line offset before script
line += data.substring(lastHtmlPos, scriptInfo.start).split(rLineSplit).length - 1;

sources.push({
source: normalized.source,
offset: normalized.offset,
line: line
});

// save offsets for next fragment
line += normalized.lineCount - 1;
lastHtmlPos = scriptInfo.end;
});

return {
sources: sources,
errors: errors,
addError: function(error) {
errors._errorList.push({
filename: filename,
rule: error.rule,
message: error.message,
line: error.line,
column: error.column
});
}
};
}
function extractJs(filename, data) {
var errors = new Errors(new HtmlFile({
filename: filename,
source: data
}));
var scripts = getScripts(data);
var sources = [];
var line = 1;
var lastHtmlPos = 0;
Function (anonymous_219)
✓ Was called
scripts.forEach(function(scriptInfo) {···
// fetch script source and normalize it
var normalized = normalizeSource(scriptInfo.source);

// add line offset before script
line += data.substring(lastHtmlPos, scriptInfo.start).split(rLineSplit).length - 1;

sources.push({
source: normalized.source,
offset: normalized.offset,
line: line
});

// save offsets for next fragment
line += normalized.lineCount - 1;
lastHtmlPos = scriptInfo.end;
});
scripts.forEach(function(scriptInfo) {
// fetch script source and normalize it
var normalized = normalizeSource(scriptInfo.source);
// add line offset before script
line += data.substring(lastHtmlPos, scriptInfo.start).split(rLineSplit).length - 1;
sources.push({
source: normalized.source,
offset: normalized.offset,
line: line
});
// save offsets for next fragment
line += normalized.lineCount - 1;
lastHtmlPos = scriptInfo.end;
});
return {
sources: sources,
errors: errors,
Function (anonymous_220)
✓ Was called
addError: function(error) {···
errors._errorList.push({
filename: filename,
rule: error.rule,
message: error.message,
line: error.line,
column: error.column
});
}
addError: function(error) {
errors._errorList.push({
filename: filename,
rule: error.rule,
message: error.message,
line: error.line,
column: error.column
});
}
};
}
module.exports = extractJs;
node-configuration.js
var path = require('path');
var util = require('util');
var fs = require('fs');
var assert = require('assert');
var glob = require('glob');
var resolve = require('resolve');
var utils = require('../utils');
var Configuration = require('./configuration');
var configFinder = require('../cli-config');
var OVERRIDE_OPTIONS = [
'fix',
'preset',
'maxErrors',
'errorFilter',
'es3',
'extract'
];
Function req
✓ Was called
function req(entity, dir) {···
return require(
resolve.sync(entity, { basedir: dir })
);
}
function req(entity, dir) {
return require(
resolve.sync(entity, { basedir: dir })
);
}
/**
* nodejs-compatible configuration module.
*
* @name NodeConfiguration
* @augments Configuration
* @constructor
*/
Function NodeConfiguration
✓ Was called
function NodeConfiguration() {···
Configuration.call(this);
this._basePath = process.cwd();
}
function NodeConfiguration() {
Configuration.call(this);
this._basePath = process.cwd();
}
util.inherits(NodeConfiguration, Configuration);
/**
* Overrides configuration with options specified by the CLI
*
* @param {Object} program
*/
Function (anonymous_223)
✓ Was called
NodeConfiguration.prototype.overrideFromCLI = function(program) {···
var overrides = {};

OVERRIDE_OPTIONS.forEach(function(option) {
if (option in program) {
overrides[option] = program[option];
}
});

this.override(overrides);
};
NodeConfiguration.prototype.overrideFromCLI = function(program) {
var overrides = {};
Function (anonymous_224)
✓ Was called
OVERRIDE_OPTIONS.forEach(function(option) {···
if (option in program) {
overrides[option] = program[option];
}
});
OVERRIDE_OPTIONS.forEach(function(option) {
Branch IfStatement
✓ Positive was executed (if)
if (option in program) {···
overrides[option] = program[option];
}
✓ Negative was executed (else)
}···
});
if (option in program) {
overrides[option] = program[option];
}
});
this.override(overrides);
};
/**
* Load external module.
*
* @param {String|null} external - path (relative or absolute) or name to the external module
* @param {String} type - type of the module
* @param {String} [config = _basePath] - path to config relative to which external entities will be loaded
* @returns {Module|null}
* @protected
*/
Function (anonymous_225)
✓ Was called
NodeConfiguration.prototype.loadExternal = function(external, type, config) {···
assert(
typeof external === 'string' || external === null,
'"' + type + '" option requires a string or null value'
);

if (external === null) {
return null;
}

var dir = config ? path.dirname(config) : this._basePath;
var get = function(prefix, postfix) {
prefix = prefix || '';
postfix = postfix || '';

try {
return finder(
utils.normalizePath(prefix + external + postfix, dir),
dir
);
} catch (e) {}

return null;
}.bind(this);

var finder;
if (type === 'preset') {
finder = configFinder.getContent;

} else {
finder = req;
}

var content;

if (external.indexOf('jscs-') !== 0) {
content = get('jscs-');

if (!content && type === 'preset') {
content = get('jscs-preset-') || get('jscs-config-');

if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
content = get('jscs-', '.json') ||
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
get('jscs-config-', '.js');
}
}
}

return content || get();
};
NodeConfiguration.prototype.loadExternal = function(external, type, config) {
assert(
Branch LogicalExpression
✓ Was returned
typeof external === 'string' || external === null,
✓ Was returned
typeof external === 'string' || external === null,
typeof external === 'string' || external === null,
'"' + type + '" option requires a string or null value'
);
Branch IfStatement
✓ Positive was executed (if)
if (external === null) {···
return null;
}
✓ Negative was executed (else)
}···

var dir = config ? path.dirname(config) : this._basePath;
if (external === null) {
return null;
}
Branch ConditionalExpression
✓ Positive was returned (? ...)
var dir = config ? path.dirname(config) : this._basePath;
✓ Negative was returned (: ...)
var dir = config ? path.dirname(config) : this._basePath;
var dir = config ? path.dirname(config) : this._basePath;
Function (anonymous_226)
✓ Was called
var get = function(prefix, postfix) {···
prefix = prefix || '';
postfix = postfix || '';

try {
return finder(
utils.normalizePath(prefix + external + postfix, dir),
dir
);
} catch (e) {}

return null;
}.bind(this);
var get = function(prefix, postfix) {
Branch LogicalExpression
✓ Was returned
prefix = prefix || '';
✓ Was returned
prefix = prefix || '';
prefix = prefix || '';
Branch LogicalExpression
✓ Was returned
postfix = postfix || '';
✓ Was returned
postfix = postfix || '';
postfix = postfix || '';
try {
return finder(
utils.normalizePath(prefix + external + postfix, dir),
dir
);
} catch (e) {}
return null;
}.bind(this);
var finder;
Branch IfStatement
✓ Positive was executed (if)
if (type === 'preset') {···
finder = configFinder.getContent;

} else {
✓ Negative was executed (else)
} else {···
finder = req;
}
if (type === 'preset') {
finder = configFinder.getContent;
} else {
finder = req;
}
var content;
Branch IfStatement
✓ Positive was executed (if)
if (external.indexOf('jscs-') !== 0) {···
content = get('jscs-');

if (!content && type === 'preset') {
content = get('jscs-preset-') || get('jscs-config-');

if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
content = get('jscs-', '.json') ||
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
get('jscs-config-', '.js');
}
}
}
✓ Negative was executed (else)
}···

return content || get();
if (external.indexOf('jscs-') !== 0) {
content = get('jscs-');
Branch IfStatement
✓ Positive was executed (if)
if (!content && type === 'preset') {···
content = get('jscs-preset-') || get('jscs-config-');

if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
content = get('jscs-', '.json') ||
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
get('jscs-config-', '.js');
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (!content && type === 'preset') {
✓ Was returned
if (!content && type === 'preset') {
if (!content && type === 'preset') {
Branch LogicalExpression
✓ Was returned
content = get('jscs-preset-') || get('jscs-config-');
✓ Was returned
content = get('jscs-preset-') || get('jscs-config-');
content = get('jscs-preset-') || get('jscs-config-');
Branch IfStatement
✓ Positive was executed (if)
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {···
content = get('jscs-', '.json') ||
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
get('jscs-config-', '.js');
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
✓ Was returned
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
Branch LogicalExpression
✓ Was returned
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
✓ Was returned
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
if (!content && external.indexOf('/') !== -1 && !external.split('.')[1]) {
Branch LogicalExpression
✗ Was not returned
get('jscs-config-', '.js');
✓ Was returned
content = get('jscs-', '.json') ||···
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
Branch LogicalExpression
✗ Was not returned
get('jscs-preset-', '.js') ||
✓ Was returned
content = get('jscs-', '.json') ||···
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
Branch LogicalExpression
✗ Was not returned
get('jscs-config-', '.json') ||
✓ Was returned
content = get('jscs-', '.json') ||···
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
Branch LogicalExpression
✓ Was returned
get('jscs-preset-', '.json') ||
✓ Was returned
content = get('jscs-', '.json') ||···
get('jscs-', '.js') ||
Branch LogicalExpression
✓ Was returned
get('jscs-', '.js') ||
✓ Was returned
content = get('jscs-', '.json') ||
content = get('jscs-', '.json') ||
get('jscs-', '.js') ||
get('jscs-preset-', '.json') ||
get('jscs-config-', '.json') ||
get('jscs-preset-', '.js') ||
get('jscs-config-', '.js');
}
}
}
Branch LogicalExpression
✓ Was returned
return content || get();
✓ Was returned
return content || get();
return content || get();
};
/**
* Loads plugin data.
*
* @param {String|function(Configuration)} plugin
* @param {String} [config] - path to config relative to which plugin will be loaded
* @protected
*/
Function (anonymous_227)
✓ Was called
NodeConfiguration.prototype._loadPlugin = function(plugin, config) {···
if (typeof plugin !== 'function') {
plugin = this.loadExternal(plugin, 'plugin', config);
}

return Configuration.prototype._loadPlugin.call(this, plugin);
};
NodeConfiguration.prototype._loadPlugin = function(plugin, config) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof plugin !== 'function') {···
plugin = this.loadExternal(plugin, 'plugin', config);
}
✓ Negative was executed (else)
}···

return Configuration.prototype._loadPlugin.call(this, plugin);
if (typeof plugin !== 'function') {
plugin = this.loadExternal(plugin, 'plugin', config);
}
return Configuration.prototype._loadPlugin.call(this, plugin);
};
/**
* Loads preset.
*
* @param {String|null} preset
* @param {String} config - path to config relative to which plugin will be loaded
* @protected
*/
Function (anonymous_228)
✓ Was called
NodeConfiguration.prototype._loadPreset = function(preset, config) {···
var name = path.basename(preset).split('.')[0];

try {
this.registerPreset(name, this.loadExternal(preset, 'preset', config));
} catch (e) {
var registeredPresets = this.getRegisteredPresets();

if (preset in registeredPresets) {
Configuration.prototype._loadPreset.call(this, preset);
return;
}
}

// If preset is an external module, error will be thrown by the caller
Configuration.prototype._loadPreset.call(this, name);
};
NodeConfiguration.prototype._loadPreset = function(preset, config) {
var name = path.basename(preset).split('.')[0];
try {
this.registerPreset(name, this.loadExternal(preset, 'preset', config));
} catch (e) {
var registeredPresets = this.getRegisteredPresets();
Branch IfStatement
✓ Positive was executed (if)
if (preset in registeredPresets) {···
Configuration.prototype._loadPreset.call(this, preset);
return;
}
✓ Negative was executed (else)
}···
}
if (preset in registeredPresets) {
Configuration.prototype._loadPreset.call(this, preset);
return;
}
}
// If preset is an external module, error will be thrown by the caller
Configuration.prototype._loadPreset.call(this, name);
};
/**
* Loads an error filter module.
*
* @param {String|null} filter
* @param {String} config - path to config relative to which plugin will be loaded
* @protected
*/
Function (anonymous_229)
✓ Was called
NodeConfiguration.prototype._loadErrorFilter = function(filter, config) {···
Configuration.prototype._loadErrorFilter.call(
this,
this.loadExternal(filter, 'errorFilter', config)
);
};
NodeConfiguration.prototype._loadErrorFilter = function(filter, config) {
Configuration.prototype._loadErrorFilter.call(
this,
this.loadExternal(filter, 'errorFilter', config)
);
};
/**
* Loads additional rule.
*
* @param {String|Rule} additionalRule
* @param {String} config - path to config relative to which plugin will be loaded
* @private
*/
Function (anonymous_230)
✓ Was called
NodeConfiguration.prototype._loadAdditionalRule = function(additionalRule, config) {···
config = config || this._basePath;

if (typeof additionalRule === 'string') {
if (glob.hasMagic(additionalRule)) {

// In some cases there might not be a config
// like if options are defined through direct initialization (grunt plugin case)
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);

glob.sync(path.resolve(config, additionalRule)).forEach(function(p) {
var Rule = require(p);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}, this);
} else {
var Rule = this.loadExternal(additionalRule, 'rule', config);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}
} else {
Configuration.prototype._loadAdditionalRule.call(this, additionalRule);
}
};
NodeConfiguration.prototype._loadAdditionalRule = function(additionalRule, config) {
Branch LogicalExpression
✓ Was returned
config = config || this._basePath;
✓ Was returned
config = config || this._basePath;
config = config || this._basePath;
Branch IfStatement
✓ Positive was executed (if)
if (typeof additionalRule === 'string') {···
if (glob.hasMagic(additionalRule)) {

// In some cases there might not be a config
// like if options are defined through direct initialization (grunt plugin case)
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);

glob.sync(path.resolve(config, additionalRule)).forEach(function(p) {
var Rule = require(p);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}, this);
} else {
var Rule = this.loadExternal(additionalRule, 'rule', config);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}
} else {
✓ Negative was executed (else)
} else {···
Configuration.prototype._loadAdditionalRule.call(this, additionalRule);
}
if (typeof additionalRule === 'string') {
Branch IfStatement
✓ Positive was executed (if)
if (glob.hasMagic(additionalRule)) {···

// In some cases there might not be a config
// like if options are defined through direct initialization (grunt plugin case)
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);

glob.sync(path.resolve(config, additionalRule)).forEach(function(p) {
var Rule = require(p);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}, this);
} else {
✓ Negative was executed (else)
} else {···
var Rule = this.loadExternal(additionalRule, 'rule', config);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}
if (glob.hasMagic(additionalRule)) {
// In some cases there might not be a config
// like if options are defined through direct initialization (grunt plugin case)
Branch ConditionalExpression
✓ Positive was returned (? ...)
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);
✓ Negative was returned (: ...)
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);
config = fs.statSync(config).isDirectory() ? config : path.dirname(config);
Function (anonymous_231)
✓ Was called
glob.sync(path.resolve(config, additionalRule)).forEach(function(p) {···
var Rule = require(p);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}, this);
glob.sync(path.resolve(config, additionalRule)).forEach(function(p) {
var Rule = require(p);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}, this);
} else {
var Rule = this.loadExternal(additionalRule, 'rule', config);
Configuration.prototype._loadAdditionalRule.call(this, new Rule());
}
} else {
Configuration.prototype._loadAdditionalRule.call(this, additionalRule);
}
};
module.exports = NodeConfiguration;
utils.js
var path = require('path');
var Vow = require('vow');
var reservedWords = require('reserved-words');
var IDENTIFIER_NAME_ES5_RE = require('../patterns/identifiers-ES5');
var IDENTIFIER_NAME_ES6_RE = require('../patterns/identifiers-ES6');
var TRAILING_UNDERSCORES_RE = /(^_+|_+$)/g;
var SNAKE_CASE_RE = /^([a-z$][a-z0-9$]+)(_[a-z0-9$]+)+$/i;
/**
* All keywords where spaces are a stylistic choice
* @type {Array}
*/
exports.spacedKeywords = [
'do',
'for',
'if',
'else',
'switch',
'case',
'try',
'catch',
'finally',
'void',
'while',
'with',
'return',
'typeof',
'function'
];
/**
* All keywords where curly braces are a stylistic choice
* @type {Array}
*/
exports.curlyBracedKeywords = [
'if',
'else',
'for',
'while',
'do',
'case',
'default',
'with'
];
/**
* Returns true if name is valid identifier name.
*
* @param {String} name
* @param {String} dialect
* @returns {Boolean}
*/
Function (anonymous_232)
✓ Was called
exports.isValidIdentifierName = function(name, dialect) {···
dialect = dialect || 'es5';
var identifierRegex = dialect === 'es5' ? IDENTIFIER_NAME_ES5_RE : IDENTIFIER_NAME_ES6_RE;
return !reservedWords.check(name, dialect, true) && identifierRegex.test(name);
};
exports.isValidIdentifierName = function(name, dialect) {
Branch LogicalExpression
✓ Was returned
dialect = dialect || 'es5';
✓ Was returned
dialect = dialect || 'es5';
dialect = dialect || 'es5';
Branch ConditionalExpression
✓ Positive was returned (? ...)
var identifierRegex = dialect === 'es5' ? IDENTIFIER_NAME_ES5_RE : IDENTIFIER_NAME_ES6_RE;
✓ Negative was returned (: ...)
var identifierRegex = dialect === 'es5' ? IDENTIFIER_NAME_ES5_RE : IDENTIFIER_NAME_ES6_RE;
var identifierRegex = dialect === 'es5' ? IDENTIFIER_NAME_ES5_RE : IDENTIFIER_NAME_ES6_RE;
Branch LogicalExpression
✓ Was returned
return !reservedWords.check(name, dialect, true) && identifierRegex.test(name);
✓ Was returned
return !reservedWords.check(name, dialect, true) && identifierRegex.test(name);
return !reservedWords.check(name, dialect, true) && identifierRegex.test(name);
};
/**
* Snake case tester
*
* @param {String} name
* @return {Boolean}
*/
Function (anonymous_233)
✓ Was called
exports.isSnakeCased = function(name) {···
return SNAKE_CASE_RE.test(name);
};
exports.isSnakeCased = function(name) {
return SNAKE_CASE_RE.test(name);
};
/**
* Returns the function expression node if the provided node is an IIFE,
* otherwise returns null.
*
* @param {Object} node
* @return {?Object}
*/
Function (anonymous_234)
✓ Was called
exports.getFunctionNodeFromIIFE = function(node) {···
if (node.type !== 'CallExpression') {
return null;
}

var callee = node.callee;

if (callee.type === 'FunctionExpression') {
return callee;
}

if (callee.type === 'MemberExpression' &&
callee.object.type === 'FunctionExpression' &&
callee.property.type === 'Identifier' &&
(callee.property.name === 'call' || callee.property.name === 'apply')
) {
return callee.object;
}

return null;
};
exports.getFunctionNodeFromIIFE = function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type !== 'CallExpression') {···
return null;
}
✓ Negative was executed (else)
}···

var callee = node.callee;
if (node.type !== 'CallExpression') {
return null;
}
var callee = node.callee;
Branch IfStatement
✓ Positive was executed (if)
if (callee.type === 'FunctionExpression') {···
return callee;
}
✓ Negative was executed (else)
}···

if (callee.type === 'MemberExpression' &&
if (callee.type === 'FunctionExpression') {
return callee;
}
Branch IfStatement
✓ Positive was executed (if)
) {···
return callee.object;
}
✓ Negative was executed (else)
}···

return null;
Branch LogicalExpression
✓ Was returned
(callee.property.name === 'call' || callee.property.name === 'apply')
✓ Was returned
if (callee.type === 'MemberExpression' &&···
callee.object.type === 'FunctionExpression' &&
callee.property.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
callee.property.type === 'Identifier' &&
✓ Was returned
if (callee.type === 'MemberExpression' &&···
callee.object.type === 'FunctionExpression' &&
Branch LogicalExpression
✓ Was returned
callee.object.type === 'FunctionExpression' &&
✓ Was returned
if (callee.type === 'MemberExpression' &&
if (callee.type === 'MemberExpression' &&
callee.object.type === 'FunctionExpression' &&
callee.property.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
(callee.property.name === 'call' || callee.property.name === 'apply')
✓ Was returned
(callee.property.name === 'call' || callee.property.name === 'apply')
(callee.property.name === 'call' || callee.property.name === 'apply')
) {
return callee.object;
}
return null;
};
/**
* Trims leading and trailing underscores
*
* @param {String} name
* @return {String}
*/
Function (anonymous_235)
✓ Was called
exports.trimUnderscores = function(name) {···
var res = name.replace(TRAILING_UNDERSCORES_RE, '');
return res ? res : name;
};
exports.trimUnderscores = function(name) {
var res = name.replace(TRAILING_UNDERSCORES_RE, '');
Branch ConditionalExpression
✓ Positive was returned (? ...)
return res ? res : name;
✓ Negative was returned (: ...)
return res ? res : name;
return res ? res : name;
};
/**
* Whether or not the given path is relative
*
* @param {String} path
* @return {Boolean}
*/
Function (anonymous_236)
✓ Was called
exports.isRelativePath = function(path) {···
// Logic from: https://github.com/joyent/node/blob/4f1ae11a62b97052bc83756f8cb8700cc1f61661/lib/module.js#L237
var start = path.substring(0, 2);
return start === './' || start === '..';
};
exports.isRelativePath = function(path) {
// Logic from: https://github.com/joyent/node/blob/4f1ae11a62b97052bc83756f8cb8700cc1f61661/lib/module.js#L237
var start = path.substring(0, 2);
Branch LogicalExpression
✓ Was returned
return start === './' || start === '..';
✓ Was returned
return start === './' || start === '..';
return start === './' || start === '..';
};
/**
* Resolves a relative filepath against the supplied base path
* or just returns the filepath if not relative
*
* @param {String} filepath
* @param {String} basePath
* @return {String}
*/
Function (anonymous_237)
✓ Was called
exports.normalizePath = function(filepath, basePath) {···
if (this.isRelativePath(filepath)) {
return path.resolve(basePath, filepath);
}

return filepath;
};
exports.normalizePath = function(filepath, basePath) {
Branch IfStatement
✓ Positive was executed (if)
if (this.isRelativePath(filepath)) {···
return path.resolve(basePath, filepath);
}
✓ Negative was executed (else)
}···

return filepath;
if (this.isRelativePath(filepath)) {
return path.resolve(basePath, filepath);
}
return filepath;
};
/**
* Wraps a function such that you can interact with a promise and not a
* node-style callback.
*
* @param {Function} fn - function that expects a node-style callback
* @return {Function} When invoked with arguments, returns a promise resolved/rejected
* based on the results of the wrapped node-style callback
*/
Function (anonymous_238)
✓ Was called
exports.promisify = function(fn) {···
return function() {
var deferred = Vow.defer();
var args = [].slice.call(arguments);

args.push(function(err, result) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
});

fn.apply(null, args);

return deferred.promise();
};
};
exports.promisify = function(fn) {
Function (anonymous_239)
✓ Was called
return function() {···
var deferred = Vow.defer();
var args = [].slice.call(arguments);

args.push(function(err, result) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
});

fn.apply(null, args);

return deferred.promise();
};
return function() {
var deferred = Vow.defer();
var args = [].slice.call(arguments);
Function (anonymous_240)
✓ Was called
args.push(function(err, result) {···
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
});
args.push(function(err, result) {
Branch IfStatement
✓ Positive was executed (if)
if (err) {···
deferred.reject(err);
} else {
✓ Negative was executed (else)
} else {···
deferred.resolve(result);
}
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
});
fn.apply(null, args);
return deferred.promise();
};
};
/**
* All possible binary operators supported by JSCS
* @type {Array}
*/
exports.binaryOperators = [
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=',
'+', '-', '*', '/', '%', '<<', '>>', '>>>', '&',
'|', '^', '&&', '||', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='
];
/**
* Increment and decrement operators
* @type {Array}
*/
exports.incrementAndDecrementOperators = ['++', '--'];
/**
* All possible unary operators supported by JSCS
* @type {Array}
*/
exports.unaryOperators = ['-', '+', '!', '~'].concat(exports.incrementAndDecrementOperators);
/**
* All possible operators support by JSCS
* @type {Array}
*/
exports.operators = exports.binaryOperators.concat(exports.unaryOperators);
/**
* Returns a function that can check if a comment is a valid pragma.
*
* @param {Array} additionalExceptions can optionally be added to the existing pragmaKeywords
* @returns {Function} that can be used to determine if a comment (supplied as an argument is a valid pragma
*
*/
Function (anonymous_241)
✓ Was called
exports.isPragma = function(additionalExceptions) {···
var pragmaKeywords = [
'eslint',
'eslint-env',
'eslint-enable',
'eslint-disable',
'eslint-disable-line',
'eslint-disable-next-line',
'global',
'jshint',
'jslint',
'globals',
'falls through',
'exported',
'jscs:',
'jscs:enable',
'jscs:disable',
'jscs:ignore',
'istanbul'
];
if (additionalExceptions && Array.isArray(additionalExceptions)) {
pragmaKeywords = pragmaKeywords.concat(additionalExceptions);
}

return function(comment) {
// pragmaKeywords precede a space or the end of the comment
var trimmedComment = comment.trim() + ' ';
for (var i = 0; i < pragmaKeywords.length; i++) {
if (trimmedComment.indexOf(pragmaKeywords[i] + ' ') === 0) {
return true;
}
}
return false;
};
};
exports.isPragma = function(additionalExceptions) {
var pragmaKeywords = [
'eslint',
'eslint-env',
'eslint-enable',
'eslint-disable',
'eslint-disable-line',
'eslint-disable-next-line',
'global',
'jshint',
'jslint',
'globals',
'falls through',
'exported',
'jscs:',
'jscs:enable',
'jscs:disable',
'jscs:ignore',
'istanbul'
];
Branch IfStatement
✓ Positive was executed (if)
if (additionalExceptions && Array.isArray(additionalExceptions)) {···
pragmaKeywords = pragmaKeywords.concat(additionalExceptions);
}
✓ Negative was executed (else)
}···

return function(comment) {
Branch LogicalExpression
✓ Was returned
if (additionalExceptions && Array.isArray(additionalExceptions)) {
✓ Was returned
if (additionalExceptions && Array.isArray(additionalExceptions)) {
if (additionalExceptions && Array.isArray(additionalExceptions)) {
pragmaKeywords = pragmaKeywords.concat(additionalExceptions);
}
Function (anonymous_242)
✓ Was called
return function(comment) {···
// pragmaKeywords precede a space or the end of the comment
var trimmedComment = comment.trim() + ' ';
for (var i = 0; i < pragmaKeywords.length; i++) {
if (trimmedComment.indexOf(pragmaKeywords[i] + ' ') === 0) {
return true;
}
}
return false;
};
return function(comment) {
// pragmaKeywords precede a space or the end of the comment
var trimmedComment = comment.trim() + ' ';
for (var i = 0; i < pragmaKeywords.length; i++) {
Branch IfStatement
✓ Positive was executed (if)
if (trimmedComment.indexOf(pragmaKeywords[i] + ' ') === 0) {···
return true;
}
✓ Negative was executed (else)
}···
}
if (trimmedComment.indexOf(pragmaKeywords[i] + ' ') === 0) {
return true;
}
}
return false;
};
};
cli.js
/**
* Command line implementation for JSCS.
*
* See documentation on exit codes in - https://github.com/jscs-dev/node-jscs/wiki/Exit-codes
*
* Common usage case is:
*
* ./node_modules/.bin/jscs file1 dir1 file2 dir2
*/
var Vow = require('vow');
var exit = require('exit');
var Checker = require('./checker');
var configFile = require('./cli-config');
var ConfigGenerator = require('./config/generator');
Function cli
✓ Was called
module.exports = function cli(program) {···
var reporter;
var config;
var checkerPromise;
var defer = Vow.defer();
var promise = defer.promise();
var checker = new Checker();
var args = program.args;
var returnArgs = {
checker: checker,
reporter: program.reporter,
promise: promise
};

function handleMaxErrors() {
if (checker.maxErrorsExceeded()) {
console.error('Too many errors... Increase `maxErrors` configuration option value to see more.');
}
}

promise.always(function(status) {
exit(status.valueOf());
});

try {
config = configFile.load(program.config);
} catch (e) {
console.error('Config source is corrupted -', e.toString());
defer.reject(5);

return returnArgs;
}

/**
* Trying to load config.
* Custom config path can be specified using '-c' option.
*/
if (!config && !program.preset && !program.autoConfigure) {
if (program.config) {
console.error('Configuration source', program.config, 'was not found.');
} else {
console.error('No configuration found. Add a .jscsrc file to your project root or use the -c option.');
}

defer.reject(4);

return returnArgs;
}

if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
console.error('No input files specified. Try option --help for usage information.');
defer.reject(3);

return returnArgs;
}

reporter = configFile.getReporter(program.reporter, program.colors);

returnArgs.reporter = reporter.path;

if (!reporter.writer) {
console.error('Reporter "%s" does not exist.', program.reporter);
returnArgs.reporter = reporter.path;
defer.reject(6);

return returnArgs;
}

if (!config) {
config = {};
}

// To run autoconfigure over all errors in the path
if (program.autoConfigure) {
program.maxErrors = Infinity;
}

checker.getConfiguration().overrideFromCLI(program);
checker.getConfiguration().registerDefaultRules();

try {
checker.configure(config);
} catch (e) {
console.error(e.message);
defer.reject(1);

return returnArgs;
}
if (program.autoConfigure) {
var generator = new ConfigGenerator();

generator
.generate(program.autoConfigure)
.then(function() {
defer.resolve(0);
}, function(error) {
console.error('Configuration generation failed due to ', error);
defer.reject(7);
});

return returnArgs;
}

// Handle usage like 'cat myfile.js | jscs' or 'jscs -''
var usedDash = args[args.length - 1] === '-';
if (!args.length || usedDash) {
// So the dash doesn't register as a file
if (usedDash) { args.length--; }

if (program.fix) {
return {
promise: checker.fixStdin().then(function(result) {
process.stdout.write(result.output);
}),
checker: checker
};
}

checkerPromise = checker.checkStdin().then(function(errors) {
return [errors];
});
}

// Processing specified files and dirs.
if (args.length) {
checkerPromise = Vow.all(args.map(checker.execute, checker)).then(function(results) {
return [].concat.apply([], results);
});
}

checkerPromise.then(function(errorsCollection) {
reporter.writer(errorsCollection);
handleMaxErrors();

errorsCollection.forEach(function(errors) {
if (!errors.isEmpty()) {
defer.reject(2);
}
});

defer.resolve(0);
}).fail(function(e) {
console.error(e.stack);
defer.reject(1);
});

return returnArgs;
};
module.exports = function cli(program) {
var reporter;
var config;
var checkerPromise;
var defer = Vow.defer();
var promise = defer.promise();
var checker = new Checker();
var args = program.args;
var returnArgs = {
checker: checker,
reporter: program.reporter,
promise: promise
};
Function handleMaxErrors
✓ Was called
function handleMaxErrors() {···
if (checker.maxErrorsExceeded()) {
console.error('Too many errors... Increase `maxErrors` configuration option value to see more.');
}
}
function handleMaxErrors() {
Branch IfStatement
✓ Positive was executed (if)
if (checker.maxErrorsExceeded()) {···
console.error('Too many errors... Increase `maxErrors` configuration option value to see more.');
}
✓ Negative was executed (else)
}···
}
if (checker.maxErrorsExceeded()) {
console.error('Too many errors... Increase `maxErrors` configuration option value to see more.');
}
}
Function (anonymous_245)
✓ Was called
promise.always(function(status) {···
exit(status.valueOf());
});
promise.always(function(status) {
exit(status.valueOf());
});
try {
config = configFile.load(program.config);
} catch (e) {
console.error('Config source is corrupted -', e.toString());
defer.reject(5);
return returnArgs;
}
/**
* Trying to load config.
* Custom config path can be specified using '-c' option.
*/
Branch IfStatement
✓ Positive was executed (if)
if (!config && !program.preset && !program.autoConfigure) {···
if (program.config) {
console.error('Configuration source', program.config, 'was not found.');
} else {
console.error('No configuration found. Add a .jscsrc file to your project root or use the -c option.');
}

defer.reject(4);

return returnArgs;
}
✓ Negative was executed (else)
}···

if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
Branch LogicalExpression
✓ Was returned
if (!config && !program.preset && !program.autoConfigure) {
✓ Was returned
if (!config && !program.preset && !program.autoConfigure) {
Branch LogicalExpression
✓ Was returned
if (!config && !program.preset && !program.autoConfigure) {
✓ Was returned
if (!config && !program.preset && !program.autoConfigure) {
if (!config && !program.preset && !program.autoConfigure) {
Branch IfStatement
✓ Positive was executed (if)
if (program.config) {···
console.error('Configuration source', program.config, 'was not found.');
} else {
✓ Negative was executed (else)
} else {···
console.error('No configuration found. Add a .jscsrc file to your project root or use the -c option.');
}
if (program.config) {
console.error('Configuration source', program.config, 'was not found.');
} else {
console.error('No configuration found. Add a .jscsrc file to your project root or use the -c option.');
}
defer.reject(4);
return returnArgs;
}
Branch IfStatement
✓ Positive was executed (if)
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {···
console.error('No input files specified. Try option --help for usage information.');
defer.reject(3);

return returnArgs;
}
✓ Negative was executed (else)
}···

reporter = configFile.getReporter(program.reporter, program.colors);
Branch LogicalExpression
✓ Was returned
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
✓ Was returned
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
Branch LogicalExpression
✓ Was returned
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
✓ Was returned
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
if (!args.length && process.stdin.isTTY && typeof program.autoConfigure !== 'string') {
console.error('No input files specified. Try option --help for usage information.');
defer.reject(3);
return returnArgs;
}
reporter = configFile.getReporter(program.reporter, program.colors);
returnArgs.reporter = reporter.path;
Branch IfStatement
✓ Positive was executed (if)
if (!reporter.writer) {···
console.error('Reporter "%s" does not exist.', program.reporter);
returnArgs.reporter = reporter.path;
defer.reject(6);

return returnArgs;
}
✓ Negative was executed (else)
}···

if (!config) {
if (!reporter.writer) {
console.error('Reporter "%s" does not exist.', program.reporter);
returnArgs.reporter = reporter.path;
defer.reject(6);
return returnArgs;
}
Branch IfStatement
✓ Positive was executed (if)
if (!config) {···
config = {};
}
✓ Negative was executed (else)
}···

// To run autoconfigure over all errors in the path
if (!config) {
config = {};
}
// To run autoconfigure over all errors in the path
Branch IfStatement
✓ Positive was executed (if)
if (program.autoConfigure) {···
program.maxErrors = Infinity;
}
✓ Negative was executed (else)
}···

checker.getConfiguration().overrideFromCLI(program);
if (program.autoConfigure) {
program.maxErrors = Infinity;
}
checker.getConfiguration().overrideFromCLI(program);
checker.getConfiguration().registerDefaultRules();
try {
checker.configure(config);
} catch (e) {
console.error(e.message);
defer.reject(1);
return returnArgs;
}
Branch IfStatement
✓ Positive was executed (if)
if (program.autoConfigure) {···
var generator = new ConfigGenerator();

generator
.generate(program.autoConfigure)
.then(function() {
defer.resolve(0);
}, function(error) {
console.error('Configuration generation failed due to ', error);
defer.reject(7);
});

return returnArgs;
}
✓ Negative was executed (else)
}···

// Handle usage like 'cat myfile.js | jscs' or 'jscs -''
if (program.autoConfigure) {
var generator = new ConfigGenerator();
generator
.generate(program.autoConfigure)
Function (anonymous_246)
✓ Was called
.then(function() {···
defer.resolve(0);
}, function(error) {
.then(function() {
defer.resolve(0);
Function (anonymous_247)
✓ Was called
}, function(error) {···
console.error('Configuration generation failed due to ', error);
defer.reject(7);
});
}, function(error) {
console.error('Configuration generation failed due to ', error);
defer.reject(7);
});
return returnArgs;
}
// Handle usage like 'cat myfile.js | jscs' or 'jscs -''
var usedDash = args[args.length - 1] === '-';
Branch IfStatement
✓ Positive was executed (if)
if (!args.length || usedDash) {···
// So the dash doesn't register as a file
if (usedDash) { args.length--; }

if (program.fix) {
return {
promise: checker.fixStdin().then(function(result) {
process.stdout.write(result.output);
}),
checker: checker
};
}

checkerPromise = checker.checkStdin().then(function(errors) {
return [errors];
});
}
✓ Negative was executed (else)
}···

// Processing specified files and dirs.
Branch LogicalExpression
✓ Was returned
if (!args.length || usedDash) {
✓ Was returned
if (!args.length || usedDash) {
if (!args.length || usedDash) {
// So the dash doesn't register as a file
Branch IfStatement
✓ Positive was executed (if)
if (usedDash) { args.length--; }
✓ Negative was executed (else)
if (usedDash) { args.length--; }···

if (program.fix) {
if (usedDash) { args.length--; }
Branch IfStatement
✓ Positive was executed (if)
if (program.fix) {···
return {
promise: checker.fixStdin().then(function(result) {
process.stdout.write(result.output);
}),
checker: checker
};
}
✓ Negative was executed (else)
}···

checkerPromise = checker.checkStdin().then(function(errors) {
if (program.fix) {
return {
Function (anonymous_248)
✓ Was called
promise: checker.fixStdin().then(function(result) {···
process.stdout.write(result.output);
}),
promise: checker.fixStdin().then(function(result) {
process.stdout.write(result.output);
}),
checker: checker
};
}
Function (anonymous_249)
✓ Was called
checkerPromise = checker.checkStdin().then(function(errors) {···
return [errors];
});
checkerPromise = checker.checkStdin().then(function(errors) {
return [errors];
});
}
// Processing specified files and dirs.
Branch IfStatement
✓ Positive was executed (if)
if (args.length) {···
checkerPromise = Vow.all(args.map(checker.execute, checker)).then(function(results) {
return [].concat.apply([], results);
});
}
✓ Negative was executed (else)
}···

checkerPromise.then(function(errorsCollection) {
if (args.length) {
Function (anonymous_250)
✓ Was called
checkerPromise = Vow.all(args.map(checker.execute, checker)).then(function(results) {···
return [].concat.apply([], results);
});
checkerPromise = Vow.all(args.map(checker.execute, checker)).then(function(results) {
return [].concat.apply([], results);
});
}
Function (anonymous_251)
✓ Was called
checkerPromise.then(function(errorsCollection) {···
reporter.writer(errorsCollection);
handleMaxErrors();

errorsCollection.forEach(function(errors) {
if (!errors.isEmpty()) {
defer.reject(2);
}
});

defer.resolve(0);
}).fail(function(e) {
checkerPromise.then(function(errorsCollection) {
reporter.writer(errorsCollection);
handleMaxErrors();
Function (anonymous_252)
✓ Was called
errorsCollection.forEach(function(errors) {···
if (!errors.isEmpty()) {
defer.reject(2);
}
});
errorsCollection.forEach(function(errors) {
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
defer.reject(2);
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
defer.reject(2);
}
});
defer.resolve(0);
Function (anonymous_253)
✓ Was called
}).fail(function(e) {···
console.error(e.stack);
defer.reject(1);
});
}).fail(function(e) {
console.error(e.stack);
defer.reject(1);
});
return returnArgs;
};
generator.js
var fs = require('fs');
var Vow = require('vow');
var Table = require('cli-table');
var prompt = require('prompt');
var chalk = require('chalk');
var assign = require('lodash').assign;
var Checker = require('../checker');
var utils = require('../utils');
prompt.message = '';
prompt.delimiter = '';
prompt.start();
/**
* Script that walks the user through the autoconfig flow
*
* @type {String[]}
* @private
*/
var prompts = [
{
name: chalk.green('Please choose a preset number:'),
require: true,
pattern: /\d+/
},
{
name: 'Create an (e)xception for this rule, or (f)ix the errors yourself?',
require: true,
pattern: /(e|f)/
}
];
/**
* JSCS Configuration Generator
*
* @name Generator
*/
Function Generator
✓ Was called
function Generator() {···
this._config = {};
}
function Generator() {
this._config = {};
}
/**
* Generates a configuration object based for the given path
* based on the best fitting preset
*
* @param {String} path - The path containing file(s) used to guide the configuration
*
* @return {Promise} Resolved with the generated, JSCS configuration
*/
Function (anonymous_255)
✓ Was called
Generator.prototype.generate = function(path) {···
var checker = getChecker();
var _path = utils.normalizePath(path, checker.getConfiguration().getBasePath());
var presetNames = Object.keys(checker.getConfiguration().getRegisteredPresets());
var statsForPresets;

console.log('Checking', _path, 'against the presets');

return Vow
.all(presetNames.map(this._checkAgainstPreset.bind(this, _path)))
.then(function(resultsPerPreset) {
statsForPresets = this._generateStatsForPresets(resultsPerPreset, presetNames);
return statsForPresets;
}.bind(this))
.then(this._showErrorCounts.bind(this))
.then(this._getUserPresetChoice.bind(this, prompts[0]))
.then(function showViolatedRules(choiceObj) {
var presetIndex = choiceObj[prompts[0].name] - 1;
var presetName = statsForPresets[presetIndex].name;

console.log('You chose the ' + presetName + ' preset');

this._config.preset = presetName;

var errorStats = getErrorsByRuleName(statsForPresets[presetIndex].errors);

var violatedRuleCount = Object.keys(errorStats).length;

if (!violatedRuleCount) { return this._config; }

console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));

var errorPrompts = generateRuleHandlingPrompts(errorStats);

return this._getUserViolationChoices(errorPrompts)
.then(this._handleViolatedRules.bind(this, errorPrompts))
.then(function() {
return this._config;
}.bind(this));
}.bind(this))
.then(function flushConfig() {
fs.writeFileSync(process.cwd() + '/.jscsrc', JSON.stringify(this._config, null, '\t'));
console.log('Generated a .jscsrc configuration file in ' + process.cwd());
}.bind(this));
};
Generator.prototype.generate = function(path) {
var checker = getChecker();
var _path = utils.normalizePath(path, checker.getConfiguration().getBasePath());
var presetNames = Object.keys(checker.getConfiguration().getRegisteredPresets());
var statsForPresets;
console.log('Checking', _path, 'against the presets');
return Vow
.all(presetNames.map(this._checkAgainstPreset.bind(this, _path)))
Function (anonymous_256)
✓ Was called
.then(function(resultsPerPreset) {···
statsForPresets = this._generateStatsForPresets(resultsPerPreset, presetNames);
return statsForPresets;
}.bind(this))
.then(function(resultsPerPreset) {
statsForPresets = this._generateStatsForPresets(resultsPerPreset, presetNames);
return statsForPresets;
}.bind(this))
.then(this._showErrorCounts.bind(this))
.then(this._getUserPresetChoice.bind(this, prompts[0]))
Function showViolatedRules
✓ Was called
.then(function showViolatedRules(choiceObj) {···
var presetIndex = choiceObj[prompts[0].name] - 1;
var presetName = statsForPresets[presetIndex].name;

console.log('You chose the ' + presetName + ' preset');

this._config.preset = presetName;

var errorStats = getErrorsByRuleName(statsForPresets[presetIndex].errors);

var violatedRuleCount = Object.keys(errorStats).length;

if (!violatedRuleCount) { return this._config; }

console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));

var errorPrompts = generateRuleHandlingPrompts(errorStats);

return this._getUserViolationChoices(errorPrompts)
.then(this._handleViolatedRules.bind(this, errorPrompts))
.then(function() {
return this._config;
}.bind(this));
}.bind(this))
.then(function showViolatedRules(choiceObj) {
var presetIndex = choiceObj[prompts[0].name] - 1;
var presetName = statsForPresets[presetIndex].name;
console.log('You chose the ' + presetName + ' preset');
this._config.preset = presetName;
var errorStats = getErrorsByRuleName(statsForPresets[presetIndex].errors);
var violatedRuleCount = Object.keys(errorStats).length;
Branch IfStatement
✗ Positive was not executed (if)
if (!violatedRuleCount) { return this._config; }
✓ Negative was executed (else)
if (!violatedRuleCount) { return this._config; }···

console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));
if (!violatedRuleCount) { return this._config; }
Branch ConditionalExpression
✓ Positive was returned (? ...)
console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));
✗ Negative was not returned (: ...)
console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));
console.log(_path + ' violates ' + violatedRuleCount + ' rule' + (violatedRuleCount > 1 ? 's' : ''));
var errorPrompts = generateRuleHandlingPrompts(errorStats);
return this._getUserViolationChoices(errorPrompts)
.then(this._handleViolatedRules.bind(this, errorPrompts))
Function (anonymous_258)
✗ Was not called
.then(function() {···
return this._config;
}.bind(this));
.then(function() {
return this._config;
}.bind(this));
}.bind(this))
Function flushConfig
✗ Was not called
.then(function flushConfig() {···
fs.writeFileSync(process.cwd() + '/.jscsrc', JSON.stringify(this._config, null, '\t'));
console.log('Generated a .jscsrc configuration file in ' + process.cwd());
}.bind(this));
.then(function flushConfig() {
fs.writeFileSync(process.cwd() + '/.jscsrc', JSON.stringify(this._config, null, '\t'));
console.log('Generated a .jscsrc configuration file in ' + process.cwd());
}.bind(this));
};
/**
* @private
* @param {Array.<Object[]>} resultsPerPreset - List of error objects for each preset's run of checkPath
* @param {String[]} presetNames
* @return {Object[]} Aggregated datapoints for each preset
*/
Function (anonymous_260)
✓ Was called
Generator.prototype._generateStatsForPresets = function(resultsPerPreset, presetNames) {···
return resultsPerPreset.map(function(presetResults, idx) {
var errorCollection = [].concat.apply([], presetResults);

var presetStats = {
name: presetNames[idx],
sum: 0,
errors: []
};

errorCollection.forEach(function(error) {
presetStats.sum += error.getErrorCount();
presetStats.errors = presetStats.errors.concat(error.getErrorList());
});

return presetStats;
});
};
Generator.prototype._generateStatsForPresets = function(resultsPerPreset, presetNames) {
Function (anonymous_261)
✓ Was called
return resultsPerPreset.map(function(presetResults, idx) {···
var errorCollection = [].concat.apply([], presetResults);

var presetStats = {
name: presetNames[idx],
sum: 0,
errors: []
};

errorCollection.forEach(function(error) {
presetStats.sum += error.getErrorCount();
presetStats.errors = presetStats.errors.concat(error.getErrorList());
});

return presetStats;
});
return resultsPerPreset.map(function(presetResults, idx) {
var errorCollection = [].concat.apply([], presetResults);
var presetStats = {
name: presetNames[idx],
sum: 0,
errors: []
};
Function (anonymous_262)
✓ Was called
errorCollection.forEach(function(error) {···
presetStats.sum += error.getErrorCount();
presetStats.errors = presetStats.errors.concat(error.getErrorList());
});
errorCollection.forEach(function(error) {
presetStats.sum += error.getErrorCount();
presetStats.errors = presetStats.errors.concat(error.getErrorList());
});
return presetStats;
});
};
/**
* @private
* @param {Object[]} statsForPresets
*/
Function (anonymous_263)
✓ Was called
Generator.prototype._showErrorCounts = function(statsForPresets) {···
var table = getTable();

statsForPresets.forEach(function(presetStats, idx) {
table.push([idx + 1, presetStats.name, presetStats.sum, getUniqueErrorNames(presetStats.errors).length]);
});

console.log(table.toString());
};
Generator.prototype._showErrorCounts = function(statsForPresets) {
var table = getTable();
Function (anonymous_264)
✓ Was called
statsForPresets.forEach(function(presetStats, idx) {···
table.push([idx + 1, presetStats.name, presetStats.sum, getUniqueErrorNames(presetStats.errors).length]);
});
statsForPresets.forEach(function(presetStats, idx) {
table.push([idx + 1, presetStats.name, presetStats.sum, getUniqueErrorNames(presetStats.errors).length]);
});
console.log(table.toString());
};
/**
* Prompts the user to choose a preset
*
* @private
* @param {Object} prompt
* @return {Promise}
*/
Function (anonymous_265)
✓ Was called
Generator.prototype._getUserPresetChoice = function(prompt) {···
return this._showPrompt(prompt);
};
Generator.prototype._getUserPresetChoice = function(prompt) {
return this._showPrompt(prompt);
};
/**
* Prompts the user to nullify rules or fix violations themselves
*
* @private
* @param {Object[]} errorPrompts
* @return {Promise}
*/
Function (anonymous_266)
✓ Was called
Generator.prototype._getUserViolationChoices = function(errorPrompts) {···
return this._showPrompt(errorPrompts);
};
Generator.prototype._getUserViolationChoices = function(errorPrompts) {
return this._showPrompt(errorPrompts);
};
/** @private */
Generator.prototype._showPrompt = utils.promisify(prompt.get.bind(prompt));
/**
* @private
* @param {Object[]} errorPrompts
* @param {Object} choices
*/
Function (anonymous_267)
✗ Was not called
Generator.prototype._handleViolatedRules = function(errorPrompts, choices) {···
errorPrompts.forEach(function(errorPrompt) {
var userChoice = choices[errorPrompt.name];

if (userChoice && userChoice.toLowerCase() === 'e') {
this._config[errorPrompt.associatedRuleName] = null;
}
}, this);
};
Generator.prototype._handleViolatedRules = function(errorPrompts, choices) {
Function (anonymous_268)
✗ Was not called
errorPrompts.forEach(function(errorPrompt) {···
var userChoice = choices[errorPrompt.name];

if (userChoice && userChoice.toLowerCase() === 'e') {
this._config[errorPrompt.associatedRuleName] = null;
}
}, this);
errorPrompts.forEach(function(errorPrompt) {
var userChoice = choices[errorPrompt.name];
Branch IfStatement
✗ Positive was not executed (if)
if (userChoice && userChoice.toLowerCase() === 'e') {···
this._config[errorPrompt.associatedRuleName] = null;
}
✗ Negative was not executed (else)
}···
}, this);
Branch LogicalExpression
✗ Was not returned
if (userChoice && userChoice.toLowerCase() === 'e') {
✗ Was not returned
if (userChoice && userChoice.toLowerCase() === 'e') {
if (userChoice && userChoice.toLowerCase() === 'e') {
this._config[errorPrompt.associatedRuleName] = null;
}
}, this);
};
/**
* @private
* @param {String} path
* @param {String} presetName
* @return {Promise}
*/
Function (anonymous_269)
✓ Was called
Generator.prototype._checkAgainstPreset = function(path, presetName) {···
var checker = getChecker();

checker.configure({preset: presetName, maxErrors: Infinity});

return checker.checkPath(path);
};
Generator.prototype._checkAgainstPreset = function(path, presetName) {
var checker = getChecker();
checker.configure({preset: presetName, maxErrors: Infinity});
return checker.checkPath(path);
};
/**
* @private
* @return {module:lib/Checker}
*/
Function getChecker
✓ Was called
function getChecker() {···
var checker = new Checker();
checker.registerDefaultRules();
return checker;
}
function getChecker() {
var checker = new Checker();
checker.registerDefaultRules();
return checker;
}
/**
* @private
* @param {Object} errors
* @return {Object[]}
*/
Function generateRuleHandlingPrompts
✓ Was called
function generateRuleHandlingPrompts(errors) {···
// Generate list of rule names, sorted by violation count (descending)
var violatedRuleNames = Object.keys(errors);
violatedRuleNames.sort(function(a, b) {
return errors[b].violations - errors[a].violations;
});

return violatedRuleNames.map(function(ruleName) {
var violationCount = errors[ruleName].violations;
var fileCount = Object.keys(errors[ruleName].files).length;
var prompt = assign({}, prompts[1]);

prompt.associatedRuleName = ruleName;
prompt.name = chalk.green(ruleName) +
' (' + violationCount + ' violation' + (violationCount > 1 ? 's' : '') +
' in ' + fileCount + ' file' + (fileCount > 1 ? 's' : '') + '):\n ' +
prompt.name;
return prompt;
});
}
function generateRuleHandlingPrompts(errors) {
// Generate list of rule names, sorted by violation count (descending)
var violatedRuleNames = Object.keys(errors);
Function (anonymous_272)
✓ Was called
violatedRuleNames.sort(function(a, b) {···
return errors[b].violations - errors[a].violations;
});
violatedRuleNames.sort(function(a, b) {
return errors[b].violations - errors[a].violations;
});
Function (anonymous_273)
✓ Was called
return violatedRuleNames.map(function(ruleName) {···
var violationCount = errors[ruleName].violations;
var fileCount = Object.keys(errors[ruleName].files).length;
var prompt = assign({}, prompts[1]);

prompt.associatedRuleName = ruleName;
prompt.name = chalk.green(ruleName) +
' (' + violationCount + ' violation' + (violationCount > 1 ? 's' : '') +
' in ' + fileCount + ' file' + (fileCount > 1 ? 's' : '') + '):\n ' +
prompt.name;
return prompt;
});
return violatedRuleNames.map(function(ruleName) {
var violationCount = errors[ruleName].violations;
var fileCount = Object.keys(errors[ruleName].files).length;
var prompt = assign({}, prompts[1]);
prompt.associatedRuleName = ruleName;
prompt.name = chalk.green(ruleName) +
Branch ConditionalExpression
✓ Positive was returned (? ...)
' (' + violationCount + ' violation' + (violationCount > 1 ? 's' : '') +
✓ Negative was returned (: ...)
' (' + violationCount + ' violation' + (violationCount > 1 ? 's' : '') +
' (' + violationCount + ' violation' + (violationCount > 1 ? 's' : '') +
Branch ConditionalExpression
✗ Positive was not returned (? ...)
' in ' + fileCount + ' file' + (fileCount > 1 ? 's' : '') + '):\n ' +
✓ Negative was returned (: ...)
' in ' + fileCount + ' file' + (fileCount > 1 ? 's' : '') + '):\n ' +
' in ' + fileCount + ' file' + (fileCount > 1 ? 's' : '') + '):\n ' +
prompt.name;
return prompt;
});
}
/**
* @private
* @param {Object[]} errorsList
* @return {Object}
*/
Function getErrorsByRuleName
✓ Was called
function getErrorsByRuleName(errorsList) {···
var errors = {};

errorsList.forEach(function(error) {
var rulename = error.rule;
errors[rulename] = errors[rulename] || {
files: {},
violations: 0
};
errors[rulename].violations += 1;
errors[rulename].files[error.filename] = true;
});

return errors;
}
function getErrorsByRuleName(errorsList) {
var errors = {};
Function (anonymous_275)
✓ Was called
errorsList.forEach(function(error) {···
var rulename = error.rule;
errors[rulename] = errors[rulename] || {
files: {},
violations: 0
};
errors[rulename].violations += 1;
errors[rulename].files[error.filename] = true;
});
errorsList.forEach(function(error) {
var rulename = error.rule;
Branch LogicalExpression
✓ Was returned
errors[rulename] = errors[rulename] || {···
files: {},
violations: 0
};
✓ Was returned
errors[rulename] = errors[rulename] || {
errors[rulename] = errors[rulename] || {
files: {},
violations: 0
};
errors[rulename].violations += 1;
errors[rulename].files[error.filename] = true;
});
return errors;
}
/**
* @private
* @param {Object[]} errorsList
* @return {String[]}
*/
Function getUniqueErrorNames
✓ Was called
function getUniqueErrorNames(errorsList) {···
var errorNameLUT = {};

errorsList.forEach(function(error) {
errorNameLUT[error.rule] = true;
});

return Object.keys(errorNameLUT);
}
function getUniqueErrorNames(errorsList) {
var errorNameLUT = {};
Function (anonymous_277)
✓ Was called
errorsList.forEach(function(error) {···
errorNameLUT[error.rule] = true;
});
errorsList.forEach(function(error) {
errorNameLUT[error.rule] = true;
});
return Object.keys(errorNameLUT);
}
/**
* @private
* @return {Object}
*/
Function getTable
✓ Was called
function getTable() {···
return new Table({
chars: {
top: '', 'top-mid': '', 'top-left': '', 'top-right': '',
bottom: '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
left: '', 'left-mid': '',
mid: '', 'mid-mid': '',
right: '', 'right-mid': '' ,
middle: ' '
},
style: {
'padding-left': 0,
'padding-right': 0
},
head: ['', 'Preset', '#Errors', '#Rules']
});
}
function getTable() {
return new Table({
chars: {
top: '', 'top-mid': '', 'top-left': '', 'top-right': '',
bottom: '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
left: '', 'left-mid': '',
mid: '', 'mid-mid': '',
right: '', 'right-mid': '' ,
middle: ' '
},
style: {
'padding-left': 0,
'padding-right': 0
},
head: ['', 'Preset', '#Errors', '#Rules']
});
}
module.exports = Generator;
checkstyle.js
Function escapeAttrValue
✓ Was called
function escapeAttrValue(attrValue) {···
return String(attrValue)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function escapeAttrValue(attrValue) {
return String(attrValue)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
Function (anonymous_280)
✓ Was called
module.exports = function(errorCollection) {···
console.log('<?xml version="1.0" encoding="utf-8"?>\n<checkstyle version="4.3">');
errorCollection.forEach(function(errors) {
console.log(' <file name="' + escapeAttrValue(errors.getFilename()) + '">');
errors.getErrorList().forEach(function(error) {
console.log(
' <error ' +
'line="' + error.line + '" ' +
'column="' + (error.column + 1) + '" ' +
'severity="error" ' +
'message="' + escapeAttrValue(error.message) + '" ' +
'source="jscs" />'
);
});
console.log(' </file>');
});
console.log('</checkstyle>');
};
module.exports = function(errorCollection) {
console.log('<?xml version="1.0" encoding="utf-8"?>\n<checkstyle version="4.3">');
Function (anonymous_281)
✓ Was called
errorCollection.forEach(function(errors) {···
console.log(' <file name="' + escapeAttrValue(errors.getFilename()) + '">');
errors.getErrorList().forEach(function(error) {
console.log(
' <error ' +
'line="' + error.line + '" ' +
'column="' + (error.column + 1) + '" ' +
'severity="error" ' +
'message="' + escapeAttrValue(error.message) + '" ' +
'source="jscs" />'
);
});
console.log(' </file>');
});
errorCollection.forEach(function(errors) {
console.log(' <file name="' + escapeAttrValue(errors.getFilename()) + '">');
Function (anonymous_282)
✓ Was called
errors.getErrorList().forEach(function(error) {···
console.log(
' <error ' +
'line="' + error.line + '" ' +
'column="' + (error.column + 1) + '" ' +
'severity="error" ' +
'message="' + escapeAttrValue(error.message) + '" ' +
'source="jscs" />'
);
});
errors.getErrorList().forEach(function(error) {
console.log(
' <error ' +
'line="' + error.line + '" ' +
'column="' + (error.column + 1) + '" ' +
'severity="error" ' +
'message="' + escapeAttrValue(error.message) + '" ' +
'source="jscs" />'
);
});
console.log(' </file>');
});
console.log('</checkstyle>');
};
console.js
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_283)
✓ Was called
module.exports = function(errorsCollection) {···
var errorCount = 0;
/**
* Formatting every error set.
*/
errorsCollection.forEach(function(errors) {
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error, true) + '\n');
});
}
});
if (errorCount) {
/**
* Printing summary.
*/
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
};
module.exports = function(errorsCollection) {
var errorCount = 0;
/**
* Formatting every error set.
*/
Function (anonymous_284)
✓ Was called
errorsCollection.forEach(function(errors) {···
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error, true) + '\n');
});
}
});
errorsCollection.forEach(function(errors) {
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error, true) + '\n');
});
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
Function (anonymous_285)
✓ Was called
errors.getErrorList().forEach(function(error) {···
errorCount++;
console.log(errors.explainError(error, true) + '\n');
});
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error, true) + '\n');
});
}
});
Branch IfStatement
✓ Positive was executed (if)
if (errorCount) {···
/**
* Printing summary.
*/
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
✓ Negative was executed (else)
}···
};
if (errorCount) {
/**
* Printing summary.
*/
Branch ConditionalExpression
✓ Positive was returned (? ...)
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
✓ Negative was returned (: ...)
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
};
inline.js
var util = require('util');
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_286)
✓ Was called
module.exports = function(errorsCollection) {···
var errorCount = 0;
/**
* Formatting every error set.
*/
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
if (!errors.isEmpty()) {
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message));
});
}
});
};
module.exports = function(errorsCollection) {
var errorCount = 0;
/**
* Formatting every error set.
*/
Function (anonymous_287)
✓ Was called
errorsCollection.forEach(function(errors) {···
var file = errors.getFilename();
if (!errors.isEmpty()) {
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message));
});
}
});
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message));
});
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
Function (anonymous_288)
✓ Was called
errors.getErrorList().forEach(function(error) {···
errorCount++;
console.log(util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message));
});
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message));
});
}
});
};
inlinesingle.js
/**
* inlinesingle solves an issue that Windows (7+) users have been
* experiencing using SublimeLinter-jscs. It appears this is due to
* SublimeText not managing multi-line output properly on these machines.
* This reporter differs from inline.js by producing one comment line
* separated by linebreaks rather than a series of separate lines.
*/
var util = require('util');
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_289)
✓ Was called
module.exports = function(errorsCollection) {···
errorsCollection.forEach(function(errors) {
if (!errors.isEmpty()) {
var file = errors.getFilename();
var out = errors.getErrorList().map(function(error) {
return util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message);
});
console.log(out.join('\n'));
}
});
};
module.exports = function(errorsCollection) {
Function (anonymous_290)
✓ Was called
errorsCollection.forEach(function(errors) {···
if (!errors.isEmpty()) {
var file = errors.getFilename();
var out = errors.getErrorList().map(function(error) {
return util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message);
});
console.log(out.join('\n'));
}
});
errorsCollection.forEach(function(errors) {
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
var file = errors.getFilename();
var out = errors.getErrorList().map(function(error) {
return util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message);
});
console.log(out.join('\n'));
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
var file = errors.getFilename();
Function (anonymous_291)
✓ Was called
var out = errors.getErrorList().map(function(error) {···
return util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message);
});
var out = errors.getErrorList().map(function(error) {
return util.format('%s: line %d, col %d, %s', file, error.line, error.column, error.message);
});
console.log(out.join('\n'));
}
});
};
json.js
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_292)
✓ Was called
module.exports = function(errorsCollection) {···
var jsonOutput = {};
var anyError = false;
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
var arr = jsonOutput[file] = [];

if (!errors.isEmpty()) {
anyError = true;
}
errors.getErrorList().forEach(function(error) {
arr.push({
line: error.line,
column: error.column + 1,
message: error.message
});
});
});
if (anyError) {
console.log(JSON.stringify(jsonOutput));
}
};
module.exports = function(errorsCollection) {
var jsonOutput = {};
var anyError = false;
Function (anonymous_293)
✓ Was called
errorsCollection.forEach(function(errors) {···
var file = errors.getFilename();
var arr = jsonOutput[file] = [];

if (!errors.isEmpty()) {
anyError = true;
}
errors.getErrorList().forEach(function(error) {
arr.push({
line: error.line,
column: error.column + 1,
message: error.message
});
});
});
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
var arr = jsonOutput[file] = [];
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
anyError = true;
}
✓ Negative was executed (else)
}···
errors.getErrorList().forEach(function(error) {
if (!errors.isEmpty()) {
anyError = true;
}
Function (anonymous_294)
✓ Was called
errors.getErrorList().forEach(function(error) {···
arr.push({
line: error.line,
column: error.column + 1,
message: error.message
});
});
errors.getErrorList().forEach(function(error) {
arr.push({
line: error.line,
column: error.column + 1,
message: error.message
});
});
});
Branch IfStatement
✓ Positive was executed (if)
if (anyError) {···
console.log(JSON.stringify(jsonOutput));
}
✓ Negative was executed (else)
}···
};
if (anyError) {
console.log(JSON.stringify(jsonOutput));
}
};
junit.js
var xml = require('xmlbuilder');
Function (anonymous_295)
✓ Was called
module.exports = function(errorCollection) {···
var i = 0;
var testsuite = xml.create('testsuite');

testsuite.att('name', 'JSCS');
testsuite.att('tests', errorCollection.length);

errorCollection.forEach(function(errors) {
var errorsCount = errors.getErrorCount();
var testcase = testsuite.ele('testcase', {
name: errors.getFilename(),
failures: errorsCount
});

i += errorsCount;

errors.getErrorList().forEach(function(error) {
testcase.ele('failure', {}, errors.explainError(error));
});
});

testsuite.att('failures', i);

console.log(testsuite.end({pretty: true}));
};
module.exports = function(errorCollection) {
var i = 0;
var testsuite = xml.create('testsuite');
testsuite.att('name', 'JSCS');
testsuite.att('tests', errorCollection.length);
Function (anonymous_296)
✓ Was called
errorCollection.forEach(function(errors) {···
var errorsCount = errors.getErrorCount();
var testcase = testsuite.ele('testcase', {
name: errors.getFilename(),
failures: errorsCount
});

i += errorsCount;

errors.getErrorList().forEach(function(error) {
testcase.ele('failure', {}, errors.explainError(error));
});
});
errorCollection.forEach(function(errors) {
var errorsCount = errors.getErrorCount();
var testcase = testsuite.ele('testcase', {
name: errors.getFilename(),
failures: errorsCount
});
i += errorsCount;
Function (anonymous_297)
✓ Was called
errors.getErrorList().forEach(function(error) {···
testcase.ele('failure', {}, errors.explainError(error));
});
errors.getErrorList().forEach(function(error) {
testcase.ele('failure', {}, errors.explainError(error));
});
});
testsuite.att('failures', i);
console.log(testsuite.end({pretty: true}));
};
disallow-anonymous-functions.js
/**
* Requires that a function expression be named.
* Named functions provide more information in the error stack trace than anonymous functions.
*
* This option does not help if you use Arrow functions (ES6) which are always anonymous.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowAnonymousFunctions": true
* ```
*
* ##### Valid
*
* ```js
* var a = function foo(){
*
* };
*
* $('#foo').click(function bar(){
*
* });
* ```
*
* ##### Invalid
*
* ```js
* var a = function(){
*
* };
*
* $('#foo').click(function(){
*
* });
* ```
*/
var assert = require('assert');
Function (anonymous_298)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_299)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_300)
✓ Was called
getOptionName: function() {···
return 'disallowAnonymousFunctions';
},
getOptionName: function() {
return 'disallowAnonymousFunctions';
},
Function (anonymous_301)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {
if (node.id === null) {
errors.add('Anonymous functions need to be named', node);
}
});
}
check: function(file, errors) {
Function (anonymous_302)
✓ Was called
file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {···
if (node.id === null) {
errors.add('Anonymous functions need to be named', node);
}
});
file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.id === null) {···
errors.add('Anonymous functions need to be named', node);
}
✓ Negative was executed (else)
}···
});
if (node.id === null) {
errors.add('Anonymous functions need to be named', node);
}
});
}
};
disallow-array-destructuring-return.js
/**
* Requires object destructuring for multiple return values,
* not array destructuring.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "disallowArrayDestructuringReturn": true
* ```
*
* ##### Valid
*
* ```js
* const { left, right } = processInput(input);
* ```
*
* ##### Invalid
*
* ```js
* const [ left, __, top ] = processInput(input);
* ```
*/
var assert = require('assert');
Function (anonymous_303)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_304)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_305)
✓ Was called
getOptionName: function() {···
return 'disallowArrayDestructuringReturn';
},
getOptionName: function() {
return 'disallowArrayDestructuringReturn';
},
Function (anonymous_306)
✓ Was called
check: function(file, errors) {···
var addError = function(node) {
errors.add(
'Array destructuring is not allowed for return, ' +
'use object destructuring instead',
node
);
};

var isViolationDetected = function(maybeArrayPattern, maybeCallExpression) {

return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
};

file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {

if (node.type === 'VariableDeclaration') {
node.declarations.forEach(function(declaration) {
if (!isViolationDetected(declaration.id, declaration.init)) {
return;
}

addError(declaration.init);
});
}

if (node.type === 'AssignmentExpression') {
if (!isViolationDetected(node.left, node.right)) {
return;
}

addError(node.right);
}
});
}
check: function(file, errors) {
Function (anonymous_307)
✓ Was called
var addError = function(node) {···
errors.add(
'Array destructuring is not allowed for return, ' +
'use object destructuring instead',
node
);
};
var addError = function(node) {
errors.add(
'Array destructuring is not allowed for return, ' +
'use object destructuring instead',
node
);
};
Function (anonymous_308)
✓ Was called
var isViolationDetected = function(maybeArrayPattern, maybeCallExpression) {···

return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
};
var isViolationDetected = function(maybeArrayPattern, maybeCallExpression) {
Branch LogicalExpression
✓ Was returned
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
✗ Was not returned
return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&···
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
Branch LogicalExpression
✓ Was returned
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
✗ Was not returned
return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
Branch LogicalExpression
✓ Was returned
return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
✗ Was not returned
return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
return maybeCallExpression && maybeCallExpression.type === 'CallExpression' &&
maybeArrayPattern && maybeArrayPattern.type === 'ArrayPattern';
};
Function (anonymous_309)
✓ Was called
file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {···

if (node.type === 'VariableDeclaration') {
node.declarations.forEach(function(declaration) {
if (!isViolationDetected(declaration.id, declaration.init)) {
return;
}

addError(declaration.init);
});
}

if (node.type === 'AssignmentExpression') {
if (!isViolationDetected(node.left, node.right)) {
return;
}

addError(node.right);
}
});
file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclaration') {···
node.declarations.forEach(function(declaration) {
if (!isViolationDetected(declaration.id, declaration.init)) {
return;
}

addError(declaration.init);
});
}
✓ Negative was executed (else)
}···

if (node.type === 'AssignmentExpression') {
if (node.type === 'VariableDeclaration') {
Function (anonymous_310)
✓ Was called
node.declarations.forEach(function(declaration) {···
if (!isViolationDetected(declaration.id, declaration.init)) {
return;
}

addError(declaration.init);
});
node.declarations.forEach(function(declaration) {
Branch IfStatement
✓ Positive was executed (if)
if (!isViolationDetected(declaration.id, declaration.init)) {···
return;
}
✓ Negative was executed (else)
}···

addError(declaration.init);
if (!isViolationDetected(declaration.id, declaration.init)) {
return;
}
addError(declaration.init);
});
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'AssignmentExpression') {···
if (!isViolationDetected(node.left, node.right)) {
return;
}

addError(node.right);
}
✓ Negative was executed (else)
}···
});
if (node.type === 'AssignmentExpression') {
Branch IfStatement
✓ Positive was executed (if)
if (!isViolationDetected(node.left, node.right)) {···
return;
}
✓ Negative was executed (else)
}···

addError(node.right);
if (!isViolationDetected(node.left, node.right)) {
return;
}
addError(node.right);
}
});
}
};
disallow-arrow-functions.js
/**
* Disallows arrow functions.
*
* Why enable this rule? Arrow functions might cause more problems than they
* solve:
*
* - Object-orientation may be better without ECMAScript's `this`.
* - You can't name an arrow function.
* - Arrow functions' syntax can cause maintenance issues; see
* `disallowShorthandArrowFunctions`.
* - Arrow functions shouldn't be used on prototypes, as objects' methods,
* as event listeners, or as anything polymorhpic- or mixin-related. See
* [here](https://gist.github.com/qubyte/43e0093274e793cc82ba#gistcomment-1292183).
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "disallowArrowFunctions": true
* ```
*
* ##### Valid
*
* ```js
* // function expression in a callback
* [1, 2, 3].map(function (x) {
* return x * x;
* });
* ```
*
* ##### Invalid
*
* ```js
* // arrow function
* [1, 2, 3].map((x) => {
* return x * x;
* });
* ```
*/
var assert = require('assert');
Function (anonymous_311)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_312)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_313)
✓ Was called
getOptionName: function() {···
return 'disallowArrowFunctions';
},
getOptionName: function() {
return 'disallowArrowFunctions';
},
Function (anonymous_314)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ArrowFunctionExpression'], function(node) {
errors.add('Do not use arrow functions', node);
});
}
check: function(file, errors) {
Function (anonymous_315)
✓ Was called
file.iterateNodesByType(['ArrowFunctionExpression'], function(node) {···
errors.add('Do not use arrow functions', node);
});
file.iterateNodesByType(['ArrowFunctionExpression'], function(node) {
errors.add('Do not use arrow functions', node);
});
}
};
disallow-capitalized-comments.js
/**
* Requires the first alphabetical character of a comment to be lowercase.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* `"disallowCapitalizedComments": true`
*
* Valid:
*
* ```
* // valid
* //valid
*
* /*
* valid
* *\/
*
* /**
* * valid
* *\/
*
* // 123 or any non-alphabetical starting character
* ```
*
* Invalid:
* ```
* // Invalid
* //Invalid
* /** Invalid *\/
* /**
* * Invalid
* *\/
* ```
*/
var assert = require('assert');
Function (anonymous_316)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_317)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_318)
✓ Was called
getOptionName: function() {···
return 'disallowCapitalizedComments';
},
getOptionName: function() {
return 'disallowCapitalizedComments';
},
Function (anonymous_319)
✓ Was called
check: function(file, errors) {···
var letterPattern = require('../../patterns/L');
var lowerCasePattern = require('../../patterns/Ll');

file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
var stripped = comment.value.replace(/[\n\s\*]/g, '');
var firstChar = stripped[0];

if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {
errors.add(
'Comments must start with a lowercase letter',
comment
);
}
});
}
check: function(file, errors) {
var letterPattern = require('../../patterns/L');
var lowerCasePattern = require('../../patterns/Ll');
Function (anonymous_320)
✓ Was called
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {···
var stripped = comment.value.replace(/[\n\s\*]/g, '');
var firstChar = stripped[0];

if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {
errors.add(
'Comments must start with a lowercase letter',
comment
);
}
});
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
var stripped = comment.value.replace(/[\n\s\*]/g, '');
var firstChar = stripped[0];
Branch IfStatement
✓ Positive was executed (if)
if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {···
errors.add(
'Comments must start with a lowercase letter',
comment
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {
✓ Was returned
if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {
if (letterPattern.test(firstChar) && !lowerCasePattern.test(firstChar)) {
errors.add(
'Comments must start with a lowercase letter',
comment
);
}
});
}
};
disallow-comma-before-line-break.js
/**
* Disallows commas as last token on a line in lists.
*
* Type: `Boolean`, `Object`
*
* Values:
* - `true` for default behavior (strict mode, comma on the same line)
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'function'` ignores objects if one of their values is a function expression
*
* JSHint: [`laxcomma`](http://www.jshint.com/docs/options/#laxcomma)
*
* #### Example
*
* ```js
* "disallowCommaBeforeLineBreak": true
* ```
*
* ##### Valid for `true`
*
* ```js
* var x = {
* one: 1
* , two: 2
* };
* var y = {three: 3, four: 4};
* ```
*
* ##### Invalid
*
* ```js
* var x = {
* one: 1,
* two: 2
* };
* ```
*
* ##### Valid for `{"allExcept": ["function"]}`
*
* ```js
* var x = {
* one: 1,
* two: function() {}
* };
* ```
*
*/
var assert = require('assert');
Function (anonymous_321)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_322)
✓ Was called
configure: function(options) {···
var optionName = this.getOptionName();

if (typeof options !== 'object') {
assert(
options === true,
optionName + ' option requires either a true value or an object'
);

var _options = {allExcept: []};
return this.configure(_options);
}

assert(
Array.isArray(options.allExcept),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);

this._exceptFunction = options.allExcept.indexOf('function') > -1;
},
configure: function(options) {
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
optionName + ' option requires either a true value or an object'
);

var _options = {allExcept: []};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
options === true,
optionName + ' option requires either a true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);
this._exceptFunction = options.allExcept.indexOf('function') > -1;
},
Function (anonymous_323)
✓ Was called
getOptionName: function() {···
return 'disallowCommaBeforeLineBreak';
},
getOptionName: function() {
return 'disallowCommaBeforeLineBreak';
},
Function (anonymous_324)
✓ Was called
check: function(file, errors) {···
var exceptFunction = this._exceptFunction;

function canSkip(token) {
var node = token.parentElement;
if (node.getNewlineCount() === 0) {
return true;
}

// exception for function params
if (
node.params &&
file.isOnTheSameLine(node.params[0], node.params[node.params.length - 1])
) {
return true;
}

// See #1841
if (!exceptFunction || !node.properties) {
return false;
}

return node.properties.some(function(property) {
return property.value.type === 'FunctionExpression';
});
}

file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var nextToken = token.getNextCodeToken();

if (canSkip(token) || nextToken.value === ',') {
return;
}

errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Commas should be placed on the same line as value'
});

errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token,
message: 'Commas should be placed on new line'
});
});
}
check: function(file, errors) {
var exceptFunction = this._exceptFunction;
Function canSkip
✓ Was called
function canSkip(token) {···
var node = token.parentElement;
if (node.getNewlineCount() === 0) {
return true;
}

// exception for function params
if (
node.params &&
file.isOnTheSameLine(node.params[0], node.params[node.params.length - 1])
) {
return true;
}

// See #1841
if (!exceptFunction || !node.properties) {
return false;
}

return node.properties.some(function(property) {
return property.value.type === 'FunctionExpression';
});
}
function canSkip(token) {
var node = token.parentElement;
Branch IfStatement
✓ Positive was executed (if)
if (node.getNewlineCount() === 0) {···
return true;
}
✓ Negative was executed (else)
}···

// exception for function params
if (node.getNewlineCount() === 0) {
return true;
}
// exception for function params
Branch IfStatement
✓ Positive was executed (if)
) {···
return true;
}
✓ Negative was executed (else)
}···

// See #1841
if (
Branch LogicalExpression
✓ Was returned
file.isOnTheSameLine(node.params[0], node.params[node.params.length - 1])
✓ Was returned
node.params &&
node.params &&
file.isOnTheSameLine(node.params[0], node.params[node.params.length - 1])
) {
return true;
}
// See #1841
Branch IfStatement
✓ Positive was executed (if)
if (!exceptFunction || !node.properties) {···
return false;
}
✓ Negative was executed (else)
}···

return node.properties.some(function(property) {
Branch LogicalExpression
✓ Was returned
if (!exceptFunction || !node.properties) {
✓ Was returned
if (!exceptFunction || !node.properties) {
if (!exceptFunction || !node.properties) {
return false;
}
Function (anonymous_326)
✓ Was called
return node.properties.some(function(property) {···
return property.value.type === 'FunctionExpression';
});
return node.properties.some(function(property) {
return property.value.type === 'FunctionExpression';
});
}
Function (anonymous_327)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
var nextToken = token.getNextCodeToken();

if (canSkip(token) || nextToken.value === ',') {
return;
}

errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Commas should be placed on the same line as value'
});

errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token,
message: 'Commas should be placed on new line'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var nextToken = token.getNextCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (canSkip(token) || nextToken.value === ',') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.sameLine({
Branch LogicalExpression
✓ Was returned
if (canSkip(token) || nextToken.value === ',') {
✓ Was returned
if (canSkip(token) || nextToken.value === ',') {
if (canSkip(token) || nextToken.value === ',') {
return;
}
errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Commas should be placed on the same line as value'
});
errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token,
message: 'Commas should be placed on new line'
});
});
}
};
disallow-curly-braces.js
/**
* Disallows curly braces after statements.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to disallow curly braces after the following keywords:
*
* #### Example
*
* ```js
* "disallowCurlyBraces": [
* "if",
* "else",
* "while",
* "for",
* "do",
* "with"
* ]
* ```
*
* ##### Valid
*
* ```js
* if (x) x++;
* ```
*
* ##### Invalid
*
* ```js
* if (x) {
* x++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').curlyBracedKeywords;
Function (anonymous_328)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_329)
✓ Was called
configure: function(statementTypes) {···
assert(
Array.isArray(statementTypes) || statementTypes === true,
this.getOptionName() + ' option requires array or true value'
);

if (statementTypes === true) {
statementTypes = defaultKeywords;
}

this._typeIndex = {};
statementTypes.forEach(function(type) {
this._typeIndex[type] = true;
}.bind(this));
},
configure: function(statementTypes) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(statementTypes) || statementTypes === true,
✓ Was returned
Array.isArray(statementTypes) || statementTypes === true,
Array.isArray(statementTypes) || statementTypes === true,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (statementTypes === true) {···
statementTypes = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._typeIndex = {};
if (statementTypes === true) {
statementTypes = defaultKeywords;
}
this._typeIndex = {};
Function (anonymous_330)
✓ Was called
statementTypes.forEach(function(type) {···
this._typeIndex[type] = true;
}.bind(this));
statementTypes.forEach(function(type) {
this._typeIndex[type] = true;
}.bind(this));
},
Function (anonymous_331)
✓ Was called
getOptionName: function() {···
return 'disallowCurlyBraces';
},
getOptionName: function() {
return 'disallowCurlyBraces';
},
Function (anonymous_332)
✓ Was called
check: function(file, errors) {···

function isSingleBlockStatement(node) {
return node && node.type === 'BlockStatement' &&
node.body.length === 1;
}

function addError(typeString, entity) {
errors.add(
typeString + ' statement with extra curly braces',
entity
);
}

function checkBody(type, typeString) {
file.iterateNodesByType(type, function(node) {
if (isSingleBlockStatement(node.body)) {
addError(typeString, node);
}
});
}

var typeIndex = this._typeIndex;

if (typeIndex.if || typeIndex.else) {
file.iterateNodesByType('IfStatement', function(node) {
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
addError('If', node);
}
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
addError('Else', node.alternate.getFirstToken());
}
});
}

if (typeIndex.while) {
checkBody('WhileStatement', 'While');
}

if (typeIndex.for) {
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}

if (typeIndex.do) {
checkBody('DoWhileStatement', 'Do while');
}

if (typeIndex.with) {
checkBody('WithStatement', 'With');
}
}
check: function(file, errors) {
Function isSingleBlockStatement
✓ Was called
function isSingleBlockStatement(node) {···
return node && node.type === 'BlockStatement' &&
node.body.length === 1;
}
function isSingleBlockStatement(node) {
Branch LogicalExpression
✓ Was returned
node.body.length === 1;
✓ Was returned
return node && node.type === 'BlockStatement' &&
Branch LogicalExpression
✓ Was returned
return node && node.type === 'BlockStatement' &&
✓ Was returned
return node && node.type === 'BlockStatement' &&
return node && node.type === 'BlockStatement' &&
node.body.length === 1;
}
Function addError
✓ Was called
function addError(typeString, entity) {···
errors.add(
typeString + ' statement with extra curly braces',
entity
);
}
function addError(typeString, entity) {
errors.add(
typeString + ' statement with extra curly braces',
entity
);
}
Function checkBody
✓ Was called
function checkBody(type, typeString) {···
file.iterateNodesByType(type, function(node) {
if (isSingleBlockStatement(node.body)) {
addError(typeString, node);
}
});
}
function checkBody(type, typeString) {
Function (anonymous_336)
✓ Was called
file.iterateNodesByType(type, function(node) {···
if (isSingleBlockStatement(node.body)) {
addError(typeString, node);
}
});
file.iterateNodesByType(type, function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isSingleBlockStatement(node.body)) {···
addError(typeString, node);
}
✓ Negative was executed (else)
}···
});
if (isSingleBlockStatement(node.body)) {
addError(typeString, node);
}
});
}
var typeIndex = this._typeIndex;
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.if || typeIndex.else) {···
file.iterateNodesByType('IfStatement', function(node) {
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
addError('If', node);
}
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
addError('Else', node.alternate.getFirstToken());
}
});
}
✓ Negative was executed (else)
}···

if (typeIndex.while) {
Branch LogicalExpression
✓ Was returned
if (typeIndex.if || typeIndex.else) {
✓ Was returned
if (typeIndex.if || typeIndex.else) {
if (typeIndex.if || typeIndex.else) {
Function (anonymous_337)
✓ Was called
file.iterateNodesByType('IfStatement', function(node) {···
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
addError('If', node);
}
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
addError('Else', node.alternate.getFirstToken());
}
});
file.iterateNodesByType('IfStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {···
addError('If', node);
}
✓ Negative was executed (else)
}···
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
Branch LogicalExpression
✓ Was returned
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
✓ Was returned
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
addError('If', node);
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {···
addError('Else', node.alternate.getFirstToken());
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
✓ Was returned
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
addError('Else', node.alternate.getFirstToken());
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.while) {···
checkBody('WhileStatement', 'While');
}
✓ Negative was executed (else)
}···

if (typeIndex.for) {
if (typeIndex.while) {
checkBody('WhileStatement', 'While');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.for) {···
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}
✓ Negative was executed (else)
}···

if (typeIndex.do) {
if (typeIndex.for) {
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.do) {···
checkBody('DoWhileStatement', 'Do while');
}
✓ Negative was executed (else)
}···

if (typeIndex.with) {
if (typeIndex.do) {
checkBody('DoWhileStatement', 'Do while');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.with) {···
checkBody('WithStatement', 'With');
}
✓ Negative was executed (else)
}···
}
if (typeIndex.with) {
checkBody('WithStatement', 'With');
}
}
};
disallow-dangling-underscores.js
/**
* Disallows identifiers that start or end in `_`.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `Object`:
* - `allExcept`: array of quoted identifiers
*
* JSHint: [`nomen`](http://www.jshint.com/docs/options/#nomen)
*
* Some popular identifiers are automatically listed as exceptions:
*
* - `__proto__` (javascript)
* - `_` (underscore.js)
* - `__filename` (node.js global)
* - `__dirname` (node.js global)
* - `super_` (node.js, used by
* [`util.inherits`](http://nodejs.org/docs/latest/api/util.html#util_util_inherits_constructor_superconstructor))
*
* #### Example
*
* ```js
* "disallowDanglingUnderscores": { "allExcept": ["_exception"] }
* ```
*
* ##### Valid
*
* ```js
* var x = 1;
* var o = obj.__proto__;
* var y = _.extend;
* var z = __dirname;
* var w = __filename;
* var x_y = 1;
* var v = _exception;
* ```
*
* ##### Invalid
*
* ```js
* var _x = 1;
* var x_ = 1;
* var x_y_ = 1;
* ```
*/
var assert = require('assert');
Function (anonymous_338)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_339)
✓ Was called
configure: function(identifiers) {···
assert(
identifiers === true ||
typeof identifiers === 'object',
this.getOptionName() + ' option requires the value `true` ' +
'or an object with String[] `allExcept` property'
);

// verify first item in `allExcept` property in object (if it's an object)
assert(
typeof identifiers !== 'object' ||
Array.isArray(identifiers.allExcept) &&
typeof identifiers.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);

var isTrue = identifiers === true;
var defaultIdentifiers = [
'__proto__',
'_',
'__dirname',
'__filename',
'super_'
];

if (isTrue) {
identifiers = defaultIdentifiers;
} else {
identifiers = (identifiers.allExcept).concat(defaultIdentifiers);
}

this._identifierIndex = identifiers;
},
configure: function(identifiers) {
assert(
Branch LogicalExpression
✓ Was returned
typeof identifiers === 'object',
✓ Was returned
identifiers === true ||
identifiers === true ||
typeof identifiers === 'object',
this.getOptionName() + ' option requires the value `true` ' +
'or an object with String[] `allExcept` property'
);
// verify first item in `allExcept` property in object (if it's an object)
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(identifiers.allExcept) &&···
typeof identifiers.allExcept[0] === 'string',
✓ Was returned
typeof identifiers !== 'object' ||
typeof identifiers !== 'object' ||
Branch LogicalExpression
✓ Was returned
typeof identifiers.allExcept[0] === 'string',
✓ Was returned
Array.isArray(identifiers.allExcept) &&
Array.isArray(identifiers.allExcept) &&
typeof identifiers.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
var isTrue = identifiers === true;
var defaultIdentifiers = [
'__proto__',
'_',
'__dirname',
'__filename',
'super_'
];
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
identifiers = defaultIdentifiers;
} else {
✓ Negative was executed (else)
} else {···
identifiers = (identifiers.allExcept).concat(defaultIdentifiers);
}
if (isTrue) {
identifiers = defaultIdentifiers;
} else {
identifiers = (identifiers.allExcept).concat(defaultIdentifiers);
}
this._identifierIndex = identifiers;
},
Function (anonymous_340)
✓ Was called
getOptionName: function() {···
return 'disallowDanglingUnderscores';
},
getOptionName: function() {
return 'disallowDanglingUnderscores';
},
Function (anonymous_341)
✓ Was called
check: function(file, errors) {···
var allowedIdentifiers = this._identifierIndex;

file.iterateTokensByType('Identifier', function(token) {
var value = token.value;

if ((value[0] === '_' || value.slice(-1) === '_') &&
allowedIdentifiers.indexOf(value) < 0
) {
errors.add(
'Invalid dangling underscore found',
token
);
}
});
}
check: function(file, errors) {
var allowedIdentifiers = this._identifierIndex;
Function (anonymous_342)
✓ Was called
file.iterateTokensByType('Identifier', function(token) {···
var value = token.value;

if ((value[0] === '_' || value.slice(-1) === '_') &&
allowedIdentifiers.indexOf(value) < 0
) {
errors.add(
'Invalid dangling underscore found',
token
);
}
});
file.iterateTokensByType('Identifier', function(token) {
var value = token.value;
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add(
'Invalid dangling underscore found',
token
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
allowedIdentifiers.indexOf(value) < 0
✓ Was returned
if ((value[0] === '_' || value.slice(-1) === '_') &&
Branch LogicalExpression
✓ Was returned
if ((value[0] === '_' || value.slice(-1) === '_') &&
✓ Was returned
if ((value[0] === '_' || value.slice(-1) === '_') &&
if ((value[0] === '_' || value.slice(-1) === '_') &&
allowedIdentifiers.indexOf(value) < 0
) {
errors.add(
'Invalid dangling underscore found',
token
);
}
});
}
};
disallow-empty-blocks.js
/**
* Disallows empty blocks (except for catch blocks).
*
* Type: `Boolean` or `Object`
*
* Values:
* - `true` for default behavior (strict mode, no empty blocks allowed)
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'comments'` blocks containing only comments are not considered empty
*
* JSHint: [`noempty`](http://jshint.com/docs/options/#noempty)
*
* #### Example
*
* ```js
* "disallowEmptyBlocks": true
* ```
*
* ##### Valid
*
* ```js
* if ( a == b ) { c = d; }
* try { a = b; } catch( e ){}
* ```
*
* ##### Invalid
*
* ```js
* if ( a == b ) { } else { c = d; }
* ```
*/
var assert = require('assert');
Function (anonymous_343)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_344)
✓ Was called
configure: function(options) {···
var optionName = this.getOptionName();

if (typeof options !== 'object') {
assert(
options === true,
optionName + ' option requires a true value or an object like: { allExcept: [\'comments\'] }'
);

var _options = {
allExcept: []
};
return this.configure(_options);
}

assert(
Array.isArray(options.allExcept),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);

this._exceptComments = options.allExcept.indexOf('comments') > -1;
},
configure: function(options) {
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
optionName + ' option requires a true value or an object like: { allExcept: [\'comments\'] }'
);

var _options = {
allExcept: []
};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
options === true,
optionName + ' option requires a true value or an object like: { allExcept: [\'comments\'] }'
);
var _options = {
allExcept: []
};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);
this._exceptComments = options.allExcept.indexOf('comments') > -1;
},
Function (anonymous_345)
✓ Was called
getOptionName: function() {···
return 'disallowEmptyBlocks';
},
getOptionName: function() {
return 'disallowEmptyBlocks';
},
Function (anonymous_346)
✓ Was called
check: function(file, errors) {···
var exceptComments = this._exceptComments;

function canSkip(token) {
if (!exceptComments) {
return false;
}
var canSkipToken = false;
var tokenLoc = token.getLoc();
file.getComments().forEach(function(comment) {
var commentLoc = comment.getLoc();
if (commentLoc.start.line >= tokenLoc.start.line &&
commentLoc.end.line <= tokenLoc.end.line) {
canSkipToken = true;
}
});
return canSkipToken;
}

file.iterateNodesByType('BlockStatement', function(node) {
if (node.body.length) {
return true;
}

if (canSkip(node)) {
return true;
}

if (node.parentElement.type !== 'CatchClause' &&
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
node.parentElement.type !== 'ArrowFunctionExpression' &&
node.parentElement.type !== 'ObjectMethod') {
errors.add('Empty block found', node.lastChild);
}
});
}
check: function(file, errors) {
var exceptComments = this._exceptComments;
Function canSkip
✓ Was called
function canSkip(token) {···
if (!exceptComments) {
return false;
}
var canSkipToken = false;
var tokenLoc = token.getLoc();
file.getComments().forEach(function(comment) {
var commentLoc = comment.getLoc();
if (commentLoc.start.line >= tokenLoc.start.line &&
commentLoc.end.line <= tokenLoc.end.line) {
canSkipToken = true;
}
});
return canSkipToken;
}
function canSkip(token) {
Branch IfStatement
✓ Positive was executed (if)
if (!exceptComments) {···
return false;
}
✓ Negative was executed (else)
}···
var canSkipToken = false;
if (!exceptComments) {
return false;
}
var canSkipToken = false;
var tokenLoc = token.getLoc();
Function (anonymous_348)
✓ Was called
file.getComments().forEach(function(comment) {···
var commentLoc = comment.getLoc();
if (commentLoc.start.line >= tokenLoc.start.line &&
commentLoc.end.line <= tokenLoc.end.line) {
canSkipToken = true;
}
});
file.getComments().forEach(function(comment) {
var commentLoc = comment.getLoc();
Branch IfStatement
✓ Positive was executed (if)
commentLoc.end.line <= tokenLoc.end.line) {···
canSkipToken = true;
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
commentLoc.end.line <= tokenLoc.end.line) {
✓ Was returned
if (commentLoc.start.line >= tokenLoc.start.line &&
if (commentLoc.start.line >= tokenLoc.start.line &&
commentLoc.end.line <= tokenLoc.end.line) {
canSkipToken = true;
}
});
return canSkipToken;
}
Function (anonymous_349)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
if (node.body.length) {
return true;
}

if (canSkip(node)) {
return true;
}

if (node.parentElement.type !== 'CatchClause' &&
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
node.parentElement.type !== 'ArrowFunctionExpression' &&
node.parentElement.type !== 'ObjectMethod') {
errors.add('Empty block found', node.lastChild);
}
});
file.iterateNodesByType('BlockStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.body.length) {···
return true;
}
✓ Negative was executed (else)
}···

if (canSkip(node)) {
if (node.body.length) {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (canSkip(node)) {···
return true;
}
✓ Negative was executed (else)
}···

if (node.parentElement.type !== 'CatchClause' &&
if (canSkip(node)) {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
node.parentElement.type !== 'ObjectMethod') {···
errors.add('Empty block found', node.lastChild);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
node.parentElement.type !== 'ObjectMethod') {
✓ Was returned
if (node.parentElement.type !== 'CatchClause' &&···
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
node.parentElement.type !== 'ArrowFunctionExpression' &&
Branch LogicalExpression
✓ Was returned
node.parentElement.type !== 'ArrowFunctionExpression' &&
✓ Was returned
if (node.parentElement.type !== 'CatchClause' &&···
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
Branch LogicalExpression
✓ Was returned
node.parentElement.type !== 'FunctionExpression' &&
✓ Was returned
if (node.parentElement.type !== 'CatchClause' &&···
node.parentElement.type !== 'FunctionDeclaration' &&
Branch LogicalExpression
✓ Was returned
node.parentElement.type !== 'FunctionDeclaration' &&
✓ Was returned
if (node.parentElement.type !== 'CatchClause' &&
if (node.parentElement.type !== 'CatchClause' &&
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
node.parentElement.type !== 'ArrowFunctionExpression' &&
node.parentElement.type !== 'ObjectMethod') {
errors.add('Empty block found', node.lastChild);
}
});
}
};
disallow-function-declarations.js
/**
* Disallows function declarations.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowFunctionDeclarations": true
* ```
*
* ##### Valid
*
* ```js
* var expressed = function() {
*
* };
*
* var expressed = function deeply() {
*
* };
*
* $('#foo').click(function bar() {
*
* });
* ```
*
* ##### Invalid
*
* ```js
* function stated() {
*
* }
* ```
*/
var assert = require('assert');
Function (anonymous_350)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_351)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_352)
✓ Was called
getOptionName: function() {···
return 'disallowFunctionDeclarations';
},
getOptionName: function() {
return 'disallowFunctionDeclarations';
},
Function (anonymous_353)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('FunctionDeclaration', function(node) {
errors.add('Illegal function declaration', node);
});
}
check: function(file, errors) {
Function (anonymous_354)
✓ Was called
file.iterateNodesByType('FunctionDeclaration', function(node) {···
errors.add('Illegal function declaration', node);
});
file.iterateNodesByType('FunctionDeclaration', function(node) {
errors.add('Illegal function declaration', node);
});
}
};
disallow-identical-destructuring-names.js
/**
* Disallows identical destructuring names for the key and value in favor of using shorthand destructuring.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowIdenticalDestructuringNames": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var {left, top} = obj; // shorthand
* var {left, top: topper} = obj; // different identifier
* let { [key]: key } = obj; // computed property
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* var {left: left, top: top} = obj;
* ```
*/
var assert = require('assert');
Function (anonymous_355)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_356)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_357)
✓ Was called
getOptionName: function() {···
return 'disallowIdenticalDestructuringNames';
},
getOptionName: function() {
return 'disallowIdenticalDestructuringNames';
},
Function (anonymous_358)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ObjectPattern'], function(node) {
var props = node.properties;
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
prop.key.name === prop.value.name) {
errors.add('Use the shorthand form of destructuring instead', prop);
}
}
});
}
check: function(file, errors) {
Function (anonymous_359)
✓ Was called
file.iterateNodesByType(['ObjectPattern'], function(node) {···
var props = node.properties;
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
prop.key.name === prop.value.name) {
errors.add('Use the shorthand form of destructuring instead', prop);
}
}
});
file.iterateNodesByType(['ObjectPattern'], function(node) {
var props = node.properties;
for (var i = 0; i < props.length; i++) {
var prop = props[i];
Branch IfStatement
✓ Positive was executed (if)
prop.key.name === prop.value.name) {···
errors.add('Use the shorthand form of destructuring instead', prop);
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
prop.key.name === prop.value.name) {
✓ Was returned
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
Branch LogicalExpression
✓ Was returned
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
✓ Was returned
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
Branch LogicalExpression
✓ Was returned
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
✗ Was not returned
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
if (prop.type === 'ObjectProperty' && !prop.shorthand && !prop.computed &&
prop.key.name === prop.value.name) {
errors.add('Use the shorthand form of destructuring instead', prop);
}
}
});
}
};
disallow-identifier-names.js
/**
* Disallows a specified set of identifier names.
*
* Type: `Array`
*
* Values: Array of strings, which should be disallowed as identifier names
*
* #### Example
*
* ```js
* "disallowIdentifierNames": ['temp', 'foo']
* ```
*
* ##### Valid
*
* ```js
* var good = 1;
* object['fine'] = 2;
* object.fine = 3;
* ```
*
* ##### Invalid
*
* ```js
* var temp = 1;
* object['foo'] = 2;
* object.foo = 3;
* ```
*/
var assert = require('assert');
Function (anonymous_360)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_361)
✓ Was called
configure: function(identifiers) {···
assert(
Array.isArray(identifiers),
'disallowIdentifierNames option requires an array'
);

this._identifierIndex = {};
for (var i = 0, l = identifiers.length; i < l; i++) {
this._identifierIndex[identifiers[i]] = true;
}
},
configure: function(identifiers) {
assert(
Array.isArray(identifiers),
'disallowIdentifierNames option requires an array'
);
this._identifierIndex = {};
for (var i = 0, l = identifiers.length; i < l; i++) {
this._identifierIndex[identifiers[i]] = true;
}
},
Function (anonymous_362)
✓ Was called
getOptionName: function() {···
return 'disallowIdentifierNames';
},
getOptionName: function() {
return 'disallowIdentifierNames';
},
Function (anonymous_363)
✓ Was called
check: function(file, errors) {···
var disallowedIdentifiers = this._identifierIndex;

file.iterateNodesByType('Identifier', function(node) {
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.name)) {
errors.add('Illegal Identifier name: ' + node.name, node);
}
});

file.iterateNodesByType('MemberExpression', function(node) {
if (node.property.type === 'StringLiteral') {
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.property.value)) {
errors.add('Illegal Identifier name: ' + node.property.value, node.property);
}
}
});

}
check: function(file, errors) {
var disallowedIdentifiers = this._identifierIndex;
Function (anonymous_364)
✓ Was called
file.iterateNodesByType('Identifier', function(node) {···
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.name)) {
errors.add('Illegal Identifier name: ' + node.name, node);
}
});
file.iterateNodesByType('Identifier', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.name)) {···
errors.add('Illegal Identifier name: ' + node.name, node);
}
✓ Negative was executed (else)
}···
});
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.name)) {
errors.add('Illegal Identifier name: ' + node.name, node);
}
});
Function (anonymous_365)
✓ Was called
file.iterateNodesByType('MemberExpression', function(node) {···
if (node.property.type === 'StringLiteral') {
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.property.value)) {
errors.add('Illegal Identifier name: ' + node.property.value, node.property);
}
}
});
file.iterateNodesByType('MemberExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.property.type === 'StringLiteral') {···
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.property.value)) {
errors.add('Illegal Identifier name: ' + node.property.value, node.property);
}
}
✓ Negative was executed (else)
}···
});
if (node.property.type === 'StringLiteral') {
Branch IfStatement
✓ Positive was executed (if)
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.property.value)) {···
errors.add('Illegal Identifier name: ' + node.property.value, node.property);
}
✓ Negative was executed (else)
}···
}
if (Object.prototype.hasOwnProperty.call(disallowedIdentifiers, node.property.value)) {
errors.add('Illegal Identifier name: ' + node.property.value, node.property);
}
}
});
}
};
disallow-implicit-type-conversion.js
/**
* Disallows implicit type conversion.
*
* Type: `Array`
*
* Values: Array of quoted types
*
* #### Example
*
* ```js
* "disallowImplicitTypeConversion": ["numeric", "boolean", "binary", "string"]
* ```
*
* ##### Valid
*
* ```js
* x = Boolean(y);
* x = Number(y);
* x = String(y);
* x = s.indexOf('.') !== -1;
* ```
*
* ##### Invalid
*
* ```js
* x = !!y;
* x = +y;
* x = '' + y;
* x = ~s.indexOf('.');
* ```
*/
var assert = require('assert');
Function (anonymous_366)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_367)
✓ Was called
configure: function(types) {···
assert(Array.isArray(types), this.getOptionName() + ' option requires array value');
this._typeIndex = {};
for (var i = 0, l = types.length; i < l; i++) {
this._typeIndex[types[i]] = true;
}
},
configure: function(types) {
assert(Array.isArray(types), this.getOptionName() + ' option requires array value');
this._typeIndex = {};
for (var i = 0, l = types.length; i < l; i++) {
this._typeIndex[types[i]] = true;
}
},
Function (anonymous_368)
✓ Was called
getOptionName: function() {···
return 'disallowImplicitTypeConversion';
},
getOptionName: function() {
return 'disallowImplicitTypeConversion';
},
Function (anonymous_369)
✓ Was called
check: function(file, errors) {···
var types = this._typeIndex;
if (types.numeric || types.boolean || types.binary) {
file.iterateNodesByType('UnaryExpression', function(node) {
if (types.numeric && node.operator === '+') {
errors.add('Implicit numeric conversion', node);
}
if (types.binary && node.operator === '~') {
errors.add('Implicit binary conversion', node);
}
if (types.boolean &&
node.operator === '!' &&
node.argument.type === 'UnaryExpression' &&
node.argument.operator === '!'
) {
errors.add('Implicit boolean conversion', node);
}
});
}
if (types.string) {
file.iterateNodesByType('BinaryExpression', function(node) {

if (node.operator !== '+') {
return;
}

// Do not report concatination for same string literals (#1538)
if (node.left.type === node.right.type) {
return;
}

if (
(node.left.type === 'StringLiteral' && node.left.value === '') ||
(node.right.type === 'StringLiteral' && node.right.value === '')
) {
errors.add('Implicit string conversion', node);
}
});
}
}
check: function(file, errors) {
var types = this._typeIndex;
Branch IfStatement
✓ Positive was executed (if)
if (types.numeric || types.boolean || types.binary) {···
file.iterateNodesByType('UnaryExpression', function(node) {
if (types.numeric && node.operator === '+') {
errors.add('Implicit numeric conversion', node);
}
if (types.binary && node.operator === '~') {
errors.add('Implicit binary conversion', node);
}
if (types.boolean &&
node.operator === '!' &&
node.argument.type === 'UnaryExpression' &&
node.argument.operator === '!'
) {
errors.add('Implicit boolean conversion', node);
}
});
}
✓ Negative was executed (else)
}···
if (types.string) {
Branch LogicalExpression
✓ Was returned
if (types.numeric || types.boolean || types.binary) {
✓ Was returned
if (types.numeric || types.boolean || types.binary) {
Branch LogicalExpression
✓ Was returned
if (types.numeric || types.boolean || types.binary) {
✓ Was returned
if (types.numeric || types.boolean || types.binary) {
if (types.numeric || types.boolean || types.binary) {
Function (anonymous_370)
✓ Was called
file.iterateNodesByType('UnaryExpression', function(node) {···
if (types.numeric && node.operator === '+') {
errors.add('Implicit numeric conversion', node);
}
if (types.binary && node.operator === '~') {
errors.add('Implicit binary conversion', node);
}
if (types.boolean &&
node.operator === '!' &&
node.argument.type === 'UnaryExpression' &&
node.argument.operator === '!'
) {
errors.add('Implicit boolean conversion', node);
}
});
file.iterateNodesByType('UnaryExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (types.numeric && node.operator === '+') {···
errors.add('Implicit numeric conversion', node);
}
✓ Negative was executed (else)
}···
if (types.binary && node.operator === '~') {
Branch LogicalExpression
✓ Was returned
if (types.numeric && node.operator === '+') {
✓ Was returned
if (types.numeric && node.operator === '+') {
if (types.numeric && node.operator === '+') {
errors.add('Implicit numeric conversion', node);
}
Branch IfStatement
✓ Positive was executed (if)
if (types.binary && node.operator === '~') {···
errors.add('Implicit binary conversion', node);
}
✓ Negative was executed (else)
}···
if (types.boolean &&
Branch LogicalExpression
✓ Was returned
if (types.binary && node.operator === '~') {
✓ Was returned
if (types.binary && node.operator === '~') {
if (types.binary && node.operator === '~') {
errors.add('Implicit binary conversion', node);
}
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add('Implicit boolean conversion', node);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
node.argument.operator === '!'
✓ Was returned
if (types.boolean &&···
node.operator === '!' &&
node.argument.type === 'UnaryExpression' &&
Branch LogicalExpression
✓ Was returned
node.argument.type === 'UnaryExpression' &&
✓ Was returned
if (types.boolean &&···
node.operator === '!' &&
Branch LogicalExpression
✓ Was returned
node.operator === '!' &&
✓ Was returned
if (types.boolean &&
if (types.boolean &&
node.operator === '!' &&
node.argument.type === 'UnaryExpression' &&
node.argument.operator === '!'
) {
errors.add('Implicit boolean conversion', node);
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (types.string) {···
file.iterateNodesByType('BinaryExpression', function(node) {

if (node.operator !== '+') {
return;
}

// Do not report concatination for same string literals (#1538)
if (node.left.type === node.right.type) {
return;
}

if (
(node.left.type === 'StringLiteral' && node.left.value === '') ||
(node.right.type === 'StringLiteral' && node.right.value === '')
) {
errors.add('Implicit string conversion', node);
}
});
}
✓ Negative was executed (else)
}···
}
if (types.string) {
Function (anonymous_371)
✓ Was called
file.iterateNodesByType('BinaryExpression', function(node) {···

if (node.operator !== '+') {
return;
}

// Do not report concatination for same string literals (#1538)
if (node.left.type === node.right.type) {
return;
}

if (
(node.left.type === 'StringLiteral' && node.left.value === '') ||
(node.right.type === 'StringLiteral' && node.right.value === '')
) {
errors.add('Implicit string conversion', node);
}
});
file.iterateNodesByType('BinaryExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.operator !== '+') {···
return;
}
✓ Negative was executed (else)
}···

// Do not report concatination for same string literals (#1538)
if (node.operator !== '+') {
return;
}
// Do not report concatination for same string literals (#1538)
Branch IfStatement
✓ Positive was executed (if)
if (node.left.type === node.right.type) {···
return;
}
✓ Negative was executed (else)
}···

if (
if (node.left.type === node.right.type) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add('Implicit string conversion', node);
}
✓ Negative was executed (else)
}···
});
if (
Branch LogicalExpression
✓ Was returned
(node.right.type === 'StringLiteral' && node.right.value === '')
✓ Was returned
(node.left.type === 'StringLiteral' && node.left.value === '') ||
Branch LogicalExpression
✓ Was returned
(node.left.type === 'StringLiteral' && node.left.value === '') ||
✓ Was returned
(node.left.type === 'StringLiteral' && node.left.value === '') ||
(node.left.type === 'StringLiteral' && node.left.value === '') ||
Branch LogicalExpression
✓ Was returned
(node.right.type === 'StringLiteral' && node.right.value === '')
✓ Was returned
(node.right.type === 'StringLiteral' && node.right.value === '')
(node.right.type === 'StringLiteral' && node.right.value === '')
) {
errors.add('Implicit string conversion', node);
}
});
}
}
};
disallow-keywords-in-comments.js
/**
* Disallows keywords in your comments, such as TODO or FIXME
*
* Types: `Boolean`, `String` or `Array`
*
* Values:
* - `true`
* - `'\b(word1|word2)\b'`
* - `['word1', 'word2']`
*
* #### Examples
*
* ```js
* "disallowKeywordsInComments": true
* "disallowKeywordsInComments": "\\b(word1|word2)\\b"
* "disallowKeywordsInComments": ["word1", "word2"]
* ```
*
* #### Invalid:
* ```
* // ToDo
* //TODO
* /** fixme *\/
* /**
* * FIXME
* *\/
* ```
*/
var assert = require('assert');
Function (anonymous_372)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_373)
✓ Was called
configure: function(keywords) {···
this._message = 'Comments cannot contain the following keywords: ';
this._keywords = ['todo', 'fixme'];

switch (true) {
case Array.isArray(keywords):
// use the array of strings provided to build RegExp pattern
this._keywords = keywords;
/* falls through */
case keywords:
// use default keywords
this._message += this._keywords.join(', ');
this._keywordRegEx = new RegExp('\\b(' + this._keywords.join('|') + ')\\b', 'gi');
break;
case typeof keywords === 'string':
// use string passed in as the RegExp pattern
this._message = 'Comments cannot contain keywords based on the expression you provided';
this._keywordRegEx = new RegExp(keywords, 'gi');
break;
default:
assert(false, this.getOptionName() + ' option requires a true value, a string or an array');
}
},
configure: function(keywords) {
this._message = 'Comments cannot contain the following keywords: ';
this._keywords = ['todo', 'fixme'];
Branch SwitchStatement
✓ Was evaluated
case Array.isArray(keywords):···
// use the array of strings provided to build RegExp pattern
this._keywords = keywords;
✓ Was evaluated
case keywords:···
// use default keywords
this._message += this._keywords.join(', ');
this._keywordRegEx = new RegExp('\\b(' + this._keywords.join('|') + ')\\b', 'gi');
break;
✓ Was evaluated
case typeof keywords === 'string':···
// use string passed in as the RegExp pattern
this._message = 'Comments cannot contain keywords based on the expression you provided';
this._keywordRegEx = new RegExp(keywords, 'gi');
break;
✓ Was evaluated
default:···
assert(false, this.getOptionName() + ' option requires a true value, a string or an array');
switch (true) {
case Array.isArray(keywords):
// use the array of strings provided to build RegExp pattern
this._keywords = keywords;
/* falls through */
case keywords:
// use default keywords
this._message += this._keywords.join(', ');
this._keywordRegEx = new RegExp('\\b(' + this._keywords.join('|') + ')\\b', 'gi');
break;
case typeof keywords === 'string':
// use string passed in as the RegExp pattern
this._message = 'Comments cannot contain keywords based on the expression you provided';
this._keywordRegEx = new RegExp(keywords, 'gi');
break;
default:
assert(false, this.getOptionName() + ' option requires a true value, a string or an array');
}
},
Function (anonymous_374)
✓ Was called
getOptionName: function() {···
return 'disallowKeywordsInComments';
},
getOptionName: function() {
return 'disallowKeywordsInComments';
},
Function (anonymous_375)
✓ Was called
check: function(file, errors) {···
var keywordRegEx = this._keywordRegEx;
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
var match;

// Both '//' and '/*' comment starters have offset '2'
var commentOffset = 2;
keywordRegEx.lastIndex = 0;
while ((match = keywordRegEx.exec(comment.value)) !== null) {
errors.add(
this.mesage,
comment,
match.index + commentOffset
);
}
});
}
check: function(file, errors) {
var keywordRegEx = this._keywordRegEx;
Function (anonymous_376)
✓ Was called
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {···
var match;

// Both '//' and '/*' comment starters have offset '2'
var commentOffset = 2;
keywordRegEx.lastIndex = 0;
while ((match = keywordRegEx.exec(comment.value)) !== null) {
errors.add(
this.mesage,
comment,
match.index + commentOffset
);
}
});
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
var match;
// Both '//' and '/*' comment starters have offset '2'
var commentOffset = 2;
keywordRegEx.lastIndex = 0;
while ((match = keywordRegEx.exec(comment.value)) !== null) {
errors.add(
this.mesage,
comment,
match.index + commentOffset
);
}
});
}
};
disallow-keywords-on-new-line.js
/**
* Disallows placing keywords on a new line.
*
* Types: `Array`
*
* Values:
*
* - `Array` specifies quoted keywords which are disallowed from being placed on a new line
*
* #### Example
*
* ```js
* "disallowKeywordsOnNewLine": ["else"]
* ```
*
* ##### Valid
*
* ```js
* if (x < 0) {
* x++;
* } else {
* x--;
* }
* ```
* ```js
* if (x < 0)
* x++;
* else
* x--;
* ```
* ```js
* if (x < 0) {
* x++;
* }
* // comments
* else {
* x--;
* }
* ```
* ```js
* do {
* x++;
* } while(x < 0);
* ```
* ```js
* do
* x++;
* while(x < 0);
* ```
* ```js
* do {
* x++;
* }
* // comments
* while(x < 0);
* ```
*
* ##### Invalid
*
* ```js
* if (x < 0) {
* x++;
* }
* else {
* x--;
* }
* ```
*/
var assert = require('assert');
Function isPreviousTokenAComment
✓ Was called
function isPreviousTokenAComment(token) {···
var prevToken = token.getPreviousNonWhitespaceToken();
return (prevToken.type === 'CommentLine' || prevToken.type === 'CommentBlock');
}
function isPreviousTokenAComment(token) {
var prevToken = token.getPreviousNonWhitespaceToken();
Branch LogicalExpression
✓ Was returned
return (prevToken.type === 'CommentLine' || prevToken.type === 'CommentBlock');
✓ Was returned
return (prevToken.type === 'CommentLine' || prevToken.type === 'CommentBlock');
return (prevToken.type === 'CommentLine' || prevToken.type === 'CommentBlock');
}
Function (anonymous_378)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_379)
✓ Was called
configure: function(keywords) {···
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
configure: function(keywords) {
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
Function (anonymous_380)
✓ Was called
getOptionName: function() {···
return 'disallowKeywordsOnNewLine';
},
getOptionName: function() {
return 'disallowKeywordsOnNewLine';
},
Function (anonymous_381)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = token.getPreviousCodeToken();

if (token.value === 'else') {
if (prevToken.value !== '}') {
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}

// Special cases for #885, using while as the keyword contradicts rule meaning
// but it is more efficient and reduces complexity of the code in this rule
if (token.value === 'while') {
var parentElement = token.parentElement;

// "while" that is part of a do will not return nodes as it is not a start token
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
// allow "while" that is part of a "do while" with no braces to succeed
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}

errors.assert.sameLine({
token: prevToken,
nextToken: token
});
});
}
check: function(file, errors) {
Function (anonymous_382)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var prevToken = token.getPreviousCodeToken();

if (token.value === 'else') {
if (prevToken.value !== '}') {
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}

// Special cases for #885, using while as the keyword contradicts rule meaning
// but it is more efficient and reduces complexity of the code in this rule
if (token.value === 'while') {
var parentElement = token.parentElement;

// "while" that is part of a do will not return nodes as it is not a start token
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
// allow "while" that is part of a "do while" with no braces to succeed
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}

errors.assert.sameLine({
token: prevToken,
nextToken: token
});
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (token.value === 'else') {···
if (prevToken.value !== '}') {
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
✓ Negative was executed (else)
}···

// Special cases for #885, using while as the keyword contradicts rule meaning
if (token.value === 'else') {
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value !== '}') {···
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}
✓ Negative was executed (else)
}···

if (isPreviousTokenAComment(token)) {
if (prevToken.value !== '}') {
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (isPreviousTokenAComment(token)) {···
// Special case for #1421, to handle comments before the else
return;
}
✓ Negative was executed (else)
}···
}
if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
// Special cases for #885, using while as the keyword contradicts rule meaning
// but it is more efficient and reduces complexity of the code in this rule
Branch IfStatement
✓ Positive was executed (if)
if (token.value === 'while') {···
var parentElement = token.parentElement;

// "while" that is part of a do will not return nodes as it is not a start token
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
// allow "while" that is part of a "do while" with no braces to succeed
return;
}

if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
✓ Negative was executed (else)
}···

errors.assert.sameLine({
if (token.value === 'while') {
var parentElement = token.parentElement;
// "while" that is part of a do will not return nodes as it is not a start token
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {···
// allow "while" that is part of a "do while" with no braces to succeed
return;
}
✓ Negative was executed (else)
}···

if (isPreviousTokenAComment(token)) {
Branch LogicalExpression
✓ Was returned
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
✓ Was returned
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
// allow "while" that is part of a "do while" with no braces to succeed
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (isPreviousTokenAComment(token)) {···
// Special case for #1421, to handle comments before the else
return;
}
✓ Negative was executed (else)
}···
}
if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
errors.assert.sameLine({
token: prevToken,
nextToken: token
});
});
}
};
disallow-keywords.js
/**
* Disallows usage of specified keywords.
*
* Type: `Array`
*
* Values: Array of quoted keywords
*
* #### Example
*
* ```js
* "disallowKeywords": ["with"]
* ```
*
* ##### Invalid
*
* ```js
* with (x) {
* prop++;
* }
* ```
*/
var assert = require('assert');
Function (anonymous_383)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_384)
✓ Was called
configure: function(keywords) {···
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
configure: function(keywords) {
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
Function (anonymous_385)
✓ Was called
getOptionName: function() {···
return 'disallowKeywords';
},
getOptionName: function() {
return 'disallowKeywords';
},
Function (anonymous_386)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.add('Illegal keyword: ' + token.value, token);
});
}
check: function(file, errors) {
Function (anonymous_387)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
errors.add('Illegal keyword: ' + token.value, token);
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.add('Illegal keyword: ' + token.value, token);
});
}
};
disallow-mixed-spaces-and-tabs.js
/**
* Requires lines to not contain both spaces and tabs consecutively,
* or spaces after tabs only for alignment if "smart"
*
* Types: `Boolean` or `String`
*
* Values: `true` or `"smart"`
*
* JSHint: [`smarttabs`](http://www.jshint.com/docs/options/#smarttabs)
*
* #### Example
*
* ```js
* "disallowMixedSpacesAndTabs": true
* ```
*
* ##### Valid example for mode `true`
*
* ```js
* \tvar foo = "blah blah";
* \s\s\s\svar foo = "blah blah";
* \t/**
* \t\s*
* \t\s*\/ //a single space to align the star in a multi-line comment is allowed
* ```
*
* ##### Invalid example for mode `true`
*
* ```js
* \t\svar foo = "blah blah";
* \s\tsvar foo = "blah blah";
* ```
*
* ##### Valid example for mode `"smart"`
*
* ```js
* \tvar foo = "blah blah";
* \t\svar foo = "blah blah";
* \s\s\s\svar foo = "blah blah";
* \t/**
* \t\s*
* \t\s*\/ //a single space to align the star in a multi-line comment is allowed
* ```
*
* ##### Invalid example for mode `"smart"`
*
* ```js
* \s\tsvar foo = "blah blah";
* ```
*/
var assert = require('assert');
Function (anonymous_388)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_389)
✓ Was called
configure: function(options) {···
assert(
options === true || options === 'smart',
this.getOptionName() + ' option requires a true value or "smart"'
);

this._options = options;
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'smart',
✓ Was returned
options === true || options === 'smart',
options === true || options === 'smart',
this.getOptionName() + ' option requires a true value or "smart"'
);
this._options = options;
},
Function (anonymous_390)
✓ Was called
getOptionName: function() {···
return 'disallowMixedSpacesAndTabs';
},
getOptionName: function() {
return 'disallowMixedSpacesAndTabs';
},
Function (anonymous_391)
✓ Was called
check: function(file, errors) {···
var test = this._options === true ?
(/ \t|\t [^\*]|\t $/) :
(/ \t/);

file.iterateTokensByType('Whitespace', function(token) {
var match = test.exec(token.value);
if (match) {
errors.add('Mixed spaces and tabs found', token, token.index);
}
});
}
check: function(file, errors) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
(/ \t|\t [^\*]|\t $/) :
✓ Negative was returned (: ...)
(/ \t/);
var test = this._options === true ?
(/ \t|\t [^\*]|\t $/) :
(/ \t/);
Function (anonymous_392)
✓ Was called
file.iterateTokensByType('Whitespace', function(token) {···
var match = test.exec(token.value);
if (match) {
errors.add('Mixed spaces and tabs found', token, token.index);
}
});
file.iterateTokensByType('Whitespace', function(token) {
var match = test.exec(token.value);
Branch IfStatement
✓ Positive was executed (if)
if (match) {···
errors.add('Mixed spaces and tabs found', token, token.index);
}
✓ Negative was executed (else)
}···
});
if (match) {
errors.add('Mixed spaces and tabs found', token, token.index);
}
});
}
};
disallow-multi-line-ternary.js
/**
* Disallows the test, consequent and alternate to be on separate lines when using the ternary operator.
*
* Types: `Boolean`
*
* #### Example
*
* ```js
* "disallowMultiLineTernary": true
* ```
*
* ##### Valid
*
* ```js
* var foo = (a === b) ? 1 : 2;
* ```
*
* ##### Invalid
*
* ```js
* var foo = (a === b)
* ? 1
* : 2;
* ```
*/
var assert = require('assert');
Function (anonymous_393)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_394)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_395)
✓ Was called
getOptionName: function() {···
return 'disallowMultiLineTernary';
},
getOptionName: function() {
return 'disallowMultiLineTernary';
},
Function (anonymous_396)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ConditionalExpression', function(node) {

errors.assert.sameLine({
token: node.test,
nextToken: node.consequent,
message: 'Illegal new line after test'
});

errors.assert.sameLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Illegal new line after consequent'
});
});
}
check: function(file, errors) {
Function (anonymous_397)
✓ Was called
file.iterateNodesByType('ConditionalExpression', function(node) {···

errors.assert.sameLine({
token: node.test,
nextToken: node.consequent,
message: 'Illegal new line after test'
});

errors.assert.sameLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Illegal new line after consequent'
});
});
file.iterateNodesByType('ConditionalExpression', function(node) {
errors.assert.sameLine({
token: node.test,
nextToken: node.consequent,
message: 'Illegal new line after test'
});
errors.assert.sameLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Illegal new line after consequent'
});
});
}
};
disallow-multiple-line-breaks.js
/**
* Disallows multiple blank lines in a row.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowMultipleLineBreaks": true
* ```
*
* ##### Valid
* ```js
* var x = 1;
*
* x++;
* ```
*
* ##### Invalid
* ```js
* var x = 1;
*
*
* x++;
* ```
*/
var assert = require('assert');
Function (anonymous_398)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_399)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_400)
✓ Was called
getOptionName: function() {···
return 'disallowMultipleLineBreaks';
},
getOptionName: function() {
return 'disallowMultipleLineBreaks';
},
Function (anonymous_401)
✓ Was called
check: function(file, errors) {···
// Iterate over all tokens (including comments)
file.iterateTokensByType('Whitespace', function(whitespaceToken) {
if (whitespaceToken.getNewlineCount() === 0) {
return;
}

var token = whitespaceToken.getPreviousNonWhitespaceToken();

if (!token) {
return;
}

var nextToken = token.getNextNonWhitespaceToken();

errors.assert.linesBetween({
token: token,
nextToken: nextToken,
atMost: 2
});
});
}
check: function(file, errors) {
// Iterate over all tokens (including comments)
Function (anonymous_402)
✓ Was called
file.iterateTokensByType('Whitespace', function(whitespaceToken) {···
if (whitespaceToken.getNewlineCount() === 0) {
return;
}

var token = whitespaceToken.getPreviousNonWhitespaceToken();

if (!token) {
return;
}

var nextToken = token.getNextNonWhitespaceToken();

errors.assert.linesBetween({
token: token,
nextToken: nextToken,
atMost: 2
});
});
file.iterateTokensByType('Whitespace', function(whitespaceToken) {
Branch IfStatement
✓ Positive was executed (if)
if (whitespaceToken.getNewlineCount() === 0) {···
return;
}
✓ Negative was executed (else)
}···

var token = whitespaceToken.getPreviousNonWhitespaceToken();
if (whitespaceToken.getNewlineCount() === 0) {
return;
}
var token = whitespaceToken.getPreviousNonWhitespaceToken();
Branch IfStatement
✓ Positive was executed (if)
if (!token) {···
return;
}
✓ Negative was executed (else)
}···

var nextToken = token.getNextNonWhitespaceToken();
if (!token) {
return;
}
var nextToken = token.getNextNonWhitespaceToken();
errors.assert.linesBetween({
token: token,
nextToken: nextToken,
atMost: 2
});
});
}
};
disallow-multiple-line-strings.js
/**
* Disallows strings that span multiple lines without using concatenation.
*
* Type: `Boolean`
*
* Value: `true`
*
* JSHint: [`multistr`](http://www.jshint.com/docs/options/#multistr)
*
* #### Example
*
* ```js
* "disallowMultipleLineStrings": true
* ```
*
* ##### Valid
* ```js
* var x = "multi" +
* "line";
* var y = "single line";
* ```
*
* ##### Invalid
* ```js
* var x = "multi \
* line";
* ```
*/
var assert = require('assert');
Function (anonymous_403)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_404)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_405)
✓ Was called
getOptionName: function() {···
return 'disallowMultipleLineStrings';
},
getOptionName: function() {
return 'disallowMultipleLineStrings';
},
Function (anonymous_406)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByType('String', function(token) {
if (token.getNewlineCount() !== 0) {
errors.add('Multiline strings are disallowed.', token);
}
});
}
check: function(file, errors) {
Function (anonymous_407)
✓ Was called
file.iterateTokensByType('String', function(token) {···
if (token.getNewlineCount() !== 0) {
errors.add('Multiline strings are disallowed.', token);
}
});
file.iterateTokensByType('String', function(token) {
Branch IfStatement
✓ Positive was executed (if)
if (token.getNewlineCount() !== 0) {···
errors.add('Multiline strings are disallowed.', token);
}
✓ Negative was executed (else)
}···
});
if (token.getNewlineCount() !== 0) {
errors.add('Multiline strings are disallowed.', token);
}
});
}
};
disallow-multiple-spaces.js
/**
* Disallows multiple indentation characters (tabs or spaces) between identifiers, keywords, and any other token
*
* Type: `Boolean` or `Object`
*
* Values: `true` or `{"allowEOLComments": true}` to allow on-line comments to be ignored
*
* #### Examples
*
* ```js
* "disallowMultipleSpaces": true
* // or
* "disallowMultipleSpaces": {"allowEOLComments": true}
* ```
*
* ##### Valid
* ```js
* var x = "hello";
* function y() {}
* ```
*
* ##### Valid for `{"allowEOLComments": true}`
*
* ```js
* var x = "hello" // world;
* function y() {}
* ```
*
* ##### Invalid
* ```js
* var x = "hello";
* function y() {}
* ```
*/
var assert = require('assert');
Function (anonymous_408)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_409)
✓ Was called
configure: function(options) {···
assert(
options === true ||
typeof options === 'object' &&
options.allowEOLComments === true,
this.getOptionName() + ' option requires true value ' +
'or an object with `allowEOLComments` property'
);

this._allowEOLComments = options.allowEOLComments;
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'object' &&···
options.allowEOLComments === true,
✓ Was returned
options === true ||
options === true ||
Branch LogicalExpression
✓ Was returned
options.allowEOLComments === true,
✓ Was returned
typeof options === 'object' &&
typeof options === 'object' &&
options.allowEOLComments === true,
this.getOptionName() + ' option requires true value ' +
'or an object with `allowEOLComments` property'
);
this._allowEOLComments = options.allowEOLComments;
},
Function (anonymous_410)
✓ Was called
getOptionName: function() {···
return 'disallowMultipleSpaces';
},
getOptionName: function() {
return 'disallowMultipleSpaces';
},
Function (anonymous_411)
✓ Was called
check: function(file, errors) {···
var token = file.getProgram().getFirstToken();
var nextToken;

while (token) {
nextToken = token.getNextNonWhitespaceToken();

if (!nextToken) {
break;
}

if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {
errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
atMost: 1
});
}

token = token.getNextNonWhitespaceToken();
}
}
check: function(file, errors) {
var token = file.getProgram().getFirstToken();
var nextToken;
while (token) {
nextToken = token.getNextNonWhitespaceToken();
Branch IfStatement
✓ Positive was executed (if)
if (!nextToken) {···
break;
}
✓ Negative was executed (else)
}···

if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {
if (!nextToken) {
break;
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {···
errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
atMost: 1
});
}
✓ Negative was executed (else)
}···

token = token.getNextNonWhitespaceToken();
Branch LogicalExpression
✓ Was returned
if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {
✓ Was returned
if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {
if (!this._allowEOLComments || nextToken.type !== 'CommentLine') {
errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
atMost: 1
});
}
token = token.getNextNonWhitespaceToken();
}
}
};
disallow-multiple-var-decl.js
/**
* Disallows multiple `var` declaration (except for-loop).
*
* Types: `Boolean` or `Object`
*
* Values:
*
* - `true` disallows multiple variable declarations except within a for loop
* - `Object`:
* - `'strict'` disallows all multiple variable declarations
* - `'allExcept'` array of exceptions:
* - `'undefined'` allows declarations where all variables are not defined
* - `'require'` allows declarations where all variables are importing external modules with require
*
* #### Example
*
* ```js
* "disallowMultipleVarDecl": true
* ```
*
* ##### Valid for `true`
*
* ```js
* var x = 1;
* var y = 2;
*
* for (var i = 0, j = arr.length; i < j; i++) {}
* ```
*
* ##### Valid for `{ strict: true }`
*
* ```js
* var x = 1;
* var y = 2;
* ```
*
* ##### Valid for `{ allExcept: ['undefined'] }`
*
* ```js
* var a, b;
* var x = 1;
* var y = 2;
*
* for (var i = 0, j = arr.length; i < j; i++) {}
* ```
* ##### Valid for `{ allExcept: ['require'] }`
*
* ```js
* var a = require('a'),
* b = require('b');
*
* var x = 1;
* var y = 2;
*
* for (var i = 0, j = arr.length; i < j; i++) {}
* ```
*
* ##### Invalid
*
* ```js
* var x = 1,
* y = 2;
*
* var x, y = 2, z;
* ```
*/
var assert = require('assert');
Function (anonymous_412)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_413)
✓ Was called
configure: function(options) {···
// support for legacy options
if (typeof options !== 'object') {
assert(
options === true ||
options === 'strict' ||
options === 'exceptUndefined',
this.getOptionName() +
' option requires a true value, "strict", "exceptUndefined", or an object'
);

var _options = {
strict: options === 'strict',
allExcept: []
};

if (options === 'exceptUndefined') {
_options.allExcept.push('undefined');
}

return this.configure(_options);
}

if (Array.isArray(options.allExcept)) {
this._exceptUndefined = options.allExcept.indexOf('undefined') > -1;
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}

this._strictMode = options.strict === true;
},
configure: function(options) {
// support for legacy options
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true ||
options === 'strict' ||
options === 'exceptUndefined',
this.getOptionName() +
' option requires a true value, "strict", "exceptUndefined", or an object'
);

var _options = {
strict: options === 'strict',
allExcept: []
};

if (options === 'exceptUndefined') {
_options.allExcept.push('undefined');
}

return this.configure(_options);
}
✓ Negative was executed (else)
}···

if (Array.isArray(options.allExcept)) {
if (typeof options !== 'object') {
assert(
Branch LogicalExpression
✓ Was returned
options === 'exceptUndefined',
✓ Was returned
options === true ||···
options === 'strict' ||
Branch LogicalExpression
✓ Was returned
options === 'strict' ||
✓ Was returned
options === true ||
options === true ||
options === 'strict' ||
options === 'exceptUndefined',
this.getOptionName() +
' option requires a true value, "strict", "exceptUndefined", or an object'
);
var _options = {
strict: options === 'strict',
allExcept: []
};
Branch IfStatement
✓ Positive was executed (if)
if (options === 'exceptUndefined') {···
_options.allExcept.push('undefined');
}
✓ Negative was executed (else)
}···

return this.configure(_options);
if (options === 'exceptUndefined') {
_options.allExcept.push('undefined');
}
return this.configure(_options);
}
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._exceptUndefined = options.allExcept.indexOf('undefined') > -1;
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}
✓ Negative was executed (else)
}···

this._strictMode = options.strict === true;
if (Array.isArray(options.allExcept)) {
this._exceptUndefined = options.allExcept.indexOf('undefined') > -1;
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}
this._strictMode = options.strict === true;
},
Function (anonymous_414)
✓ Was called
getOptionName: function() {···
return 'disallowMultipleVarDecl';
},
getOptionName: function() {
return 'disallowMultipleVarDecl';
},
Function (anonymous_415)
✓ Was called
check: function(file, errors) {···

function isSourcedFromRequire(node) {
// If this node is a CallExpression it has a callee,
// check if this is the `require` function
if (node.callee && node.callee.name === 'require') {
return true;
}

// If this CallExpression is not a `require` we keep looking for
// the `require` method up in the tree
if (node.callee && node.callee.object) {
return isSourcedFromRequire(node.callee.object);
}

// If there is no `callee` this might be a MemberExpression, keep
// look for the `require` method up in the tree.
if (node.object) {
return isSourcedFromRequire(node.object);
}

return false;
}

var inStrictMode = this._strictMode;
var exceptUndefined = this._exceptUndefined;
var exceptRequire = this._exceptRequire;

file.iterateNodesByType('VariableDeclaration', function(node) {
var definedVariables = node.declarations.filter(function(declaration) {
return !!declaration.init;
});
var hasDefinedVariables = definedVariables.length > 0;

var requireStatements = node.declarations.filter(function(declaration) {
var init = declaration.init;
return init && isSourcedFromRequire(init);
});
var allRequireStatements = requireStatements.length === node.declarations.length;

var isForStatement = node.parentElement.type === 'ForStatement';

// allow single var declarations
if (node.declarations.length === 1) {
return;
}

// allow multiple var declarations in for statement unless we're in strict mode
// for (var i = 0, j = myArray.length; i < j; i++) {}
if (!inStrictMode && isForStatement) {
return;
}

// allow multiple var declarations with all undefined variables in exceptUndefined mode
// var a, b, c
if (exceptUndefined && !hasDefinedVariables) {
return;
}

// allow multiple var declaration with all require
// var a = require("a"), b = require("b")
if (exceptRequire && allRequireStatements) {
return;
}

// allow multiple var declarations only with require && undefined
// var a = require("a"), b = require("b"), x, y
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
return;
}

errors.add('Multiple var declaration', node);
});
}
check: function(file, errors) {
Function isSourcedFromRequire
✓ Was called
function isSourcedFromRequire(node) {···
// If this node is a CallExpression it has a callee,
// check if this is the `require` function
if (node.callee && node.callee.name === 'require') {
return true;
}

// If this CallExpression is not a `require` we keep looking for
// the `require` method up in the tree
if (node.callee && node.callee.object) {
return isSourcedFromRequire(node.callee.object);
}

// If there is no `callee` this might be a MemberExpression, keep
// look for the `require` method up in the tree.
if (node.object) {
return isSourcedFromRequire(node.object);
}

return false;
}
function isSourcedFromRequire(node) {
// If this node is a CallExpression it has a callee,
// check if this is the `require` function
Branch IfStatement
✓ Positive was executed (if)
if (node.callee && node.callee.name === 'require') {···
return true;
}
✓ Negative was executed (else)
}···

// If this CallExpression is not a `require` we keep looking for
Branch LogicalExpression
✓ Was returned
if (node.callee && node.callee.name === 'require') {
✓ Was returned
if (node.callee && node.callee.name === 'require') {
if (node.callee && node.callee.name === 'require') {
return true;
}
// If this CallExpression is not a `require` we keep looking for
// the `require` method up in the tree
Branch IfStatement
✓ Positive was executed (if)
if (node.callee && node.callee.object) {···
return isSourcedFromRequire(node.callee.object);
}
✓ Negative was executed (else)
}···

// If there is no `callee` this might be a MemberExpression, keep
Branch LogicalExpression
✓ Was returned
if (node.callee && node.callee.object) {
✓ Was returned
if (node.callee && node.callee.object) {
if (node.callee && node.callee.object) {
return isSourcedFromRequire(node.callee.object);
}
// If there is no `callee` this might be a MemberExpression, keep
// look for the `require` method up in the tree.
Branch IfStatement
✓ Positive was executed (if)
if (node.object) {···
return isSourcedFromRequire(node.object);
}
✓ Negative was executed (else)
}···

return false;
if (node.object) {
return isSourcedFromRequire(node.object);
}
return false;
}
var inStrictMode = this._strictMode;
var exceptUndefined = this._exceptUndefined;
var exceptRequire = this._exceptRequire;
Function (anonymous_417)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···
var definedVariables = node.declarations.filter(function(declaration) {
return !!declaration.init;
});
var hasDefinedVariables = definedVariables.length > 0;

var requireStatements = node.declarations.filter(function(declaration) {
var init = declaration.init;
return init && isSourcedFromRequire(init);
});
var allRequireStatements = requireStatements.length === node.declarations.length;

var isForStatement = node.parentElement.type === 'ForStatement';

// allow single var declarations
if (node.declarations.length === 1) {
return;
}

// allow multiple var declarations in for statement unless we're in strict mode
// for (var i = 0, j = myArray.length; i < j; i++) {}
if (!inStrictMode && isForStatement) {
return;
}

// allow multiple var declarations with all undefined variables in exceptUndefined mode
// var a, b, c
if (exceptUndefined && !hasDefinedVariables) {
return;
}

// allow multiple var declaration with all require
// var a = require("a"), b = require("b")
if (exceptRequire && allRequireStatements) {
return;
}

// allow multiple var declarations only with require && undefined
// var a = require("a"), b = require("b"), x, y
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
return;
}

errors.add('Multiple var declaration', node);
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Function (anonymous_418)
✓ Was called
var definedVariables = node.declarations.filter(function(declaration) {···
return !!declaration.init;
});
var definedVariables = node.declarations.filter(function(declaration) {
return !!declaration.init;
});
var hasDefinedVariables = definedVariables.length > 0;
Function (anonymous_419)
✓ Was called
var requireStatements = node.declarations.filter(function(declaration) {···
var init = declaration.init;
return init && isSourcedFromRequire(init);
});
var requireStatements = node.declarations.filter(function(declaration) {
var init = declaration.init;
Branch LogicalExpression
✓ Was returned
return init && isSourcedFromRequire(init);
✓ Was returned
return init && isSourcedFromRequire(init);
return init && isSourcedFromRequire(init);
});
var allRequireStatements = requireStatements.length === node.declarations.length;
var isForStatement = node.parentElement.type === 'ForStatement';
// allow single var declarations
Branch IfStatement
✓ Positive was executed (if)
if (node.declarations.length === 1) {···
return;
}
✓ Negative was executed (else)
}···

// allow multiple var declarations in for statement unless we're in strict mode
if (node.declarations.length === 1) {
return;
}
// allow multiple var declarations in for statement unless we're in strict mode
// for (var i = 0, j = myArray.length; i < j; i++) {}
Branch IfStatement
✓ Positive was executed (if)
if (!inStrictMode && isForStatement) {···
return;
}
✓ Negative was executed (else)
}···

// allow multiple var declarations with all undefined variables in exceptUndefined mode
Branch LogicalExpression
✓ Was returned
if (!inStrictMode && isForStatement) {
✓ Was returned
if (!inStrictMode && isForStatement) {
if (!inStrictMode && isForStatement) {
return;
}
// allow multiple var declarations with all undefined variables in exceptUndefined mode
// var a, b, c
Branch IfStatement
✓ Positive was executed (if)
if (exceptUndefined && !hasDefinedVariables) {···
return;
}
✓ Negative was executed (else)
}···

// allow multiple var declaration with all require
Branch LogicalExpression
✓ Was returned
if (exceptUndefined && !hasDefinedVariables) {
✓ Was returned
if (exceptUndefined && !hasDefinedVariables) {
if (exceptUndefined && !hasDefinedVariables) {
return;
}
// allow multiple var declaration with all require
// var a = require("a"), b = require("b")
Branch IfStatement
✓ Positive was executed (if)
if (exceptRequire && allRequireStatements) {···
return;
}
✓ Negative was executed (else)
}···

// allow multiple var declarations only with require && undefined
Branch LogicalExpression
✓ Was returned
if (exceptRequire && allRequireStatements) {
✓ Was returned
if (exceptRequire && allRequireStatements) {
if (exceptRequire && allRequireStatements) {
return;
}
// allow multiple var declarations only with require && undefined
// var a = require("a"), b = require("b"), x, y
Branch IfStatement
✓ Positive was executed (if)
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {···
return;
}
✓ Negative was executed (else)
}···

errors.add('Multiple var declaration', node);
Branch LogicalExpression
✓ Was returned
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
✓ Was returned
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
Branch LogicalExpression
✓ Was returned
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
✓ Was returned
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
if (exceptUndefined && exceptRequire && definedVariables.length === requireStatements.length) {
return;
}
errors.add('Multiple var declaration', node);
});
}
};
disallow-named-unassigned-functions.js
/**
* Disallows unassigned functions to be named inline
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowNamedUnassignedFunctions": true
* ```
*
* ##### Valid
* ```js
* [].forEach(function () {});
* var x = function() {};
* function y() {}
* ```
*
* ##### Invalid
* ```js
* [].forEach(function x() {});
* ```
*/
var assert = require('assert');
Function (anonymous_420)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_421)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires true value'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires true value'
);
},
Function (anonymous_422)
✓ Was called
getOptionName: function() {···
return 'disallowNamedUnassignedFunctions';
},
getOptionName: function() {
return 'disallowNamedUnassignedFunctions';
},
Function (anonymous_423)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('FunctionExpression', function(node) {
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
if (node.parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}

// If the function has not been named, skip it
// e.g. `[].forEach(function() {`
if (node.id === null) {
return;
}

// Otherwise, complain that it is being named
errors.add('Inline functions cannot be named', node);
});
}
check: function(file, errors) {
Function (anonymous_424)
✓ Was called
file.iterateNodesByType('FunctionExpression', function(node) {···
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
if (node.parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}

// If the function has not been named, skip it
// e.g. `[].forEach(function() {`
if (node.id === null) {
return;
}

// Otherwise, complain that it is being named
errors.add('Inline functions cannot be named', node);
});
file.iterateNodesByType('FunctionExpression', function(node) {
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
Branch IfStatement
✓ Positive was executed (if)
if (node.parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {···
return;
}
✓ Negative was executed (else)
}···

// If the function has not been named, skip it
if (node.parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}
// If the function has not been named, skip it
// e.g. `[].forEach(function() {`
Branch IfStatement
✓ Positive was executed (if)
if (node.id === null) {···
return;
}
✓ Negative was executed (else)
}···

// Otherwise, complain that it is being named
if (node.id === null) {
return;
}
// Otherwise, complain that it is being named
errors.add('Inline functions cannot be named', node);
});
}
};
disallow-nested-ternaries.js
/**
* Disallows nested ternaries.
*
* Types: `Boolean`, `Object`
*
* Values: `true` or an Object that contains a `maxLevel` property equal to an integer
* indicating the maximum levels of nesting to be allowed.
*
* #### Examples
*
* ```js
* "disallowNestedTernaries": true
*
* // or
*
* "disallowNestedTernaries": { "maxLevel": 1 }
* ```
*
* ##### Valid for modes `true` and `"maxLevel": 1`
*
* ```js
* var foo = (a === b) ? 1 : 2;
* ```
*
* ##### Invalid for mode `true`, but valid for `"maxLevel": 1`
*
* ```js
* var foo = (a === b)
* ? (a === c)
* ? 1
* : 2
* : (b === c)
* ? 3
* : 4;
* ```
*
* ##### Invalid for modes `true` and `"maxLevel": 1`
*
* ```js
* var foo = (a === b)
* ? (a === c)
* ? (c === d)
* ? 5
* : 6
* : 2
* : (b === c)
* ? 3
* : 4;
* ```
*/
var assert = require('assert');
Function (anonymous_425)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_426)
✓ Was called
configure: function(options) {···
assert(
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
this.getOptionName() + ' option requires a true value or an object with "maxLevel" property'
);

this._maxLevel = 0;
if (options.maxLevel) {
this._maxLevel = options.maxLevel;
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
✓ Was returned
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
Branch LogicalExpression
✓ Was returned
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
✗ Was not returned
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
this.getOptionName() + ' option requires a true value or an object with "maxLevel" property'
);
this._maxLevel = 0;
Branch IfStatement
✓ Positive was executed (if)
if (options.maxLevel) {···
this._maxLevel = options.maxLevel;
}
✓ Negative was executed (else)
}···
},
if (options.maxLevel) {
this._maxLevel = options.maxLevel;
}
},
Function (anonymous_427)
✓ Was called
getOptionName: function() {···
return 'disallowNestedTernaries';
},
getOptionName: function() {
return 'disallowNestedTernaries';
},
Function (anonymous_428)
✓ Was called
check: function(file, errors) {···
var maxLevel = this._maxLevel;
file.iterateNodesByType('ConditionalExpression', function(node) {
var level = 0;
var getLevel = function(currentNode) {
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
level += 1;
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
};
getLevel(node);
});
}
check: function(file, errors) {
var maxLevel = this._maxLevel;
Function (anonymous_429)
✓ Was called
file.iterateNodesByType('ConditionalExpression', function(node) {···
var level = 0;
var getLevel = function(currentNode) {
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
level += 1;
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
};
getLevel(node);
});
file.iterateNodesByType('ConditionalExpression', function(node) {
var level = 0;
Function (anonymous_430)
✓ Was called
var getLevel = function(currentNode) {···
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
level += 1;
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
};
var getLevel = function(currentNode) {
Branch IfStatement
✓ Positive was executed (if)
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {···
level += 1;
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
✓ Negative was executed (else)
}···
};
Branch LogicalExpression
✓ Was returned
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
✗ Was not returned
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
level += 1;
Branch IfStatement
✓ Positive was executed (if)
if (level > maxLevel) {···
errors.add('Illegal nested ternary', node);
return;
}
✓ Negative was executed (else)
}···
getLevel(currentNode.parentElement);
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
};
getLevel(node);
});
}
};
disallow-newline-before-block-statements.js
/**
* Disallows newline before opening curly brace of all block statements.
*
* Type: `Boolean` or `Array` or `Object`
*
* Values:
*
* - `true` always disallows newline before curly brace of block statements
* - `Array` specifies block-type keywords after which newlines are disallowed before curly brace
* - Valid types include: `['if', 'else', 'try', 'catch', 'finally', 'do', 'while', 'for', 'function', 'class',
* 'switch']`
* - `Object`:
* - `value`: `true` or an Array
* - `allExcept`: Array of exceptions
* - `"multiLine"`: if the conditions span on multiple lines, require a new line before the curly brace
*
* #### Example
*
* ```js
* "disallowNewlineBeforeBlockStatements": true
* ```
*
* ##### Valid
*
* ```js
* function good(){
* var obj = {
* val: true
* };
*
* return {
* data: obj
* };
* }
*
* if (cond){
* foo();
* }
*
* for (var e in elements){
* bar(e);
* }
*
* while (cond){
* foo();
* }
* ```
*
* ##### Invalid
*
* ```js
* function bad()
* {
* var obj =
* {
* val: true
* };
*
* return {
* data: obj
* };
* }
*
* if (cond)
* {
* foo();
* }
*
* for (var e in elements)
* {
* bar(e);
* }
*
* while (cond)
* {
* foo();
* }
* ```
*
* #### Example
*
* ```js
* "disallowNewlineBeforeBlockStatements": ["if", "else", "for"]
* ```
*
* ##### Valid
*
* ```js
* if (i > 0) {
* positive = true;
* }
*
* if (i < 0) {
* negative = true;
* } else {
* negative = false;
* }
*
* for (var i = 0, len = myList.length; i < len; ++i) {
* newList.push(myList[i]);
* }
*
* // this is fine, since "function" wasn't configured
* function myFunc(x)
* {
* return x + 1;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (i < 0)
* {
* negative = true;
* }
*
* if (i < 0)
* {
* negative = true;
* }
* else
* {
* negative = false;
* }
*
* for (var i = 0, len = myList.length; i < len; ++i)
* {
* newList.push(myList[i]);
* }
* ```
*
* #### Example
*
* ```js
* "disallowNewlineBeforeBlockStatements": ["function", "while"]
* ```
*
* ##### Valid
*
* ```js
* function myFunc(x) {
* return x + 1;
* }
*
* var z = function(x) {
* return x - 1;
* }
*
* // this is fine, since "for" wasn't configured
* for (var i = 0, len = myList.length; i < len; ++i)
* {
* newList.push(myList[i]);
* }
* ```
*
* ##### Invalid
*
* ```js
* function myFunc(x)
* {
* return x + 1;
* }
*
* var z = function(x)
* {
* return x - 1;
* }
* ```
*
* #### Example
*
* ```js
* "disallowNewlineBeforeBlockStatements": {
* "value": true,
* "allExcept": ["multiLine"]
* }
* ```
*
* ##### Valid
*
* ```js
* function myFunc(x,
* y)
* {
* return x + y;
* }
*
* function foo() {
* if (bar && baz &&
* bat)
* {
* return true;
* }
* }
* ```
*
* ##### Invalid
*
* ```js
* function myFunc(x,
* y) {
* return x + y;
* }
*
* function foo() {
* if (bar && baz &&
* bat) {
* return true;
* }
* }
* ```
*/
var assert = require('assert');
Function (anonymous_431)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_432)
✓ Was called
configure: function(options) {···
var settingValue;
this._hasMultiLineEx = false;
if (options.constructor === Object) {
settingValue = options.value;
if (options.allExcept) {
assert(
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
options.allExcept[0] === 'multiLine',
'allExcept option must be an array whose values can be only `multiLine`'
);
this._hasMultiLineEx = true;
}
} else {
settingValue = options;
}
assert(
Array.isArray(settingValue) && settingValue.length || settingValue === true,
'disallowNewlineBeforeBlockStatements option requires non-empty array value or true value'
);

this._setting = settingValue;
},
configure: function(options) {
var settingValue;
this._hasMultiLineEx = false;
Branch IfStatement
✓ Positive was executed (if)
if (options.constructor === Object) {···
settingValue = options.value;
if (options.allExcept) {
assert(
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
options.allExcept[0] === 'multiLine',
'allExcept option must be an array whose values can be only `multiLine`'
);
this._hasMultiLineEx = true;
}
} else {
✓ Negative was executed (else)
} else {···
settingValue = options;
}
if (options.constructor === Object) {
settingValue = options.value;
Branch IfStatement
✓ Positive was executed (if)
if (options.allExcept) {···
assert(
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
options.allExcept[0] === 'multiLine',
'allExcept option must be an array whose values can be only `multiLine`'
);
this._hasMultiLineEx = true;
}
✗ Negative was not executed (else)
}···
} else {
if (options.allExcept) {
assert(
Branch LogicalExpression
✓ Was returned
options.allExcept[0] === 'multiLine',
✗ Was not returned
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
Branch LogicalExpression
✓ Was returned
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
✗ Was not returned
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
Array.isArray(options.allExcept) && options.allExcept.length === 1 &&
options.allExcept[0] === 'multiLine',
'allExcept option must be an array whose values can be only `multiLine`'
);
this._hasMultiLineEx = true;
}
} else {
settingValue = options;
}
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
Branch LogicalExpression
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
Array.isArray(settingValue) && settingValue.length || settingValue === true,
'disallowNewlineBeforeBlockStatements option requires non-empty array value or true value'
);
this._setting = settingValue;
},
Function (anonymous_433)
✓ Was called
getOptionName: function() {···
return 'disallowNewlineBeforeBlockStatements';
},
getOptionName: function() {
return 'disallowNewlineBeforeBlockStatements';
},
Function (anonymous_434)
✓ Was called
check: function(file, errors) {···
var setting = this._setting;
var hasMultiLineEx = this._hasMultiLineEx;

function assertSameLine(token, nextToken) {
errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is disallowed'
});
}
function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}

file.iterateNodesByType(['BlockStatement', 'ClassBody'], function(node) {
if (isBareBlock(node)) {
return;
}

if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

// Check if the 'conditions' span on multiple lines.
// The simplest way is to check if the round braces are on different lines.
//
// For example:
// // same line
// for (var i = 0; i < length; i++) {
// }
//
// // different lines:
// for (var i = 0;
// i < length;
// i++)
// {
// }
var parentElement = node.parentElement;
var parentNextToken = file.getFirstNodeToken(parentElement);
var openingRoundBrace = file.findNextToken(parentNextToken, 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

// Not always the conditions are there: to check look for the presence of round braces.
// For example:
// try {
// } ...
if (openingRoundBrace && closingRoundBrace &&
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
}
});

if (setting === true || setting.indexOf('switch') !== -1) {
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

var openingRoundBrace = file.findNextToken(file.getFirstNodeToken(node), 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

if (!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
});
}
}
check: function(file, errors) {
var setting = this._setting;
var hasMultiLineEx = this._hasMultiLineEx;
Function assertSameLine
✓ Was called
function assertSameLine(token, nextToken) {···
errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is disallowed'
});
}
function assertSameLine(token, nextToken) {
errors.assert.sameLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is disallowed'
});
}
Function assertDifferentLine
✓ Was called
function assertDifferentLine(token, nextToken) {···
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}
function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}
Function (anonymous_437)
✓ Was called
file.iterateNodesByType(['BlockStatement', 'ClassBody'], function(node) {···
if (isBareBlock(node)) {
return;
}

if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

// Check if the 'conditions' span on multiple lines.
// The simplest way is to check if the round braces are on different lines.
//
// For example:
// // same line
// for (var i = 0; i < length; i++) {
// }
//
// // different lines:
// for (var i = 0;
// i < length;
// i++)
// {
// }
var parentElement = node.parentElement;
var parentNextToken = file.getFirstNodeToken(parentElement);
var openingRoundBrace = file.findNextToken(parentNextToken, 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

// Not always the conditions are there: to check look for the presence of round braces.
// For example:
// try {
// } ...
if (openingRoundBrace && closingRoundBrace &&
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
}
});
file.iterateNodesByType(['BlockStatement', 'ClassBody'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isBareBlock(node)) {···
return;
}
✓ Negative was executed (else)
}···

if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
if (isBareBlock(node)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {···
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

// Check if the 'conditions' span on multiple lines.
// The simplest way is to check if the round braces are on different lines.
//
// For example:
// // same line
// for (var i = 0; i < length; i++) {
// }
//
// // different lines:
// for (var i = 0;
// i < length;
// i++)
// {
// }
var parentElement = node.parentElement;
var parentNextToken = file.getFirstNodeToken(parentElement);
var openingRoundBrace = file.findNextToken(parentNextToken, 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

// Not always the conditions are there: to check look for the presence of round braces.
// For example:
// try {
// } ...
if (openingRoundBrace && closingRoundBrace &&
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
✓ Was returned
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (hasMultiLineEx !== true) {···
assertSameLine(prevToken, openingBrace);
return;
}
✓ Negative was executed (else)
}···

// Check if the 'conditions' span on multiple lines.
if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}
// Check if the 'conditions' span on multiple lines.
// The simplest way is to check if the round braces are on different lines.
//
// For example:
// // same line
// for (var i = 0; i < length; i++) {
// }
//
// // different lines:
// for (var i = 0;
// i < length;
// i++)
// {
// }
var parentElement = node.parentElement;
var parentNextToken = file.getFirstNodeToken(parentElement);
var openingRoundBrace = file.findNextToken(parentNextToken, 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');
// Not always the conditions are there: to check look for the presence of round braces.
// For example:
// try {
// } ...
Branch IfStatement
✓ Positive was executed (if)
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {···
assertDifferentLine(prevToken, openingBrace);
} else {
✓ Negative was executed (else)
} else {···
assertSameLine(prevToken, openingBrace);
}
Branch LogicalExpression
✓ Was returned
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
✓ Was returned
if (openingRoundBrace && closingRoundBrace &&
Branch LogicalExpression
✓ Was returned
if (openingRoundBrace && closingRoundBrace &&
✗ Was not returned
if (openingRoundBrace && closingRoundBrace &&
if (openingRoundBrace && closingRoundBrace &&
!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
}
});
Branch IfStatement
✓ Positive was executed (if)
if (setting === true || setting.indexOf('switch') !== -1) {···
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

var openingRoundBrace = file.findNextToken(file.getFirstNodeToken(node), 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

if (!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
});
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (setting === true || setting.indexOf('switch') !== -1) {
✓ Was returned
if (setting === true || setting.indexOf('switch') !== -1) {
if (setting === true || setting.indexOf('switch') !== -1) {
Function (anonymous_438)
✓ Was called
file.iterateNodesByType(['SwitchStatement'], function(node) {···
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}

var openingRoundBrace = file.findNextToken(file.getFirstNodeToken(node), 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');

if (!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
});
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);
Branch IfStatement
✓ Positive was executed (if)
if (hasMultiLineEx !== true) {···
assertSameLine(prevToken, openingBrace);
return;
}
✓ Negative was executed (else)
}···

var openingRoundBrace = file.findNextToken(file.getFirstNodeToken(node), 'Punctuator', '(');
if (hasMultiLineEx !== true) {
assertSameLine(prevToken, openingBrace);
return;
}
var openingRoundBrace = file.findNextToken(file.getFirstNodeToken(node), 'Punctuator', '(');
var closingRoundBrace = file.findPrevToken(openingBrace, 'Punctuator', ')');
Branch IfStatement
✓ Positive was executed (if)
if (!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {···
assertDifferentLine(prevToken, openingBrace);
} else {
✓ Negative was executed (else)
} else {···
assertSameLine(prevToken, openingBrace);
}
if (!file.isOnTheSameLine(openingRoundBrace, closingRoundBrace)) {
assertDifferentLine(prevToken, openingBrace);
} else {
assertSameLine(prevToken, openingBrace);
}
});
}
}
};
Function isBareBlock
✓ Was called
function isBareBlock(node) {···
var parentElement = node.parentElement;

return parentElement &&
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
}
function isBareBlock(node) {
var parentElement = node.parentElement;
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
return parentElement &&···
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
Branch LogicalExpression
✓ Was returned
parentElement.type === 'Program' ||
✓ Was returned
return parentElement &&···
parentElement.type === 'BlockStatement' ||
Branch LogicalExpression
✓ Was returned
parentElement.type === 'BlockStatement' ||
✗ Was not returned
return parentElement &&
return parentElement &&
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
}
Function getBlockType
✓ Was called
function getBlockType(node) {···
var parentElement = node.parentElement;
switch (parentElement.type) {
case 'IfStatement':
return (parentElement.alternate === node) ? 'else' : 'if';
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
return 'function';
case 'ForStatement':
case 'ForInStatement':
case 'ForOfStatement':
return 'for';
case 'WhileStatement':
return 'while';
case 'DoWhileStatement':
return 'do';
case 'TryStatement':
return (parentElement.finalizer === node) ? 'finally' : 'try';
case 'CatchClause':
return 'catch';
case 'ClassDeclaration':
return 'class';
}
}
function getBlockType(node) {
var parentElement = node.parentElement;
Branch SwitchStatement
✓ Was evaluated
case 'IfStatement':···
return (parentElement.alternate === node) ? 'else' : 'if';
✓ Was evaluated
case 'FunctionDeclaration':
✓ Was evaluated
case 'FunctionExpression':
✓ Was evaluated
case 'ArrowFunctionExpression':···
return 'function';
✓ Was evaluated
case 'ForStatement':
✓ Was evaluated
case 'ForInStatement':
✓ Was evaluated
case 'ForOfStatement':···
return 'for';
✓ Was evaluated
case 'WhileStatement':···
return 'while';
✓ Was evaluated
case 'DoWhileStatement':···
return 'do';
✓ Was evaluated
case 'TryStatement':···
return (parentElement.finalizer === node) ? 'finally' : 'try';
✓ Was evaluated
case 'CatchClause':···
return 'catch';
✓ Was evaluated
case 'ClassDeclaration':···
return 'class';
switch (parentElement.type) {
case 'IfStatement':
Branch ConditionalExpression
✓ Positive was returned (? ...)
return (parentElement.alternate === node) ? 'else' : 'if';
✓ Negative was returned (: ...)
return (parentElement.alternate === node) ? 'else' : 'if';
return (parentElement.alternate === node) ? 'else' : 'if';
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
return 'function';
case 'ForStatement':
case 'ForInStatement':
case 'ForOfStatement':
return 'for';
case 'WhileStatement':
return 'while';
case 'DoWhileStatement':
return 'do';
case 'TryStatement':
Branch ConditionalExpression
✓ Positive was returned (? ...)
return (parentElement.finalizer === node) ? 'finally' : 'try';
✓ Negative was returned (: ...)
return (parentElement.finalizer === node) ? 'finally' : 'try';
return (parentElement.finalizer === node) ? 'finally' : 'try';
case 'CatchClause':
return 'catch';
case 'ClassDeclaration':
return 'class';
}
}
disallow-node-types.js
/**
* Disallow use of certain AST Node types.
*
* Babylon node types
* - [Core](https://github.com/babel/babel/blob/master/doc/ast/spec.md)
* - [Flow](https://github.com/babel/babel/blob/master/doc/ast/flow.md)
* - [JSX](https://github.com/babel/babel/blob/master/doc/ast/jsx.md)
*
* Type: `Array`
*
* Value: Array of parser node types to be disallowed.
*
* #### Example
*
* ```js
* "disallowNodeTypes": ['LabeledStatement']
* ```
*
* ##### Valid
*
* ```js
* // use of an allowed node type
* var a = 1;
* // shorthand form of arrow function that returns an object
* var f = () => ({ a: 1 });
* ```
*
* ##### Invalid
*
* ```js
* // label statement with loop
* loop1:
* for (i = 0; i < 10; i++) {
* if (i === 3) {
* break loop1;
* }
* }
* // accidental label statement with arrow function
* var f = () => { a: 1 };
* // label statement
* { a: 1 }
* ```
*/
var assert = require('assert');
Function (anonymous_441)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_442)
✓ Was called
configure: function(nodeTypes) {···
assert(
Array.isArray(nodeTypes),
'disallowNodeTypes option requires an array'
);

this._nodeTypes = nodeTypes;
},
configure: function(nodeTypes) {
assert(
Array.isArray(nodeTypes),
'disallowNodeTypes option requires an array'
);
this._nodeTypes = nodeTypes;
},
Function (anonymous_443)
✓ Was called
getOptionName: function() {···
return 'disallowNodeTypes';
},
getOptionName: function() {
return 'disallowNodeTypes';
},
Function (anonymous_444)
✓ Was called
check: function(file, errors) {···
var disallowedNodeTypes = this._nodeTypes;
file.iterateNodesByType(disallowedNodeTypes, function(node) {
errors.add('Illegal use of disallowed node type: ' + node.type, node);
});
}
check: function(file, errors) {
var disallowedNodeTypes = this._nodeTypes;
Function (anonymous_445)
✓ Was called
file.iterateNodesByType(disallowedNodeTypes, function(node) {···
errors.add('Illegal use of disallowed node type: ' + node.type, node);
});
file.iterateNodesByType(disallowedNodeTypes, function(node) {
errors.add('Illegal use of disallowed node type: ' + node.type, node);
});
}
};
disallow-not-operators-in-conditionals.js
/**
* Disallows the not, not equals, and strict not equals operators in conditionals.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowNotOperatorsInConditionals": true
* ```
*
* ##### Valid
*
* ```js
* if (clause) {
* // Do something really crazy
* } else {
* // Do something crazy
* }
*
* if (a == 1) {
* // Do something really crazy
* } else {
* // Do something crazy
* }
*
* var a = (clause) ? 1 : 0
* ```
*
* ##### Invalid
*
* ```js
* if (!clause) {
* // Do something crazy
* } else {
* // Do something really crazy
* }
*
* if (a != 1) {
* // Do something crazy
* } else {
* // Do something really crazy
* }
*
* if (a !== 1) {
* // Do something crazy
* } else {
* // Do something really crazy
* }
*
* var a = (!clause) ? 0 : 1
* ```
*/
var assert = require('assert');
Function (anonymous_446)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_447)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_448)
✓ Was called
getOptionName: function() {···
return 'disallowNotOperatorsInConditionals';
},
getOptionName: function() {
return 'disallowNotOperatorsInConditionals';
},
Function (anonymous_449)
✓ Was called
check: function(file, errors) {···
function hasNotOperator(test) {
return test.type === 'UnaryExpression' && test.operator === '!';
}

function hasNotEqualOperator(test) {
return test.type === 'BinaryExpression' && test.operator === '!=';
}

function hasStrictNotEqualOperator(test) {
return test.type === 'BinaryExpression' && test.operator === '!==';
}

file.iterateNodesByType(['IfStatement', 'ConditionalExpression'], function(node) {
var alternate = node.alternate;

// check if the if statement has an else block
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
return;
}
var test = node.test;
if (hasNotOperator(test)) {
errors.add('Illegal use of not operator in if statement', test);
}
if (hasNotEqualOperator(test)) {
errors.add('Illegal use of not equal operator in if statement', test);
}
if (hasStrictNotEqualOperator(test)) {
errors.add('Illegal use of strict not equal operator in if statement', test);
}
});
}
check: function(file, errors) {
Function hasNotOperator
✓ Was called
function hasNotOperator(test) {···
return test.type === 'UnaryExpression' && test.operator === '!';
}
function hasNotOperator(test) {
Branch LogicalExpression
✓ Was returned
return test.type === 'UnaryExpression' && test.operator === '!';
✓ Was returned
return test.type === 'UnaryExpression' && test.operator === '!';
return test.type === 'UnaryExpression' && test.operator === '!';
}
Function hasNotEqualOperator
✓ Was called
function hasNotEqualOperator(test) {···
return test.type === 'BinaryExpression' && test.operator === '!=';
}
function hasNotEqualOperator(test) {
Branch LogicalExpression
✓ Was returned
return test.type === 'BinaryExpression' && test.operator === '!=';
✓ Was returned
return test.type === 'BinaryExpression' && test.operator === '!=';
return test.type === 'BinaryExpression' && test.operator === '!=';
}
Function hasStrictNotEqualOperator
✓ Was called
function hasStrictNotEqualOperator(test) {···
return test.type === 'BinaryExpression' && test.operator === '!==';
}
function hasStrictNotEqualOperator(test) {
Branch LogicalExpression
✓ Was returned
return test.type === 'BinaryExpression' && test.operator === '!==';
✓ Was returned
return test.type === 'BinaryExpression' && test.operator === '!==';
return test.type === 'BinaryExpression' && test.operator === '!==';
}
Function (anonymous_453)
✓ Was called
file.iterateNodesByType(['IfStatement', 'ConditionalExpression'], function(node) {···
var alternate = node.alternate;

// check if the if statement has an else block
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
return;
}
var test = node.test;
if (hasNotOperator(test)) {
errors.add('Illegal use of not operator in if statement', test);
}
if (hasNotEqualOperator(test)) {
errors.add('Illegal use of not equal operator in if statement', test);
}
if (hasStrictNotEqualOperator(test)) {
errors.add('Illegal use of strict not equal operator in if statement', test);
}
});
file.iterateNodesByType(['IfStatement', 'ConditionalExpression'], function(node) {
var alternate = node.alternate;
// check if the if statement has an else block
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {···
return;
}
✓ Negative was executed (else)
}···
var test = node.test;
Branch LogicalExpression
✓ Was returned
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
✓ Was returned
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
Branch LogicalExpression
✓ Was returned
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
✓ Was returned
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
return;
}
var test = node.test;
Branch IfStatement
✓ Positive was executed (if)
if (hasNotOperator(test)) {···
errors.add('Illegal use of not operator in if statement', test);
}
✓ Negative was executed (else)
}···
if (hasNotEqualOperator(test)) {
if (hasNotOperator(test)) {
errors.add('Illegal use of not operator in if statement', test);
}
Branch IfStatement
✓ Positive was executed (if)
if (hasNotEqualOperator(test)) {···
errors.add('Illegal use of not equal operator in if statement', test);
}
✓ Negative was executed (else)
}···
if (hasStrictNotEqualOperator(test)) {
if (hasNotEqualOperator(test)) {
errors.add('Illegal use of not equal operator in if statement', test);
}
Branch IfStatement
✓ Positive was executed (if)
if (hasStrictNotEqualOperator(test)) {···
errors.add('Illegal use of strict not equal operator in if statement', test);
}
✓ Negative was executed (else)
}···
});
if (hasStrictNotEqualOperator(test)) {
errors.add('Illegal use of strict not equal operator in if statement', test);
}
});
}
};
disallow-object-keys-on-new-line.js
/**
* Disallows placing object keys on new line
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowObjectKeysOnNewLine": true
* ```
*
* ##### Valid
*
* ```js
* var a = {
* b: 'b', c: 'c'
* };
* ```
*
* ##### Invalid
*
* ```js
* var a = {
* b: 'b',
* c: 'c'
* };
* ```
*/
var assert = require('assert');
Function (anonymous_454)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_455)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_456)
✓ Was called
getOptionName: function() {···
return 'disallowObjectKeysOnNewLine';
},
getOptionName: function() {
return 'disallowObjectKeysOnNewLine';
},
Function (anonymous_457)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
var properties = node.properties;
for (var i = 1; i < properties.length; i++) {
var propertyNode = properties[i];

errors.assert.sameLine({
token: propertyNode.getPreviousCodeToken(),
nextToken: propertyNode.getFirstToken(),
message: 'Object keys should be on the same line'
});
}
});
}
check: function(file, errors) {
Function (anonymous_458)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var properties = node.properties;
for (var i = 1; i < properties.length; i++) {
var propertyNode = properties[i];

errors.assert.sameLine({
token: propertyNode.getPreviousCodeToken(),
nextToken: propertyNode.getFirstToken(),
message: 'Object keys should be on the same line'
});
}
});
file.iterateNodesByType('ObjectExpression', function(node) {
var properties = node.properties;
for (var i = 1; i < properties.length; i++) {
var propertyNode = properties[i];
errors.assert.sameLine({
token: propertyNode.getPreviousCodeToken(),
nextToken: propertyNode.getFirstToken(),
message: 'Object keys should be on the same line'
});
}
});
}
};
disallow-operator-before-line-break.js
/**
* Requires putting certain operators on the next line rather than on the current line before a line break.
*
* Types: `Array` or `Boolean`
*
* Values: Array of operators to apply to or `true`
*
* #### Example
*
* ```js
* "disallowOperatorBeforeLineBreak": ["+", "."]
* ```
*
* ##### Valid
*
* ```js
* $el.on( 'click', fn )
* .appendTo( 'body' );
*
* var x = 4 + 5
* + 12 + 13;
* ```
*
* ##### Invalid
*
* ```js
* $el.on( 'click', fn ).
* appendTo( 'body' );
*
* var x = 4 + 5 +
* 12 + 13;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').binaryOperators.slice().concat(['.']);
Function (anonymous_459)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_460)
✓ Was called
configure: function(operators) {···
assert(Array.isArray(operators) || operators === true,
this.getOptionName() + ' option requires array or true value');

if (operators === true) {
operators = defaultOperators;
}
this._operators = operators;
},
configure: function(operators) {
Branch LogicalExpression
✓ Was returned
assert(Array.isArray(operators) || operators === true,
✓ Was returned
assert(Array.isArray(operators) || operators === true,
assert(Array.isArray(operators) || operators === true,
this.getOptionName() + ' option requires array or true value');
Branch IfStatement
✓ Positive was executed (if)
if (operators === true) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···
this._operators = operators;
if (operators === true) {
operators = defaultOperators;
}
this._operators = operators;
},
Function (anonymous_461)
✓ Was called
getOptionName: function() {···
return 'disallowOperatorBeforeLineBreak';
},
getOptionName: function() {
return 'disallowOperatorBeforeLineBreak';
},
Function (anonymous_462)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Punctuator', this._operators, function(token) {
errors.assert.sameLine({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator needs to either be on the same line or after a line break.'
});
});
}
check: function(file, errors) {
Function (anonymous_463)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', this._operators, function(token) {···
errors.assert.sameLine({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator needs to either be on the same line or after a line break.'
});
});
file.iterateTokensByTypeAndValue('Punctuator', this._operators, function(token) {
errors.assert.sameLine({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator needs to either be on the same line or after a line break.'
});
});
}
};
disallow-padding-newlines-after-blocks.js
/**
* Disallow a newline after blocks
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowPaddingNewLinesAfterBlocks": true
* ```
*
* ##### Valid
*
* ```js
* function () {
* for (var i = 0; i < 2; i++) {
* if (true) {
* return false;
* }
* continue;
* }
* var obj = {
* foo: function() {
* return 1;
* },
* bar: function() {
* return 2;
* }
* };
* }
* ```
*
* ##### Invalid
*
* ```js
* function () {
* for (var i = 0; i < 2; i++) {
* if (true) {
* return false;
* }
*
* continue;
* }
*
* var obj = {
* foo: function() {
* return 1;
* },
*
* bar: function() {
* return 2;
* }
* };
* }
* ```
*/
var assert = require('assert');
Function (anonymous_464)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_465)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_466)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewLinesAfterBlocks';
},
getOptionName: function() {
return 'disallowPaddingNewLinesAfterBlocks';
},
Function (anonymous_467)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('BlockStatement', function(node) {
var endToken = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endToken);

while (nextToken.type !== 'EOF') {
if (file.isOnTheSameLine(endToken, nextToken)) {
endToken = nextToken;
nextToken = file.getNextToken(nextToken);
continue;
}

errors.assert.linesBetween({
token: endToken,
nextToken: nextToken,
atMost: 1,
message: 'Extra newline after closing curly brace'
});

return;
}
});
}
check: function(file, errors) {
Function (anonymous_468)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
var endToken = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endToken);

while (nextToken.type !== 'EOF') {
if (file.isOnTheSameLine(endToken, nextToken)) {
endToken = nextToken;
nextToken = file.getNextToken(nextToken);
continue;
}

errors.assert.linesBetween({
token: endToken,
nextToken: nextToken,
atMost: 1,
message: 'Extra newline after closing curly brace'
});

return;
}
});
file.iterateNodesByType('BlockStatement', function(node) {
var endToken = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endToken);
while (nextToken.type !== 'EOF') {
Branch IfStatement
✓ Positive was executed (if)
if (file.isOnTheSameLine(endToken, nextToken)) {···
endToken = nextToken;
nextToken = file.getNextToken(nextToken);
continue;
}
✓ Negative was executed (else)
}···

errors.assert.linesBetween({
if (file.isOnTheSameLine(endToken, nextToken)) {
endToken = nextToken;
nextToken = file.getNextToken(nextToken);
continue;
}
errors.assert.linesBetween({
token: endToken,
nextToken: nextToken,
atMost: 1,
message: 'Extra newline after closing curly brace'
});
return;
}
});
}
};
disallow-padding-newlines-after-use-strict.js
/**
* Disallow a blank line after `'use strict';` statements
*
* Values: `true`
*
* #### Example
*
* ```js
* "disallowPaddingNewLinesAfterUseStrict": true
* ```
*
* ##### Valid
*
* ```js
* 'use strict';
* // code
* ```
*
* ##### Invalid
*
* ```js
* 'use strict';
*
* // code
* ```
*/
var assert = require('assert');
Function (anonymous_469)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_470)
✓ Was called
configure: function(disallowPaddingNewLinesAfterUseStrict) {···
assert(
disallowPaddingNewLinesAfterUseStrict === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(disallowPaddingNewLinesAfterUseStrict) {
assert(
disallowPaddingNewLinesAfterUseStrict === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_471)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewLinesAfterUseStrict';
},
getOptionName: function() {
return 'disallowPaddingNewLinesAfterUseStrict';
},
Function (anonymous_472)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('Directive', function(node) {
var literal = node.value;

if (literal.value !== 'use strict') {
return;
}

var endOfNode = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});

errors.assert.linesBetween({
atMost: 1,
token: endOfNode,
nextToken: nextToken
});
});
}
check: function(file, errors) {
Function (anonymous_473)
✓ Was called
file.iterateNodesByType('Directive', function(node) {···
var literal = node.value;

if (literal.value !== 'use strict') {
return;
}

var endOfNode = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});

errors.assert.linesBetween({
atMost: 1,
token: endOfNode,
nextToken: nextToken
});
});
file.iterateNodesByType('Directive', function(node) {
var literal = node.value;
Branch IfStatement
✓ Positive was executed (if)
if (literal.value !== 'use strict') {···
return;
}
✓ Negative was executed (else)
}···

var endOfNode = file.getLastNodeToken(node);
if (literal.value !== 'use strict') {
return;
}
var endOfNode = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});
errors.assert.linesBetween({
atMost: 1,
token: endOfNode,
nextToken: nextToken
});
});
}
};
disallow-padding-newlines-before-export.js
/**
* Disallows newline before module.exports
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowPaddingNewLinesBeforeExport": true
* ```
*
* ##### Valid
*
* ```js
* var a = 2;
* module.exports = a;
* ```
*
* ##### Invalid
*
* ```js
* var a = 2;
*
* module.exports = a;
* ```
*/
var assert = require('assert');
Function (anonymous_474)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_475)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_476)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewLinesBeforeExport';
},
getOptionName: function() {
return 'disallowPaddingNewLinesBeforeExport';
},
Function (anonymous_477)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('AssignmentExpression', function(node) {
var left = node.left;

if (!(
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}

var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken, {includeComments: true});

errors.assert.linesBetween({
atMost: 1,
token: prevToken,
nextToken: firstToken,
message: 'Unexpected extra newline before export'
});
});
}
check: function(file, errors) {
Function (anonymous_478)
✓ Was called
file.iterateNodesByType('AssignmentExpression', function(node) {···
var left = node.left;

if (!(
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}

var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken, {includeComments: true});

errors.assert.linesBetween({
atMost: 1,
token: prevToken,
nextToken: firstToken,
message: 'Unexpected extra newline before export'
});
});
file.iterateNodesByType('AssignmentExpression', function(node) {
var left = node.left;
Branch IfStatement
✓ Positive was executed (if)
left.property.name === 'exports')) {···
return;
}
✓ Negative was executed (else)
}···

var firstToken = node.getFirstToken();
if (!(
Branch LogicalExpression
✓ Was returned
left.property.name === 'exports')) {
✓ Was returned
left.object &&···
left.object.name === 'module' &&
left.property &&
Branch LogicalExpression
✓ Was returned
left.property &&
✓ Was returned
left.object &&···
left.object.name === 'module' &&
Branch LogicalExpression
✓ Was returned
left.object.name === 'module' &&
✓ Was returned
left.object &&
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}
var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken, {includeComments: true});
errors.assert.linesBetween({
atMost: 1,
token: prevToken,
nextToken: firstToken,
message: 'Unexpected extra newline before export'
});
});
}
};
disallow-padding-newlines-before-keywords.js
/**
* Disallow an empty line above the specified keywords.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted types or `true` to disallow padding new lines after all of the keywords below.
*
* #### Example
*
* ```js
* "disallowPaddingNewlinesBeforeKeywords": [
* "do",
* "for",
* "if",
* "else",
* "switch",
* "case",
* "try",
* "catch",
* "void",
* "while",
* "with",
* "return",
* "typeof",
* "function"
* ]
* ```
*
* ##### Valid
*
* ```js
* function(a) {
* if (!a) {
* return false;
* }
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
* return false;
* }
* }
* return true;
* }
* ```
*
* ##### Invalid
*
* ```js
* function(a) {
* if (!a) {
*
* return false;
* }
*
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
*
* return false;
* }
* }
*
* return true;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
Function (anonymous_479)
✓ Was called
module.exports = function() { };
module.exports = function() { };
module.exports.prototype = {
Function (anonymous_480)
✓ Was called
configure: function(keywords) {···
assert(Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');

if (keywords === true) {
keywords = defaultKeywords;
}

this._keywords = keywords;
},
configure: function(keywords) {
Branch LogicalExpression
✓ Was returned
assert(Array.isArray(keywords) || keywords === true,
✓ Was returned
assert(Array.isArray(keywords) || keywords === true,
assert(Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');
Branch IfStatement
✓ Positive was executed (if)
if (keywords === true) {···
keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
Function (anonymous_481)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewlinesBeforeKeywords';
},
getOptionName: function() {
return 'disallowPaddingNewlinesBeforeKeywords';
},
Function (anonymous_482)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.assert.linesBetween({
token: file.getPrevToken(token, { includeComments: true }),
nextToken: token,
atMost: 1,
message: 'Keyword `' + token.value + '` should not have an empty line above it'
});
});
}
check: function(file, errors) {
Function (anonymous_483)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
errors.assert.linesBetween({
token: file.getPrevToken(token, { includeComments: true }),
nextToken: token,
atMost: 1,
message: 'Keyword `' + token.value + '` should not have an empty line above it'
});
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.assert.linesBetween({
token: file.getPrevToken(token, { includeComments: true }),
nextToken: token,
atMost: 1,
message: 'Keyword `' + token.value + '` should not have an empty line above it'
});
});
}
};
disallow-padding-newlines-before-line-comments.js
/**
* Disallows newline before line comments
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowPaddingNewLinesBeforeLineComments": true
* ```
*
* ##### Valid
*
* ```js
* var a = 2;
* // comment
* return a;
* ```
*
* ##### Invalid
*
* ```js
* var a = 2;
*
* //comment
* return a;
* ```
*/
var assert = require('assert');
Function (anonymous_484)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_485)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_486)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewLinesBeforeLineComments';
},
getOptionName: function() {
return 'disallowPaddingNewLinesBeforeLineComments';
},
Function (anonymous_487)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByType('CommentLine', function(comment) {
if (comment.getLoc().start.line === 1) {
return;
}

errors.assert.linesBetween({
token: file.getPrevToken(comment, {includeComments: true}),
nextToken: comment,
atMost: 1,
message: 'Line comments must not be preceded with a blank line'
});
});
}
check: function(file, errors) {
Function (anonymous_488)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
if (comment.getLoc().start.line === 1) {
return;
}

errors.assert.linesBetween({
token: file.getPrevToken(comment, {includeComments: true}),
nextToken: comment,
atMost: 1,
message: 'Line comments must not be preceded with a blank line'
});
});
file.iterateTokensByType('CommentLine', function(comment) {
Branch IfStatement
✓ Positive was executed (if)
if (comment.getLoc().start.line === 1) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.linesBetween({
if (comment.getLoc().start.line === 1) {
return;
}
errors.assert.linesBetween({
token: file.getPrevToken(comment, {includeComments: true}),
nextToken: comment,
atMost: 1,
message: 'Line comments must not be preceded with a blank line'
});
});
}
};
disallow-padding-newlines-in-blocks.js
/**
* Disallows blocks from beginning or ending with 2 newlines.
*
* Type: `Boolean` or `Object`
*
* Values:
* - `true` validates all non-empty blocks.
* - `Object`:
* - `'open'`
* - `true` validates that there is a newline after the opening brace in a block
* - `false` ignores the newline validation after the opening brace in a block
* - `'close'`
* - `true` validates that there is a newline before the closing brace in a block
* - `false` ignores the newline validation before the closing brace in a block
* - `'allExcept'` array of exceptions:
* - `'conditionals'` ignores conditional (if, else if, else) blocks
* - `'functions'` ignores function blocks
*
* #### Example
*
* ```js
* "disallowPaddingNewlinesInBlocks": true
* "disallowPaddingNewlinesInBlocks": { "open": true, "close": false }
* "disallowPaddingNewlinesInBlocks": { "allExcept": [ "conditionals" ] }
* "disallowPaddingNewlinesInBlocks": { "open": true, "close": false, allExcept: ['conditionals'] }
* ```
*
* ##### Valid for `true`
*
* ```js
* if (true) {
* doSomething();
* }
* if (true) {doSomething();}
* var abc = function() {};
* ```
*
* ##### Valid for mode `{ "open": true, "close": false }`
*
* ```js
* if (true) {
* doSomething();
*
* }
* ```
*
* ##### Valid for `{ allExcept: ['conditionals'] }`
*
* ```js
* if (true) {
*
* doSomething();
*
* }
*
* function (foo) {
* return bar;
* }
* ```
*
* ##### Valid for `{ "open": true, "close": false, allExcept: ['conditionals'] }`
*
* ```js
* function (foo) {
* return bar;
*
* }
*
* if (true) {
*
* doSomething();
*
* }
* ```
*
* ##### Invalid
*
* ```js
* if (true) {
*
* doSomething();
*
* }
* ```
*/
var assert = require('assert');
Function (anonymous_489)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_490)
✓ Was called
configure: function(options) {···
var optionName = this.getOptionName();

this._checkOpen = true;
this._checkClose = true;

if (typeof options === 'object') {
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');

if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}

if (options.open || options.close) {
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
},
configure: function(options) {
var optionName = this.getOptionName();
this._checkOpen = true;
this._checkClose = true;
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');

if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}

if (options.open || options.close) {
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
} else {
✓ Negative was executed (else)
} else {···
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
if (typeof options === 'object') {
Branch LogicalExpression
✓ Was returned
assert(options.allExcept || options.open || options.close,
✓ Was returned
assert(options.allExcept || options.open || options.close,
Branch LogicalExpression
✓ Was returned
assert(options.allExcept || options.open || options.close,
✓ Was returned
assert(options.allExcept || options.open || options.close,
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');
Branch IfStatement
✓ Positive was executed (if)
if (options.allExcept) {···
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}
✓ Negative was executed (else)
}···

if (options.open || options.close) {
if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}
Branch IfStatement
✓ Positive was executed (if)
if (options.open || options.close) {···
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
✓ Negative was executed (else)
}···
} else {
Branch LogicalExpression
✓ Was returned
if (options.open || options.close) {
✓ Was returned
if (options.open || options.close) {
if (options.open || options.close) {
Branch LogicalExpression
✓ Was returned
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
✗ Was not returned
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');
this._checkOpen = options.open;
this._checkClose = options.close;
}
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
},
Function (anonymous_491)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewlinesInBlocks';
},
getOptionName: function() {
return 'disallowPaddingNewlinesInBlocks';
},
Function (anonymous_492)
✓ Was called
check: function(file, errors) {···
var exceptConditionals = this._exceptConditionals;
var exceptFunctions = this._exceptFunctions;
var checkOpen = this._checkOpen;
var checkClose = this._checkClose;

file.iterateNodesByType('BlockStatement', function(node) {
var openingBracket;
var closingBracket;

if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}

if (checkOpen === true) {
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atMost: 1,
message: 'Expected no padding newline after opening curly brace'
});
}

if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atMost: 1,
message: 'Expected no padding newline before closing curly brace'
});
}
});
}
check: function(file, errors) {
var exceptConditionals = this._exceptConditionals;
var exceptFunctions = this._exceptFunctions;
var checkOpen = this._checkOpen;
var checkClose = this._checkClose;
Function (anonymous_493)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
var openingBracket;
var closingBracket;

if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}

if (checkOpen === true) {
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atMost: 1,
message: 'Expected no padding newline after opening curly brace'
});
}

if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atMost: 1,
message: 'Expected no padding newline before closing curly brace'
});
}
});
file.iterateNodesByType('BlockStatement', function(node) {
var openingBracket;
var closingBracket;
Branch IfStatement
✓ Positive was executed (if)
node.parentElement.type === 'FunctionDeclaration')) {···
return;
}
✓ Negative was executed (else)
}···

if (checkOpen === true) {
Branch LogicalExpression
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||···
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
Branch LogicalExpression
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
Branch LogicalExpression
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||···
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (checkOpen === true) {···
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atMost: 1,
message: 'Expected no padding newline after opening curly brace'
});
}
✓ Negative was executed (else)
}···

if (checkClose === true) {
if (checkOpen === true) {
openingBracket = node.getFirstToken();
errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atMost: 1,
message: 'Expected no padding newline after opening curly brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (checkClose === true) {···
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atMost: 1,
message: 'Expected no padding newline before closing curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);
errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atMost: 1,
message: 'Expected no padding newline before closing curly brace'
});
}
});
}
};
disallow-padding-newlines-in-objects.js
/**
* Disallows newlines adjacent to curly braces in all object literals.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowPaddingNewLinesInObjects": true
* ```
*
* ##### Valid
*
* ```js
* var x = { a: 1 };
* var y = { a: 1,
* b: 2 };
* var z = { a: 2,
* b: 2,
*
* c: 3,
*
*
*
* d: 4 };
* foo({a: {b: 1}});
* ```
*
* ##### Invalid
*
* ```js
* var x = {
* a: 1
* };
* foo({
* a: {
* b: 1
* }
* });
* ```
*/
var assert = require('assert');
Function (anonymous_494)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_495)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_496)
✓ Was called
getOptionName: function() {···
return 'disallowPaddingNewLinesInObjects';
},
getOptionName: function() {
return 'disallowPaddingNewLinesInObjects';
},
Function (anonymous_497)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}

errors.assert.sameLine({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);

errors.assert.sameLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Illegal newline before closing curly brace'
});
});
}
check: function(file, errors) {
Function (anonymous_498)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}

errors.assert.sameLine({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);

errors.assert.sameLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Illegal newline before closing curly brace'
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.sameLine({
Branch LogicalExpression
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}
errors.assert.sameLine({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal newline after opening curly brace'
});
var closingBracket = file.getLastNodeToken(node);
errors.assert.sameLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Illegal newline before closing curly brace'
});
});
}
};
disallow-parentheses-around-arrow-param.js
/**
* Disallows parentheses around arrow function expressions with a single parameter.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "disallowParenthesesAroundArrowParam": true
* ```
*
* ##### Valid
*
* ```js
* [1, 2, 3].map(x => x * x);
* // parentheses are always required for multiple parameters
* [1, 2, 3].map((x, y, z) => x * x);
* ```
*
* ##### Invalid
*
* ```js
* [1, 2, 3].map((x) => x * x);
* ```
*/
var assert = require('assert');
Function (anonymous_499)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_500)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_501)
✓ Was called
getOptionName: function() {···
return 'disallowParenthesesAroundArrowParam';
},
getOptionName: function() {
return 'disallowParenthesesAroundArrowParam';
},
Function (anonymous_502)
✓ Was called
check: function(file, errors) {···
function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}

file.iterateNodesByType('ArrowFunctionExpression', function(node) {
if (node.params.length !== 1) {
return;
}
var firstParam = node.params[0];

var hasDefaultParameter = firstParam.type === 'AssignmentPattern';
var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
var hasRestElement = firstParam.type === 'RestElement';

if (hasDefaultParameter ||
hasDestructuring ||
hasRestElement) {
return;
}

if (isWrapped(firstParam)) {
errors.add('Illegal wrap of arrow function expressions in parentheses', firstParam);
}
});
}
check: function(file, errors) {
Function isWrapped
✓ Was called
function isWrapped(node) {···
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}
function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
Branch ConditionalExpression
✓ Positive was returned (? ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
✗ Negative was not returned (: ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
return openParensToken.value + closingTokenValue === '()';
}
Function (anonymous_504)
✓ Was called
file.iterateNodesByType('ArrowFunctionExpression', function(node) {···
if (node.params.length !== 1) {
return;
}
var firstParam = node.params[0];

var hasDefaultParameter = firstParam.type === 'AssignmentPattern';
var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
var hasRestElement = firstParam.type === 'RestElement';

if (hasDefaultParameter ||
hasDestructuring ||
hasRestElement) {
return;
}

if (isWrapped(firstParam)) {
errors.add('Illegal wrap of arrow function expressions in parentheses', firstParam);
}
});
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.params.length !== 1) {···
return;
}
✓ Negative was executed (else)
}···
var firstParam = node.params[0];
if (node.params.length !== 1) {
return;
}
var firstParam = node.params[0];
var hasDefaultParameter = firstParam.type === 'AssignmentPattern';
Branch LogicalExpression
✓ Was returned
var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
✓ Was returned
var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
var hasRestElement = firstParam.type === 'RestElement';
Branch IfStatement
✓ Positive was executed (if)
hasRestElement) {···
return;
}
✓ Negative was executed (else)
}···

if (isWrapped(firstParam)) {
Branch LogicalExpression
✓ Was returned
hasRestElement) {
✓ Was returned
if (hasDefaultParameter ||···
hasDestructuring ||
Branch LogicalExpression
✓ Was returned
hasDestructuring ||
✓ Was returned
if (hasDefaultParameter ||
if (hasDefaultParameter ||
hasDestructuring ||
hasRestElement) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (isWrapped(firstParam)) {···
errors.add('Illegal wrap of arrow function expressions in parentheses', firstParam);
}
✓ Negative was executed (else)
}···
});
if (isWrapped(firstParam)) {
errors.add('Illegal wrap of arrow function expressions in parentheses', firstParam);
}
});
}
};
disallow-quoted-keys-in-objects.js
/**
* Disallows quoted keys in object if possible.
*
* Types: `Boolean`, `String` or `Object`
*
* Values:
*
* - `true` for strict mode
* - `"allButReserved"` (*deprecated* use `"allExcept": ["reserved"]`)
* - `Object`:
* - `"allExcept"` array of exceptions:
* - `"reserved"` allows ES3+ reserved words to remain quoted
* which is helpful when using this option with JSHint's `es3` flag.
*
* #### Example
*
* ```js
* "disallowQuotedKeysInObjects": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = { a: { default: 1 } };
* ```
*
* ##### Valid for mode `{"allExcept": ["reserved"]}`
*
* ```js
* var x = {a: 1, 'default': 2};
* ```
*
* ##### Invalid
*
* ```js
* var x = {'a': 1};
* ```
*/
var assert = require('assert');
var reservedWords = require('reserved-words');
var cst = require('cst');
Function (anonymous_505)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_506)
✓ Was called
configure: function(options) {···
assert(
options === true || options === 'allButReserved' || typeof options === 'object',
this.getOptionName() + ' option requires a true value or an object'
);

this._exceptReserved = options === 'allButReserved';
if (Array.isArray(options.allExcept)) {
this._exceptReserved = options.allExcept.indexOf('reserved') !== -1;
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'allButReserved' || typeof options === 'object',
✓ Was returned
options === true || options === 'allButReserved' || typeof options === 'object',
Branch LogicalExpression
✓ Was returned
options === true || options === 'allButReserved' || typeof options === 'object',
✓ Was returned
options === true || options === 'allButReserved' || typeof options === 'object',
options === true || options === 'allButReserved' || typeof options === 'object',
this.getOptionName() + ' option requires a true value or an object'
);
this._exceptReserved = options === 'allButReserved';
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._exceptReserved = options.allExcept.indexOf('reserved') !== -1;
}
✓ Negative was executed (else)
}···
},
if (Array.isArray(options.allExcept)) {
this._exceptReserved = options.allExcept.indexOf('reserved') !== -1;
}
},
Function (anonymous_507)
✓ Was called
getOptionName: function() {···
return 'disallowQuotedKeysInObjects';
},
getOptionName: function() {
return 'disallowQuotedKeysInObjects';
},
Function (anonymous_508)
✓ Was called
check: function(file, errors) {···
var KEY_NAME_RE = /^(0|[1-9][0-9]*|[a-zA-Z_$]+[\w$]*)$/; // number or identifier
var exceptReserved = this._exceptReserved;

file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(prop) {
var key = prop.key;

// Spread properties
if (!key) {
return;
}

if (key.type !== 'StringLiteral') {
return;
}

if (typeof key.value !== 'string') {
return;
}

if (!KEY_NAME_RE.test(key.value)) {
return;
}

if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
return;
}

errors.cast({
message: 'Extra quotes for key',
element: prop
});
});
});
},
check: function(file, errors) {
var KEY_NAME_RE = /^(0|[1-9][0-9]*|[a-zA-Z_$]+[\w$]*)$/; // number or identifier
var exceptReserved = this._exceptReserved;
Function (anonymous_509)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
node.properties.forEach(function(prop) {
var key = prop.key;

// Spread properties
if (!key) {
return;
}

if (key.type !== 'StringLiteral') {
return;
}

if (typeof key.value !== 'string') {
return;
}

if (!KEY_NAME_RE.test(key.value)) {
return;
}

if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
return;
}

errors.cast({
message: 'Extra quotes for key',
element: prop
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_510)
✓ Was called
node.properties.forEach(function(prop) {···
var key = prop.key;

// Spread properties
if (!key) {
return;
}

if (key.type !== 'StringLiteral') {
return;
}

if (typeof key.value !== 'string') {
return;
}

if (!KEY_NAME_RE.test(key.value)) {
return;
}

if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
return;
}

errors.cast({
message: 'Extra quotes for key',
element: prop
});
});
node.properties.forEach(function(prop) {
var key = prop.key;
// Spread properties
Branch IfStatement
✓ Positive was executed (if)
if (!key) {···
return;
}
✓ Negative was executed (else)
}···

if (key.type !== 'StringLiteral') {
if (!key) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (key.type !== 'StringLiteral') {···
return;
}
✓ Negative was executed (else)
}···

if (typeof key.value !== 'string') {
if (key.type !== 'StringLiteral') {
return;
}
Branch IfStatement
✗ Positive was not executed (if)
if (typeof key.value !== 'string') {···
return;
}
✓ Negative was executed (else)
}···

if (!KEY_NAME_RE.test(key.value)) {
if (typeof key.value !== 'string') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!KEY_NAME_RE.test(key.value)) {···
return;
}
✓ Negative was executed (else)
}···

if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
if (!KEY_NAME_RE.test(key.value)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {···
return;
}
✓ Negative was executed (else)
}···

errors.cast({
Branch LogicalExpression
✓ Was returned
if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
✓ Was returned
if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
return;
}
errors.cast({
message: 'Extra quotes for key',
element: prop
});
});
});
},
Function (anonymous_511)
✓ Was called
_fix: function(file, error) {···
var node = error.element;
var key = node.key.childElements[0];

var newKey = new cst.Token(key.type, key.getSourceCode().slice(1, -1));

node.key.replaceChild(newKey, key);
}
_fix: function(file, error) {
var node = error.element;
var key = node.key.childElements[0];
var newKey = new cst.Token(key.type, key.getSourceCode().slice(1, -1));
node.key.replaceChild(newKey, key);
}
};
disallow-semicolons.js
/**
* Disallows lines from ending in a semicolon.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSemicolons": true
* ```
*
* ##### Valid
*
* ```js
* var a = 1
* ;[b].forEach(c)
* ```
*
* ##### Invalid
*
* ```js
* var a = 1;
* [b].forEach(c);
* ```
*/
var assert = require('assert');
var nodeExceptions = {
ForStatement: true
};
var tokenExceptions = {
'[': true,
'(': true
};
Function (anonymous_512)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_513)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_514)
✓ Was called
getOptionName: function() {···
return 'disallowSemicolons';
},
getOptionName: function() {
return 'disallowSemicolons';
},
Function (anonymous_515)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {
var nextToken = file.getNextToken(token);

var node = token.parentElement;

// Ignore node exceptions
if (node.type in nodeExceptions) {
return;
}

// Ignore next token exceptions
if (nextToken.value in tokenExceptions) {
return;
}

if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
errors.cast({
message: 'semicolons are disallowed at the end of a line.',
element: token
});
}
});
},
check: function(file, errors) {
Function (anonymous_516)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {···
var nextToken = file.getNextToken(token);

var node = token.parentElement;

// Ignore node exceptions
if (node.type in nodeExceptions) {
return;
}

// Ignore next token exceptions
if (nextToken.value in tokenExceptions) {
return;
}

if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
errors.cast({
message: 'semicolons are disallowed at the end of a line.',
element: token
});
}
});
file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {
var nextToken = file.getNextToken(token);
var node = token.parentElement;
// Ignore node exceptions
Branch IfStatement
✓ Positive was executed (if)
if (node.type in nodeExceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Ignore next token exceptions
if (node.type in nodeExceptions) {
return;
}
// Ignore next token exceptions
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value in tokenExceptions) {···
return;
}
✓ Negative was executed (else)
}···

if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
if (nextToken.value in tokenExceptions) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {···
errors.cast({
message: 'semicolons are disallowed at the end of a line.',
element: token
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
✓ Was returned
if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
if (nextToken.type === 'EOF' || !file.isOnTheSameLine(token, nextToken)) {
errors.cast({
message: 'semicolons are disallowed at the end of a line.',
element: token
});
}
});
},
Function (anonymous_517)
✓ Was called
_fix: function(file, error) {···
error.element.remove();
}
_fix: function(file, error) {
error.element.remove();
}
};
disallow-shorthand-arrow-functions.js
/**
* Require arrow functions to use a block statement (explicit return).
*
* Why enable this rule? Arrow functions' syntax can cause maintenance issues:
*
* - When you add additional lines to an arrow function's expression body, the
* function will now return `undefined`, unless you remember to add an
* explicit `return`.
* - The shorthand syntax is ambiguous in terms of returning objects.
* `(name) => {id: name}` is interpreted as a longhand arrow function with the
* label `id:`.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "disallowShorthandArrowFunctions": true
* ```
*
* ##### Valid
*
* ```js
* // block statement
* evens.map(v => {
* return v + 1;
* });
* ```
*
* ##### Invalid
*
* ```js
* // single expression
* evens.map(v => v + 1);
* ```
*/
var assert = require('assert');
Function (anonymous_518)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_519)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_520)
✓ Was called
getOptionName: function() {···
return 'disallowShorthandArrowFunctions';
},
getOptionName: function() {
return 'disallowShorthandArrowFunctions';
},
Function (anonymous_521)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
if (node.expression) {
errors.add('Use arrow function with explicit block and explicit return', node.body);
}
});
}
check: function(file, errors) {
Function (anonymous_522)
✓ Was called
file.iterateNodesByType('ArrowFunctionExpression', function(node) {···
if (node.expression) {
errors.add('Use arrow function with explicit block and explicit return', node.body);
}
});
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.expression) {···
errors.add('Use arrow function with explicit block and explicit return', node.body);
}
✓ Negative was executed (else)
}···
});
if (node.expression) {
errors.add('Use arrow function with explicit block and explicit return', node.body);
}
});
}
};
disallow-space-after-binary-operators.js
/**
* Requires sticking binary operators to the right.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to disallow space after all possible binary operators
*
* #### Example
*
* ```js
* "disallowSpaceAfterBinaryOperators": [
* "=",
* ",",
* "+",
* "-",
* "/",
* "*",
* "==",
* "===",
* "!=",
* "!=="
* // etc
* ]
* ```
*
* ##### Valid
*
* ```js
* x +y;
* ```
*
* ##### Invalid
*
* ```js
* x+ y;
* ```
*/
var assert = require('assert');
var allOperators = require('../utils').binaryOperators;
Function (anonymous_523)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_524)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = allOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = allOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = allOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_525)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterBinaryOperators';
},
getOptionName: function() {
return 'disallowSpaceAfterBinaryOperators';
},
Function (anonymous_526)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;

// Comma
if (operators[',']) {
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
if (file.getNextToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should stick to following expression'
});
});
}

// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
function(node) {
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var nextToken = file.getNextToken(operatorToken);

if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should stick to following expression'
});
}
}
);
}
check: function(file, errors) {
var operators = this._operatorIndex;
// Comma
Branch IfStatement
✓ Positive was executed (if)
if (operators[',']) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
if (file.getNextToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should stick to following expression'
});
});
}
✓ Negative was executed (else)
}···

// For everything else
if (operators[',']) {
Function (anonymous_527)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
if (file.getNextToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should stick to following expression'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
Branch IfStatement
✓ Positive was executed (if)
if (file.getNextToken(token).value === ',') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
if (file.getNextToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should stick to following expression'
});
});
}
// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
Function (anonymous_528)
✓ Was called
function(node) {···
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var nextToken = file.getNextToken(operatorToken);

if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should stick to following expression'
});
}
}
function(node) {
var operator;
var expression;
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclarator') {···
expression = node.init;
operator = '=';
} else {
✓ Negative was executed (else)
} else {···
operator = node.operator;
expression = node.right;
}
if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}
Branch IfStatement
✓ Positive was executed (if)
if (expression === null) {···
return;
}
✓ Negative was executed (else)
}···

var operatorToken = file.findPrevOperatorToken(
if (expression === null) {
return;
}
var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);
var nextToken = file.getNextToken(operatorToken);
Branch IfStatement
✓ Positive was executed (if)
if (operators[operator]) {···
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should stick to following expression'
});
}
✓ Negative was executed (else)
}···
}
if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should stick to following expression'
});
}
}
);
}
};
disallow-space-after-comma.js
/**
* Disallows spaces after commas
*
* Types: `Boolean` or `Object`
*
* Values:
* - `Boolean`: `true` to disallow any spaces after any comma
* - `Object`: `"allExcept"` array of exceptions
* - `"sparseArrays"` to allow spaces in place of absent values in sparse arrays
*
* #### Example
*
* ```js
* "disallowSpaceAfterComma": true
* ```
* ```js
* "disallowSpaceAfterComma" {"allExcept": ["sparseArrays"]}
* ```
*
* ##### Valid for mode `true`
*
* ```js
* [a,b,c];
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* [a, b, c];
* ```
* ```js
* [a,b, , ,c];
* ```
*
* ##### Valid for mode `{"allExcept": ["sparseArrays"]}`
*
* ```js
* [a,b, , ,c];
* ```
*
* ##### Invalid for mode `{"allExcept": ["sparseArrays"]}`
*
* ```js
* [a, b, , , c];
* ``
*/
var assert = require('assert');
Function (anonymous_529)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_530)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}

assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptSparseArrays = options.allExcept.indexOf('sparseArrays') >= 0;
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptSparseArrays = options.allExcept.indexOf('sparseArrays') >= 0;
},
Function (anonymous_531)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterComma';
},
getOptionName: function() {
return 'disallowSpaceAfterComma';
},
Function (anonymous_532)
✓ Was called
check: function(file, errors) {···
var exceptSparseArrays = this._exceptSparseArrays;
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var nextToken = file.getNextToken(token);

if (exceptSparseArrays && nextToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after comma'
});
});
}
check: function(file, errors) {
var exceptSparseArrays = this._exceptSparseArrays;
Function (anonymous_533)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
var nextToken = file.getNextToken(token);

if (exceptSparseArrays && nextToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after comma'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var nextToken = file.getNextToken(token);
Branch IfStatement
✓ Positive was executed (if)
if (exceptSparseArrays && nextToken.value === ',') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (exceptSparseArrays && nextToken.value === ',') {
✓ Was returned
if (exceptSparseArrays && nextToken.value === ',') {
if (exceptSparseArrays && nextToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after comma'
});
});
}
};
disallow-space-after-keywords.js
/**
* Disallows space after keyword.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to disallow spaces after all possible keywords.
*
* #### Example
*
* ```js
* "disallowSpaceAfterKeywords": [
* "if",
* "else",
* "for",
* "while",
* "do",
* "switch",
* "try",
* "catch"
* ]
* ```
*
* ##### Valid
*
* ```js
* if(x > y) {
* y++;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (x > y) {
* y++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
Function (anonymous_534)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_535)
✓ Was called
configure: function(keywords) {···
assert(
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value'
);

if (keywords === true) {
keywords = defaultKeywords;
}

this._keywords = keywords;
},
configure: function(keywords) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || keywords === true,
✓ Was returned
Array.isArray(keywords) || keywords === true,
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (keywords === true) {···
keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
Function (anonymous_536)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterKeywords';
},
getOptionName: function() {
return 'disallowSpaceAfterKeywords';
},
Function (anonymous_537)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var nextToken = file.getNextToken(token);

// Make an exception if the next token is not a Punctuator such as a Keyword or Identifier
if (nextToken.type !== 'Punctuator') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken
});
});
}
check: function(file, errors) {
Function (anonymous_538)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var nextToken = file.getNextToken(token);

// Make an exception if the next token is not a Punctuator such as a Keyword or Identifier
if (nextToken.type !== 'Punctuator') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken
});
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var nextToken = file.getNextToken(token);
// Make an exception if the next token is not a Punctuator such as a Keyword or Identifier
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type !== 'Punctuator') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
if (nextToken.type !== 'Punctuator') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken
});
});
}
};
disallow-space-after-line-comment.js
/**
* Requires that a line comment (`//`) not be followed by a space.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpaceAfterLineComment": true
* ```
*
* ##### Valid
*
* ```js
* //A comment
* /* A comment*\/
* ```
*
* ##### Invalid
*
* ```js
* // A comment
* ```
*/
var assert = require('assert');
Function (anonymous_539)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_540)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_541)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterLineComment';
},
getOptionName: function() {
return 'disallowSpaceAfterLineComment';
},
Function (anonymous_542)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByType('CommentLine', function(comment) {
var value = comment.value;
if (value.length > 0 && value[0] === ' ') {
errors.add('Illegal space after line comment', comment);
}
});
}
check: function(file, errors) {
Function (anonymous_543)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
var value = comment.value;
if (value.length > 0 && value[0] === ' ') {
errors.add('Illegal space after line comment', comment);
}
});
file.iterateTokensByType('CommentLine', function(comment) {
var value = comment.value;
Branch IfStatement
✓ Positive was executed (if)
if (value.length > 0 && value[0] === ' ') {···
errors.add('Illegal space after line comment', comment);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (value.length > 0 && value[0] === ' ') {
✓ Was returned
if (value.length > 0 && value[0] === ' ') {
if (value.length > 0 && value[0] === ' ') {
errors.add('Illegal space after line comment', comment);
}
});
}
};
disallow-space-after-object-keys.js
/**
* Disallows space after object keys.
*
* Types: `Boolean`, `String`, or `Object`
*
* Values:
* - `true`
* - `"ignoreSingleLine"` ignores objects if the object only takes up a single line
* (*deprecated* use `"allExcept": [ "singleline" ]`)
* - `"ignoreMultiLine"` ignores objects if the object takes up multiple lines
* (*deprecated* use `"allExcept": [ "multiline" ]`)
* - `Object`:
* - `"allExcept"`: array of exceptions:
* - `"singleline"` ignores objects if the object only takes up a single line
* - `"multiline"` ignores objects if the object takes up multiple lines
* - `"aligned"` ignores aligned object properties
* - `"method"` ignores method declarations
*
* #### Example
*
* ```js
* "disallowSpaceAfterObjectKeys": true
* ```
*
* ##### Valid for `true`
* ```js
* var x = {a: 1};
* var y = {
* a: 1,
* b: 2
* }
* ```
*
* ##### Valid for `{ allExcept: ['singleline'] }`
* ```js
* var x = {a : 1};
* var y = {
* a: 1,
* b: 2
* }
* ```
*
* ##### Valid for `{ allExcept: ['multiline'] }`
* ```js
* var x = {a: 1};
* var y = {
* a : 1,
* b : 2
* }
* ```
*
* ##### Valid for `{ allExcept: ['aligned'] }`
* ```js
* var y = {
* abc: 1,
* d : 2
* }
* ```
*
* ##### Valid for `{ allExcept: ['method'] }`
* ```js
* var y = {
* fn () {
* return 42;
* }
* }
* ```
*
* ##### Invalid
* ```js
* var x = {a : 1};
* ```
*/
var assert = require('assert');
Function (anonymous_544)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_545)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true ||
options === 'ignoreSingleLine' ||
options === 'ignoreMultiLine',
this.getOptionName() +
' option requires a true value, "ignoreSingleLine", "ignoreMultiLine", or an object'
);

var _options = {
allExcept: []
};

if (options === 'ignoreSingleLine') {
_options.allExcept.push('singleline');
}
if (options === 'ignoreMultiLine') {
_options.allExcept.push('multiline');
}

return this.configure(_options);
} else {
assert(
Array.isArray(options.allExcept),
this.getOptionName() +
' option object requires allExcept array property'
);
}

this._exceptSingleline = options.allExcept.indexOf('singleline') > -1;
this._exceptMultiline = options.allExcept.indexOf('multiline') > -1;
this._exceptAligned = options.allExcept.indexOf('aligned') > -1;
this._exceptMethod = options.allExcept.indexOf('method') > -1;
assert(
!this._exceptMultiline || !this._exceptAligned,
this.getOptionName() +
' option allExcept property cannot contain `aligned` and `multiline` at the same time'
);
assert(
!this._exceptMultiline || !this._exceptSingleline,
this.getOptionName() +
' option allExcept property cannot contain `singleline` and `multiline` at the same time'
);
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true ||
options === 'ignoreSingleLine' ||
options === 'ignoreMultiLine',
this.getOptionName() +
' option requires a true value, "ignoreSingleLine", "ignoreMultiLine", or an object'
);

var _options = {
allExcept: []
};

if (options === 'ignoreSingleLine') {
_options.allExcept.push('singleline');
}
if (options === 'ignoreMultiLine') {
_options.allExcept.push('multiline');
}

return this.configure(_options);
} else {
✓ Negative was executed (else)
} else {···
assert(
Array.isArray(options.allExcept),
this.getOptionName() +
' option object requires allExcept array property'
);
}
if (typeof options !== 'object') {
assert(
Branch LogicalExpression
✓ Was returned
options === 'ignoreMultiLine',
✓ Was returned
options === true ||···
options === 'ignoreSingleLine' ||
Branch LogicalExpression
✓ Was returned
options === 'ignoreSingleLine' ||
✓ Was returned
options === true ||
options === true ||
options === 'ignoreSingleLine' ||
options === 'ignoreMultiLine',
this.getOptionName() +
' option requires a true value, "ignoreSingleLine", "ignoreMultiLine", or an object'
);
var _options = {
allExcept: []
};
Branch IfStatement
✓ Positive was executed (if)
if (options === 'ignoreSingleLine') {···
_options.allExcept.push('singleline');
}
✓ Negative was executed (else)
}···
if (options === 'ignoreMultiLine') {
if (options === 'ignoreSingleLine') {
_options.allExcept.push('singleline');
}
Branch IfStatement
✓ Positive was executed (if)
if (options === 'ignoreMultiLine') {···
_options.allExcept.push('multiline');
}
✓ Negative was executed (else)
}···

return this.configure(_options);
if (options === 'ignoreMultiLine') {
_options.allExcept.push('multiline');
}
return this.configure(_options);
} else {
assert(
Array.isArray(options.allExcept),
this.getOptionName() +
' option object requires allExcept array property'
);
}
this._exceptSingleline = options.allExcept.indexOf('singleline') > -1;
this._exceptMultiline = options.allExcept.indexOf('multiline') > -1;
this._exceptAligned = options.allExcept.indexOf('aligned') > -1;
this._exceptMethod = options.allExcept.indexOf('method') > -1;
assert(
Branch LogicalExpression
✓ Was returned
!this._exceptMultiline || !this._exceptAligned,
✓ Was returned
!this._exceptMultiline || !this._exceptAligned,
!this._exceptMultiline || !this._exceptAligned,
this.getOptionName() +
' option allExcept property cannot contain `aligned` and `multiline` at the same time'
);
assert(
Branch LogicalExpression
✓ Was returned
!this._exceptMultiline || !this._exceptSingleline,
✓ Was returned
!this._exceptMultiline || !this._exceptSingleline,
!this._exceptMultiline || !this._exceptSingleline,
this.getOptionName() +
' option allExcept property cannot contain `singleline` and `multiline` at the same time'
);
},
Function (anonymous_546)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterObjectKeys';
},
getOptionName: function() {
return 'disallowSpaceAfterObjectKeys';
},
Function (anonymous_547)
✓ Was called
check: function(file, errors) {···
var exceptSingleline = this._exceptSingleline;
var exceptMultiline = this._exceptMultiline;
var exceptAligned = this._exceptAligned;
var exceptMethod = this._exceptMethod;

file.iterateNodesByType('ObjectExpression', function(node) {
var multiline = node.getNewlineCount() > 0;
if (exceptSingleline && !multiline) {
return;
}
if (exceptMultiline && multiline) {
return;
}

var maxKeyEndPos = 0;
var tokens = [];
node.properties.forEach(function(property) {
if (property.shorthand ||
(exceptMethod && property.method) ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getLastNodeToken(property.key);
if (property.computed === true) {
keyToken = file.getNextToken(keyToken);
}

if (exceptAligned) {
maxKeyEndPos = Math.max(maxKeyEndPos, keyToken.getLoc().end.column);
}
tokens.push(keyToken);
});

var noSpace = true;
if (exceptAligned) {
var withoutSpace = 0;
var alignedOnColon = 0;
tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = file.getDistanceBetween(key, colon);
if (spaces === 0) {
withoutSpace++;
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
alignedOnColon++;
}
});

noSpace = withoutSpace > alignedOnColon;
}

tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
errors.assert.spacesBetween({
token: key,
nextToken: colon,
exactly: spaces,
message: 'Illegal space after key',
disallowNewLine: true
});
});
});
}
check: function(file, errors) {
var exceptSingleline = this._exceptSingleline;
var exceptMultiline = this._exceptMultiline;
var exceptAligned = this._exceptAligned;
var exceptMethod = this._exceptMethod;
Function (anonymous_548)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var multiline = node.getNewlineCount() > 0;
if (exceptSingleline && !multiline) {
return;
}
if (exceptMultiline && multiline) {
return;
}

var maxKeyEndPos = 0;
var tokens = [];
node.properties.forEach(function(property) {
if (property.shorthand ||
(exceptMethod && property.method) ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getLastNodeToken(property.key);
if (property.computed === true) {
keyToken = file.getNextToken(keyToken);
}

if (exceptAligned) {
maxKeyEndPos = Math.max(maxKeyEndPos, keyToken.getLoc().end.column);
}
tokens.push(keyToken);
});

var noSpace = true;
if (exceptAligned) {
var withoutSpace = 0;
var alignedOnColon = 0;
tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = file.getDistanceBetween(key, colon);
if (spaces === 0) {
withoutSpace++;
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
alignedOnColon++;
}
});

noSpace = withoutSpace > alignedOnColon;
}

tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
errors.assert.spacesBetween({
token: key,
nextToken: colon,
exactly: spaces,
message: 'Illegal space after key',
disallowNewLine: true
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
var multiline = node.getNewlineCount() > 0;
Branch IfStatement
✓ Positive was executed (if)
if (exceptSingleline && !multiline) {···
return;
}
✓ Negative was executed (else)
}···
if (exceptMultiline && multiline) {
Branch LogicalExpression
✓ Was returned
if (exceptSingleline && !multiline) {
✓ Was returned
if (exceptSingleline && !multiline) {
if (exceptSingleline && !multiline) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (exceptMultiline && multiline) {···
return;
}
✓ Negative was executed (else)
}···

var maxKeyEndPos = 0;
Branch LogicalExpression
✓ Was returned
if (exceptMultiline && multiline) {
✓ Was returned
if (exceptMultiline && multiline) {
if (exceptMultiline && multiline) {
return;
}
var maxKeyEndPos = 0;
var tokens = [];
Function (anonymous_549)
✓ Was called
node.properties.forEach(function(property) {···
if (property.shorthand ||
(exceptMethod && property.method) ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getLastNodeToken(property.key);
if (property.computed === true) {
keyToken = file.getNextToken(keyToken);
}

if (exceptAligned) {
maxKeyEndPos = Math.max(maxKeyEndPos, keyToken.getLoc().end.column);
}
tokens.push(keyToken);
});
node.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
property.type === 'SpreadProperty') {···
return;
}
✓ Negative was executed (else)
}···

var keyToken = file.getLastNodeToken(property.key);
Branch LogicalExpression
✓ Was returned
property.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand ||···
(exceptMethod && property.method) ||
Branch LogicalExpression
✓ Was returned
(exceptMethod && property.method) ||
✓ Was returned
if (property.shorthand ||
if (property.shorthand ||
Branch LogicalExpression
✓ Was returned
(exceptMethod && property.method) ||
✓ Was returned
(exceptMethod && property.method) ||
(exceptMethod && property.method) ||
property.type === 'SpreadProperty') {
return;
}
var keyToken = file.getLastNodeToken(property.key);
Branch IfStatement
✓ Positive was executed (if)
if (property.computed === true) {···
keyToken = file.getNextToken(keyToken);
}
✓ Negative was executed (else)
}···

if (exceptAligned) {
if (property.computed === true) {
keyToken = file.getNextToken(keyToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (exceptAligned) {···
maxKeyEndPos = Math.max(maxKeyEndPos, keyToken.getLoc().end.column);
}
✓ Negative was executed (else)
}···
tokens.push(keyToken);
if (exceptAligned) {
maxKeyEndPos = Math.max(maxKeyEndPos, keyToken.getLoc().end.column);
}
tokens.push(keyToken);
});
var noSpace = true;
Branch IfStatement
✓ Positive was executed (if)
if (exceptAligned) {···
var withoutSpace = 0;
var alignedOnColon = 0;
tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = file.getDistanceBetween(key, colon);
if (spaces === 0) {
withoutSpace++;
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
alignedOnColon++;
}
});

noSpace = withoutSpace > alignedOnColon;
}
✓ Negative was executed (else)
}···

tokens.forEach(function(key) {
if (exceptAligned) {
var withoutSpace = 0;
var alignedOnColon = 0;
Function (anonymous_550)
✓ Was called
tokens.forEach(function(key) {···
var colon = file.getNextToken(key);
var spaces = file.getDistanceBetween(key, colon);
if (spaces === 0) {
withoutSpace++;
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
alignedOnColon++;
}
});
tokens.forEach(function(key) {
var colon = file.getNextToken(key);
var spaces = file.getDistanceBetween(key, colon);
Branch IfStatement
✓ Positive was executed (if)
if (spaces === 0) {···
withoutSpace++;
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
✓ Negative was executed (else)
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {···
alignedOnColon++;
}
if (spaces === 0) {
withoutSpace++;
Branch IfStatement
✓ Positive was executed (if)
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {···
alignedOnColon++;
}
✓ Negative was executed (else)
}···
});
} else if (spaces === maxKeyEndPos - key.getLoc().end.column) {
alignedOnColon++;
}
});
noSpace = withoutSpace > alignedOnColon;
}
Function (anonymous_551)
✓ Was called
tokens.forEach(function(key) {···
var colon = file.getNextToken(key);
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
errors.assert.spacesBetween({
token: key,
nextToken: colon,
exactly: spaces,
message: 'Illegal space after key',
disallowNewLine: true
});
});
tokens.forEach(function(key) {
var colon = file.getNextToken(key);
Branch ConditionalExpression
✓ Positive was returned (? ...)
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
✓ Negative was returned (: ...)
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
Branch LogicalExpression
✓ Was returned
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
✓ Was returned
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
var spaces = (exceptAligned && !noSpace) ? maxKeyEndPos - key.getLoc().end.column : 0;
errors.assert.spacesBetween({
token: key,
nextToken: colon,
exactly: spaces,
message: 'Illegal space after key',
disallowNewLine: true
});
});
});
}
};
disallow-space-after-prefix-unary-operators.js
/**
* Requires sticking unary operators to the right.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to disallow space after prefix for all unary operators
*
* #### Example
*
* ```js
* "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"]
* ```
*
* ##### Valid
*
* ```js
* x = !y; y = ++z;
* ```
*
* ##### Invalid
*
* ```js
* x = ! y; y = ++ z;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').unaryOperators;
Function (anonymous_552)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_553)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = defaultOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = defaultOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_554)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceAfterPrefixUnaryOperators';
},
getOptionName: function() {
return 'disallowSpaceAfterPrefixUnaryOperators';
},
Function (anonymous_555)
✓ Was called
check: function(file, errors) {···
var operatorIndex = this._operatorIndex;

file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {
// Check "node.prefix" for prefix type of (inc|dec)rement
if (node.prefix && operatorIndex[node.operator]) {
var operatorToken = node.getFirstToken();
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: file.getNextToken(operatorToken),
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
}
check: function(file, errors) {
var operatorIndex = this._operatorIndex;
Function (anonymous_556)
✓ Was called
file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {···
// Check "node.prefix" for prefix type of (inc|dec)rement
if (node.prefix && operatorIndex[node.operator]) {
var operatorToken = node.getFirstToken();
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: file.getNextToken(operatorToken),
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {
// Check "node.prefix" for prefix type of (inc|dec)rement
Branch IfStatement
✓ Positive was executed (if)
if (node.prefix && operatorIndex[node.operator]) {···
var operatorToken = node.getFirstToken();
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: file.getNextToken(operatorToken),
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (node.prefix && operatorIndex[node.operator]) {
✓ Was returned
if (node.prefix && operatorIndex[node.operator]) {
if (node.prefix && operatorIndex[node.operator]) {
var operatorToken = node.getFirstToken();
errors.assert.noWhitespaceBetween({
token: operatorToken,
nextToken: file.getNextToken(operatorToken),
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
}
};
disallow-space-before-binary-operators.js
/**
* Requires sticking binary operators to the left.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to disallow space before all possible binary operators
*
* #### Example
*
* ```js
* "disallowSpaceBeforeBinaryOperators": [
* "=",
* ",",
* "+",
* "-",
* "/",
* "*",
* "==",
* "===",
* "!=",
* "!=="
* // etc
* ]
* ```
*
* ##### Valid
*
* ```js
* x+ y;
* ```
*
* ##### Invalid
*
* ```js
* x + y;
* ```
*/
var assert = require('assert');
var allOperators = require('../utils').binaryOperators;
Function (anonymous_557)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_558)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = allOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = allOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = allOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_559)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeBinaryOperators';
},
getOptionName: function() {
return 'disallowSpaceBeforeBinaryOperators';
},
Function (anonymous_560)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;

// Comma
if (operators[',']) {
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
if (file.getPrevToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(token, {includeComments: true}),
nextToken: token,
message: 'Operator , should stick to previous expression'
});
});
}

// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
function(node) {
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var prevToken = file.getPrevToken(operatorToken, {includeComments: true});

if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to previous expression'
});
}
}
);
}
check: function(file, errors) {
var operators = this._operatorIndex;
// Comma
Branch IfStatement
✓ Positive was executed (if)
if (operators[',']) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
if (file.getPrevToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(token, {includeComments: true}),
nextToken: token,
message: 'Operator , should stick to previous expression'
});
});
}
✓ Negative was executed (else)
}···

// For everything else
if (operators[',']) {
Function (anonymous_561)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
if (file.getPrevToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(token, {includeComments: true}),
nextToken: token,
message: 'Operator , should stick to previous expression'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
Branch IfStatement
✓ Positive was executed (if)
if (file.getPrevToken(token).value === ',') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
if (file.getPrevToken(token).value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(token, {includeComments: true}),
nextToken: token,
message: 'Operator , should stick to previous expression'
});
});
}
// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
Function (anonymous_562)
✓ Was called
function(node) {···
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var prevToken = file.getPrevToken(operatorToken, {includeComments: true});

if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to previous expression'
});
}
}
function(node) {
var operator;
var expression;
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclarator') {···
expression = node.init;
operator = '=';
} else {
✓ Negative was executed (else)
} else {···
operator = node.operator;
expression = node.right;
}
if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}
Branch IfStatement
✓ Positive was executed (if)
if (expression === null) {···
return;
}
✓ Negative was executed (else)
}···

var operatorToken = file.findPrevOperatorToken(
if (expression === null) {
return;
}
var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);
var prevToken = file.getPrevToken(operatorToken, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (operators[operator]) {···
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to previous expression'
});
}
✓ Negative was executed (else)
}···
}
if (operators[operator]) {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to previous expression'
});
}
}
);
}
};
disallow-space-before-block-statements.js
/**
* Disallows space before block statements (for loops, control structures).
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpaceBeforeBlockStatements": true
* ```
*
* ##### Valid
*
* ```js
* if (cond){
* foo();
* } else{
* bar();
* }
*
* for (var e in elements){
* bar(e);
* }
*
* while (cond){
* foo();
* }
* ```
*
* ##### Invalid
*
* ```js
* if (cond) {
* foo();
* } else {
* bar();
* }
*
* for (var e in elements) {
* bar(e);
* }
*
* while (cond) {
* foo();
* }
* ```
*/
var assert = require('assert');
Function (anonymous_563)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_564)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_565)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeBlockStatements';
},
getOptionName: function() {
return 'disallowSpaceBeforeBlockStatements';
},
Function (anonymous_566)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('BlockStatement', function(node) {
if (isBareBlock(node)) {
return;
}
var first = node.getFirstToken();

errors.assert.noWhitespaceBetween({
token: file.getPrevToken(first),
nextToken: first,
disallowNewLine: true,
message: 'Extra space before opening curly brace for block expressions'
});
});
}
check: function(file, errors) {
Function (anonymous_567)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
if (isBareBlock(node)) {
return;
}
var first = node.getFirstToken();

errors.assert.noWhitespaceBetween({
token: file.getPrevToken(first),
nextToken: first,
disallowNewLine: true,
message: 'Extra space before opening curly brace for block expressions'
});
});
file.iterateNodesByType('BlockStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isBareBlock(node)) {···
return;
}
✓ Negative was executed (else)
}···
var first = node.getFirstToken();
if (isBareBlock(node)) {
return;
}
var first = node.getFirstToken();
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(first),
nextToken: first,
disallowNewLine: true,
message: 'Extra space before opening curly brace for block expressions'
});
});
}
};
Function isBareBlock
✓ Was called
function isBareBlock(node) {···
var parentElement = node.parentElement;

return parentElement &&
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
}
function isBareBlock(node) {
var parentElement = node.parentElement;
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
return parentElement &&···
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
Branch LogicalExpression
✓ Was returned
parentElement.type === 'Program' ||
✓ Was returned
return parentElement &&···
parentElement.type === 'BlockStatement' ||
Branch LogicalExpression
✓ Was returned
parentElement.type === 'BlockStatement' ||
✗ Was not returned
return parentElement &&
return parentElement &&
parentElement.type === 'BlockStatement' ||
parentElement.type === 'Program' ||
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
Branch LogicalExpression
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
✓ Was returned
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
parentElement.body && parentElement.body.type === 'BlockStatement' && Array.isArray(parentElement.body);
}
disallow-space-before-comma.js
/**
* Disallows spaces before commas
*
* Types: `Boolean` or `Object`
*
* Values:
* - `Boolean`: `true` to disallow any spaces before any comma
* - `Object`: `"allExcept"` array of exceptions
* - `"sparseArrays"` to allow spaces in place of absent values in sparse arrays
*
* #### Example
*
* ```js
* "disallowSpaceBeforeComma": true
* ```
* ```js
* "disallowSpaceBeforeComma": {"allExcept": ["sparseArrays"]}
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var a, b;
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* var a ,b;
* ```
* ```js
* [a, b, , , c]
* ```
* ##### Valid for mode `{"allExcept": ["sparseArrays"]}`
*
* ```js
* [a, b, , , c]
* ```
*
* ##### Invalid for mode `{"allExcept": ["sparseArrays"]}`
*
* ```js
* [a , b , , , c]
* ```
*
*/
var assert = require('assert');
Function (anonymous_569)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_570)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}

assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptSparseArrays = options.allExcept.indexOf('sparseArrays') >= 0;
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptSparseArrays = options.allExcept.indexOf('sparseArrays') >= 0;
},
Function (anonymous_571)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeComma';
},
getOptionName: function() {
return 'disallowSpaceBeforeComma';
},
Function (anonymous_572)
✓ Was called
check: function(file, errors) {···
var exceptSparseArrays = this._exceptSparseArrays;
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();

if (exceptSparseArrays && prevToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before comma'
});
});
}
check: function(file, errors) {
var exceptSparseArrays = this._exceptSparseArrays;
Function (anonymous_573)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
var prevToken = token.getPreviousCodeToken();

if (exceptSparseArrays && prevToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before comma'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (exceptSparseArrays && prevToken.value === ',') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (exceptSparseArrays && prevToken.value === ',') {
✓ Was returned
if (exceptSparseArrays && prevToken.value === ',') {
if (exceptSparseArrays && prevToken.value === ',') {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before comma'
});
});
}
};
disallow-space-before-keywords.js
/**
* Disallows space before keyword.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to disallow spaces before all possible keywords.
*
* #### Example
*
* ```js
* "disallowSpaceBeforeKeywords": [
* "else",
* "catch"
* ]
* ```
*
* ##### Valid
*
* ```js
* }else {
* y--;
* }
* ```
*
* ##### Invalid
*
* ```js
* } else {
* y--;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
Function (anonymous_574)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_575)
✓ Was called
configure: function(keywords) {···
assert(
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');

if (keywords === true) {
keywords = defaultKeywords;
}

this._keywords = keywords;
},
configure: function(keywords) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || keywords === true,
✓ Was returned
Array.isArray(keywords) || keywords === true,
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');
Branch IfStatement
✓ Positive was executed (if)
if (keywords === true) {···
keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
Function (anonymous_576)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeKeywords';
},
getOptionName: function() {
return 'disallowSpaceBeforeKeywords';
},
Function (anonymous_577)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
if (!prevToken || prevToken.isComment) {
return;
}

if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before "' + token.value + '" keyword'
});
}
});
}
check: function(file, errors) {
Function (anonymous_578)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
if (!prevToken || prevToken.isComment) {
return;
}

if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before "' + token.value + '" keyword'
});
}
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken || prevToken.isComment) {···
return;
}
✓ Negative was executed (else)
}···

if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
Branch LogicalExpression
✓ Was returned
if (!prevToken || prevToken.isComment) {
✓ Was returned
if (!prevToken || prevToken.isComment) {
if (!prevToken || prevToken.isComment) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {···
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before "' + token.value + '" keyword'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
✓ Was returned
if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
if (prevToken.type !== 'Keyword' && prevToken.value !== ';') {
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before "' + token.value + '" keyword'
});
}
});
}
};
disallow-space-before-object-values.js
/**
* Disallows space before object values.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpaceBeforeObjectValues": true
* ```
*
* ##### Valid
* ```js
* var x = {a:1};
* ```
* ##### Invalid
* ```js
* var x = {a: 1};
* ```
*/
var assert = require('assert');
Function (anonymous_579)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_580)
✓ Was called
configure: function(disallow) {···
assert(
disallow === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(disallow) {
assert(
disallow === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_581)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeObjectValues';
},
getOptionName: function() {
return 'disallowSpaceBeforeObjectValues';
},
Function (anonymous_582)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(property) {
if (property.shorthand ||
property.type === 'ObjectMethod' ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.noWhitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Illegal space after key colon'
});
});
});
}
check: function(file, errors) {
Function (anonymous_583)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
node.properties.forEach(function(property) {
if (property.shorthand ||
property.type === 'ObjectMethod' ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.noWhitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Illegal space after key colon'
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_584)
✓ Was called
node.properties.forEach(function(property) {···
if (property.shorthand ||
property.type === 'ObjectMethod' ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.noWhitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Illegal space after key colon'
});
});
node.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
property.type === 'SpreadProperty') {···
return;
}
✓ Negative was executed (else)
}···

var keyToken = file.getFirstNodeToken(property.key);
Branch LogicalExpression
✓ Was returned
property.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand ||···
property.type === 'ObjectMethod' ||
Branch LogicalExpression
✓ Was returned
property.type === 'ObjectMethod' ||
✓ Was returned
if (property.shorthand ||
if (property.shorthand ||
property.type === 'ObjectMethod' ||
property.type === 'SpreadProperty') {
return;
}
var keyToken = file.getFirstNodeToken(property.key);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');
errors.assert.noWhitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Illegal space after key colon'
});
});
});
}
};
disallow-space-before-postfix-unary-operators.js
/**
* Requires sticking unary operators to the left.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to disallow space before postfix for all unary operators
* (i.e. increment/decrement operators)
*
* #### Example
*
* ```js
* "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"]
* ```
*
* ##### Valid
*
* ```js
* x = y++; y = z--;
* ```
*
* ##### Invalid
*
* ```js
* x = y ++; y = z --;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').incrementAndDecrementOperators;
Function (anonymous_585)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_586)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = defaultOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = defaultOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_587)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforePostfixUnaryOperators';
},
getOptionName: function() {
return 'disallowSpaceBeforePostfixUnaryOperators';
},
Function (anonymous_588)
✓ Was called
check: function(file, errors) {···
var operatorIndex = this._operatorIndex;

// 'UpdateExpression' involve only ++ and -- operators
file.iterateNodesByType('UpdateExpression', function(node) {
// "!node.prefix" means postfix type of (inc|dec)rement
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
}
check: function(file, errors) {
var operatorIndex = this._operatorIndex;
// 'UpdateExpression' involve only ++ and -- operators
Function (anonymous_589)
✓ Was called
file.iterateNodesByType('UpdateExpression', function(node) {···
// "!node.prefix" means postfix type of (inc|dec)rement
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
file.iterateNodesByType('UpdateExpression', function(node) {
// "!node.prefix" means postfix type of (inc|dec)rement
Branch IfStatement
✓ Positive was executed (if)
if (!node.prefix && operatorIndex[node.operator]) {···
var operatorToken = file.getLastNodeToken(node);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (!node.prefix && operatorIndex[node.operator]) {
✓ Was returned
if (!node.prefix && operatorIndex[node.operator]) {
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should stick to operand'
});
}
});
}
};
disallow-space-before-semicolon.js
/**
* Disallows spaces before semicolons.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true` to disallow any spaces before any semicolon.
* - `Object`:
* - `"allExcept"`: `[ "(" ]` list of tokens that can occur after semicolon
*
* #### Example
*
* ```js
* "disallowSpaceBeforeSemicolon": true
* ```
*
* ##### Valid
*
* ```js
* var a = 1;
* ```
*
* * ##### Valid for mode `{ "allExcept": [ "(" ] }`
*
* ```js
* for ( ; nodeIndex < nodesCount; ++nodeIndex ) {}
* ```
*
* ##### Invalid
*
* ```js
* var a = 1 ;
* ```
*/
var assert = require('assert');
Function (anonymous_590)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_591)
✓ Was called
configure: function(value) {···
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule requires string value true or object';

if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
configure: function(value) {
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule requires string value true or object';
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true, error);
}
if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (isObject) {
Function (anonymous_592)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
Function (anonymous_593)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBeforeSemicolon';
},
getOptionName: function() {
return 'disallowSpaceBeforeSemicolon';
},
Function (anonymous_594)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {
var prevToken = token.getPreviousCodeToken();

if (!prevToken || prevToken.value in exceptions) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before semicolon'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_595)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {···
var prevToken = token.getPreviousCodeToken();

if (!prevToken || prevToken.value in exceptions) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before semicolon'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ';', function(token) {
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken || prevToken.value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (!prevToken || prevToken.value in exceptions) {
✓ Was returned
if (!prevToken || prevToken.value in exceptions) {
if (!prevToken || prevToken.value in exceptions) {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before semicolon'
});
});
}
};
disallow-space-between-arguments.js
/**
* Ensure there are no spaces after argument separators in call expressions.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpaceBetweenArguments": true
* ```
*
* ##### Valid
*
* ```js
* a(b,c);
* ```
*
* ##### Invalid
*
* ```js
* a(b, c);
* ```
*/
var assert = require('assert');
Function (anonymous_596)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_597)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_598)
✓ Was called
getOptionName: function() {···
return 'disallowSpaceBetweenArguments';
},
getOptionName: function() {
return 'disallowSpaceBetweenArguments';
},
Function (anonymous_599)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['CallExpression'], function(node) {
node.arguments.forEach(function(param) {
var token = file.getFirstNodeToken(param);
var punctuatorToken = file.getPrevToken(token);

if (punctuatorToken.value === ',') {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken),
message: 'Illegal space between arguments'
});
}
});
});
}
check: function(file, errors) {
Function (anonymous_600)
✓ Was called
file.iterateNodesByType(['CallExpression'], function(node) {···
node.arguments.forEach(function(param) {
var token = file.getFirstNodeToken(param);
var punctuatorToken = file.getPrevToken(token);

if (punctuatorToken.value === ',') {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken),
message: 'Illegal space between arguments'
});
}
});
});
file.iterateNodesByType(['CallExpression'], function(node) {
Function (anonymous_601)
✓ Was called
node.arguments.forEach(function(param) {···
var token = file.getFirstNodeToken(param);
var punctuatorToken = file.getPrevToken(token);

if (punctuatorToken.value === ',') {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken),
message: 'Illegal space between arguments'
});
}
});
node.arguments.forEach(function(param) {
var token = file.getFirstNodeToken(param);
var punctuatorToken = file.getPrevToken(token);
Branch IfStatement
✓ Positive was executed (if)
if (punctuatorToken.value === ',') {···
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken),
message: 'Illegal space between arguments'
});
}
✓ Negative was executed (else)
}···
});
if (punctuatorToken.value === ',') {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken),
message: 'Illegal space between arguments'
});
}
});
});
}
};
disallow-spaces-in-anonymous-function-expression.js
/**
* Disallows space before `()` or `{}` in anonymous function expressions.
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "disallowSpacesInAnonymousFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var foo = function(){};
* var Foo = {
* foo: function(){}
* }
* array.map(function(){});
* ```
*
* ##### Invalid
*
* ```js
* var foo = function () {};
* var Foo = {
* foo: function (){}
* }
* array.map(function() {});
* ```
*/
var assert = require('assert');
Function (anonymous_602)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_603)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
' or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
' or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_604)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInAnonymousFunctionExpression';
},
getOptionName: function() {
return 'disallowSpacesInAnonymousFunctionExpression';
},
Function (anonymous_605)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node;

// anonymous function expressions only
if (node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}

errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_606)
✓ Was called
file.iterateNodesByType(['FunctionExpression'], function(node) {···
var functionNode = node;

// anonymous function expressions only
if (node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}

errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node;
// anonymous function expressions only
Branch IfStatement
✓ Positive was executed (if)
if (node.id) {···
return;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
if (node.id) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}

errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✗ Was not returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
};
disallow-spaces-in-call-expression.js
/**
* Disallows space before `()` in call expressions.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpacesInCallExpression": true
* ```
*
* ##### Valid
*
* ```js
* var x = foobar();
* ```
*
* ##### Invalid
*
* ```js
* var x = foobar ();
* ```
*/
var assert = require('assert');
Function (anonymous_607)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_608)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_609)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInCallExpression';
},
getOptionName: function() {
return 'disallowSpacesInCallExpression';
},
Function (anonymous_610)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['CallExpression', 'NewExpression'], function(node) {
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');

// CallExpressions can't have missing parens, otherwise they're identifiers
if (node.type === 'NewExpression') {
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
return;
}
}

errors.assert.noWhitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Illegal space before opening round brace'
});
});
}
check: function(file, errors) {
Function (anonymous_611)
✓ Was called
file.iterateNodesByType(['CallExpression', 'NewExpression'], function(node) {···
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');

// CallExpressions can't have missing parens, otherwise they're identifiers
if (node.type === 'NewExpression') {
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
return;
}
}

errors.assert.noWhitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Illegal space before opening round brace'
});
});
file.iterateNodesByType(['CallExpression', 'NewExpression'], function(node) {
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');
// CallExpressions can't have missing parens, otherwise they're identifiers
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'NewExpression') {···
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
return;
}
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (node.type === 'NewExpression') {
Branch IfStatement
✓ Positive was executed (if)
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
✓ Was returned
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
if (roundBraceToken === null || roundBraceToken.parentElement !== node) {
return;
}
}
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Illegal space before opening round brace'
});
});
}
};
disallow-spaces-in-conditional-expression.js
/**
* Disallows space before and/or after `?` or `:` in conditional expressions.
*
* Types: `Object` or `Boolean`
*
* Values: `"afterTest"`, `"beforeConsequent"`, `"afterConsequent"`, `"beforeAlternate"` as child properties,
* or `true` to set all properties to true. Child properties must be set to `true`. These token names correspond to:
*
* ```
* var a = b ? c : d;
* ^ ^ ^ ^
* | | | |
* | | | └- beforeAlternate
* | | └--- afterConsequent
* | └-------- beforeConsequent
* └---------- afterTest
* ```
*
* #### Example
*
* ```js
* "disallowSpacesInConditionalExpression": {
* "afterTest": true,
* "beforeConsequent": true,
* "afterConsequent": true,
* "beforeAlternate": true
* }
* ```
*
* ##### Valid
*
* ```js
* var a = b?c:d;
* var a= b?c:d;
* ```
*
* ##### Invalid
*
* ```js
* var a = b ?c:d;
* var a = b? c:d;
* var a = b?c :d;
* var a = b?c: d;
* ```
*/
var assert = require('assert');
Function (anonymous_612)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_613)
✓ Was called
configure: function(options) {···
var validProperties = [
'afterTest',
'beforeConsequent',
'afterConsequent',
'beforeAlternate'
];
var optionName = this.getOptionName();

if (options === true) {
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}

assert(
typeof options === 'object',
optionName + ' option requires a true value or an object'
);

var isProperlyConfigured = validProperties.some(function(key) {
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}

return isPresent;
});

assert(
isProperlyConfigured,
optionName + ' must have at least 1 of the following properties: ' + validProperties.join(', ')
);

validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
},
configure: function(options) {
var validProperties = [
'afterTest',
'beforeConsequent',
'afterConsequent',
'beforeAlternate'
];
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (options === true) {···
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}
✓ Negative was executed (else)
}···

assert(
if (options === true) {
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}
assert(
typeof options === 'object',
optionName + ' option requires a true value or an object'
);
Function (anonymous_614)
✓ Was called
var isProperlyConfigured = validProperties.some(function(key) {···
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}

return isPresent;
});
var isProperlyConfigured = validProperties.some(function(key) {
var isPresent = key in options;
Branch IfStatement
✓ Positive was executed (if)
if (isPresent) {···
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

return isPresent;
if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
return isPresent;
});
assert(
isProperlyConfigured,
optionName + ' must have at least 1 of the following properties: ' + validProperties.join(', ')
);
Function (anonymous_615)
✓ Was called
validProperties.forEach(function(property) {···
this['_' + property] = Boolean(options[property]);
}.bind(this));
validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
},
Function (anonymous_616)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInConditionalExpression';
},
getOptionName: function() {
return 'disallowSpacesInConditionalExpression';
},
Function (anonymous_617)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ConditionalExpression'], function(node) {

var test = node.test;
var consequent = node.consequent;
var consequentToken = file.getFirstNodeToken(consequent);
var alternate = node.alternate;
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;

if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {
token = file.getPrevToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Illegal space after test'
});
}

if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
token = file.getNextToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Illegal space before consequent'
});
}

if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
token = file.getPrevToken(colonToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Illegal space after consequent'
});
}

if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
token = file.getNextToken(colonToken);
errors.assert.noWhitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Illegal space before alternate'
});
}
}.bind(this));
}
check: function(file, errors) {
Function (anonymous_618)
✓ Was called
file.iterateNodesByType(['ConditionalExpression'], function(node) {···

var test = node.test;
var consequent = node.consequent;
var consequentToken = file.getFirstNodeToken(consequent);
var alternate = node.alternate;
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;

if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {
token = file.getPrevToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Illegal space after test'
});
}

if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
token = file.getNextToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Illegal space before consequent'
});
}

if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
token = file.getPrevToken(colonToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Illegal space after consequent'
});
}

if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
token = file.getNextToken(colonToken);
errors.assert.noWhitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Illegal space before alternate'
});
}
}.bind(this));
file.iterateNodesByType(['ConditionalExpression'], function(node) {
var test = node.test;
var consequent = node.consequent;
var consequentToken = file.getFirstNodeToken(consequent);
var alternate = node.alternate;
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;
Branch IfStatement
✓ Positive was executed (if)
if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {···
token = file.getPrevToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Illegal space after test'
});
}
✓ Negative was executed (else)
}···

if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
Branch LogicalExpression
✓ Was returned
if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {
✓ Was returned
if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {
if (this._afterTest && file.isOnTheSameLine(test, questionMarkToken)) {
token = file.getPrevToken(questionMarkToken);
errors.assert.noWhitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Illegal space after test'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {···
token = file.getNextToken(questionMarkToken);

errors.assert.noWhitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Illegal space before consequent'
});
}
✓ Negative was executed (else)
}···

if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
Branch LogicalExpression
✓ Was returned
if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
✓ Was returned
if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
if (this._beforeConsequent && file.isOnTheSameLine(questionMarkToken, consequent)) {
token = file.getNextToken(questionMarkToken);
errors.assert.noWhitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Illegal space before consequent'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {···
token = file.getPrevToken(colonToken);

errors.assert.noWhitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Illegal space after consequent'
});
}
✓ Negative was executed (else)
}···

if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
Branch LogicalExpression
✓ Was returned
if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
✓ Was returned
if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
if (this._afterConsequent && file.isOnTheSameLine(consequent, colonToken)) {
token = file.getPrevToken(colonToken);
errors.assert.noWhitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Illegal space after consequent'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {···
token = file.getNextToken(colonToken);
errors.assert.noWhitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Illegal space before alternate'
});
}
✓ Negative was executed (else)
}···
}.bind(this));
Branch LogicalExpression
✓ Was returned
if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
✓ Was returned
if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
if (this._beforeAlternate && file.isOnTheSameLine(colonToken, alternate)) {
token = file.getNextToken(colonToken);
errors.assert.noWhitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Illegal space before alternate'
});
}
}.bind(this));
}
};
disallow-spaces-in-for-statement.js
/**
* Disallow spaces in between for statement.
*
* Type: `Boolean`
*
* Value: `true` to disallow spaces in between for statement.
*
* #### Example
*
* ```js
* "disallowSpacesInForStatement": true
* ```
*
* ##### Valid
*
* ```js
* for(var i=0;i<l;i++) {
* x++;
* }
* ```
*
* ##### Invalid
*
* ```js
* for(var i = 0; i<l; i++) {
* x++;
* }
* ```
*
* ```js
* for(var i = 0; i<l;i++) {
* x++;
* }
* ```
*
* ```js
* for(var i = 0;i<l; i++) {
* x++;
* }
* ```
*/
var assert = require('assert');
Function (anonymous_619)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_620)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_621)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInForStatement';
},
getOptionName: function() {
return 'disallowSpacesInForStatement';
},
Function (anonymous_622)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ForStatement', function(node) {
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(testToken),
nextToken: testToken,
message: 'Space found after semicolon'
});
}
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
message: 'Space found after semicolon'
});
}
});
}
check: function(file, errors) {
Function (anonymous_623)
✓ Was called
file.iterateNodesByType('ForStatement', function(node) {···
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(testToken),
nextToken: testToken,
message: 'Space found after semicolon'
});
}
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
message: 'Space found after semicolon'
});
}
});
file.iterateNodesByType('ForStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.test) {···
var testToken = file.getFirstNodeToken(node.test);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(testToken),
nextToken: testToken,
message: 'Space found after semicolon'
});
}
✓ Negative was executed (else)
}···
if (node.update) {
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(testToken),
nextToken: testToken,
message: 'Space found after semicolon'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (node.update) {···
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
message: 'Space found after semicolon'
});
}
✓ Negative was executed (else)
}···
});
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
message: 'Space found after semicolon'
});
}
});
}
};
disallow-spaces-in-function-declaration.js
/**
* Disallows space before `()` or `{}` in function declarations.
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "disallowSpacesInFunctionDeclaration": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* function a(){}
* ```
*
* ##### Invalid
*
* ```js
* function a() {}
* function a (){}
* function a () {}
* ```
*/
var assert = require('assert');
Function (anonymous_624)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_625)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_626)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInFunctionDeclaration';
},
getOptionName: function() {
return 'disallowSpacesInFunctionDeclaration';
},
Function (anonymous_627)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionDeclaration'], function(node) {
// Exception for `export default function` #1376
if (!node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(node.id);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_628)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration'], function(node) {···
// Exception for `export default function` #1376
if (!node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(node.id);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionDeclaration'], function(node) {
// Exception for `export default function` #1376
Branch IfStatement
✓ Positive was executed (if)
if (!node.id) {···
return;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
if (!node.id) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(node.id);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(node.id);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✗ Was not returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
};
disallow-spaces-in-function-expression.js
/**
* Disallows space before `()` or `{}` in function expressions (both [named](#disallowspacesinnamedfunctionexpression)
* and [anonymous](#disallowspacesinanonymousfunctionexpression)).
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "disallowSpacesInFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var x = function(){};
* var x = function a(){};
* var x = async function(){};
* var x = async function a(){};
* ```
*
* ##### Invalid
*
* ```js
* var x = function() {};
* var x = function (){};
* var x = function () {};
* var x = function a() {};
* var x = function a (){};
* var x = function a () {};
* var x = async function () {};
* var x = async function a() {};
* var x = async function a (){};
* var x = async function a () {};
* ```
*/
var assert = require('assert');
Function (anonymous_629)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_630)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_631)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInFunctionExpression';
},
getOptionName: function() {
return 'disallowSpacesInFunctionExpression';
},
Function (anonymous_632)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType('FunctionExpression', function(node) {

// for a named function, use node.id
var functionNode = node.id || node;

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_633)
✓ Was called
file.iterateNodesByType('FunctionExpression', function(node) {···

// for a named function, use node.id
var functionNode = node.id || node;

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
file.iterateNodesByType('FunctionExpression', function(node) {
// for a named function, use node.id
Branch LogicalExpression
✓ Was returned
var functionNode = node.id || node;
✓ Was returned
var functionNode = node.id || node;
var functionNode = node.id || node;
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✓ Positive was executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
};
disallow-spaces-in-function.js
/**
* Disallows space before `()` or `{}` in function expressions (both [named](#disallowspacesinnamedfunctionexpression)
* and [anonymous](#disallowspacesinanonymousfunctionexpression)) and function declarations.
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "disallowSpacesInFunction": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var x = function(){};
* var x = function a(){};
* function a(){}
* ```
*
* ##### Invalid
*
* ```js
* var x = function() {};
* var x = function (){};
* var x = function () {};
* var x = function a() {};
* var x = function a (){};
* var x = function a () {};
* function a() {}
* function a (){}
* function a () {}
* ```
*/
var assert = require('assert');
Function (anonymous_634)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_635)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_636)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInFunction';
},
getOptionName: function() {
return 'disallowSpacesInFunction';
},
Function (anonymous_637)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_638)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
// for a named function, use node.id
Branch LogicalExpression
✓ Was returned
var functionNode = node.id || node;
✓ Was returned
var functionNode = node.id || node;
var functionNode = node.id || node;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✗ Was not returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
});
}
};
disallow-spaces-in-generator.js
/**
* Disallow space before or after `*` in generator functions
*
* Types: `Object`
*
* - `Object` (at least one of properties must be present and it must be set to true):
* - `'beforeStar'`
* - `true` disallows space before `*`
* - `'afterStar'`
* - `true` disallows space after `*`
*
* #### Example
*
* ```js
* "disallowSpacesInGenerator": {
* "beforeStar": true,
* "afterStar": true
* }
* ```
*
* ##### Valid for mode `{ "beforeStar": true, "afterStar": false }`
* ```js
* var x = function* () {};
* function* a() {};
* var x = async function* () {};
* var x = async function* a () {};
* async function* a() {}
* var x = async function* (){};
* ```
*
* ##### Valid for mode `{ "beforeStar": false, "afterStar": true }`
* ```js
* var x = function *() {};
* function *a() {};
* var x = async function *() {};
* var x = async function *a () {};
* async function *a() {}
* var x = async function *(){};
* ```
*
*/
var assert = require('assert');
Function (anonymous_639)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_640)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be an object'
);

if ('beforeStar' in options) {
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
if ('afterStar' in options) {
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeStar || options.afterStar,
this.getOptionName() + ' must have beforeStar or afterStar property'
);

this._beforeStar = options.beforeStar;
this._afterStar = options.afterStar;
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be an object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeStar' in options) {···
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···
if ('afterStar' in options) {
if ('beforeStar' in options) {
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('afterStar' in options) {···
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('afterStar' in options) {
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeStar || options.afterStar,
✓ Was returned
options.beforeStar || options.afterStar,
options.beforeStar || options.afterStar,
this.getOptionName() + ' must have beforeStar or afterStar property'
);
this._beforeStar = options.beforeStar;
this._afterStar = options.afterStar;
},
Function (anonymous_641)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInGenerator';
},
getOptionName: function() {
return 'disallowSpacesInGenerator';
},
Function (anonymous_642)
✓ Was called
check: function(file, errors) {···
var beforeStar = this._beforeStar;
var afterStar = this._afterStar;

file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
if (!node.generator) {
return;
}

var parent = node.parentElement;
var shorthand = node.shorthand;

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
node = parent.key;
}

var currentToken = file.getFirstNodeToken(node);

if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}

if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space before star'
});
}

if (afterStar) {
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space after star'
});
}
});
}
check: function(file, errors) {
var beforeStar = this._beforeStar;
var afterStar = this._afterStar;
Function (anonymous_643)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···
if (!node.generator) {
return;
}

var parent = node.parentElement;
var shorthand = node.shorthand;

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
node = parent.key;
}

var currentToken = file.getFirstNodeToken(node);

if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}

if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space before star'
});
}

if (afterStar) {
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space after star'
});
}
});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (!node.generator) {···
return;
}
✓ Negative was executed (else)
}···

var parent = node.parentElement;
if (!node.generator) {
return;
}
var parent = node.parentElement;
var shorthand = node.shorthand;
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
node = parent.key;
}
✓ Negative was executed (else)
}···

var currentToken = file.getFirstNodeToken(node);
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
node = parent.key;
}
var currentToken = file.getFirstNodeToken(node);
Branch IfStatement
✓ Positive was executed (if)
if (node.async && currentToken.value === 'async') {···
currentToken = file.getNextToken(currentToken);
}
✓ Negative was executed (else)
}···

if (beforeStar && !shorthand) {
Branch LogicalExpression
✓ Was returned
if (node.async && currentToken.value === 'async') {
✓ Was returned
if (node.async && currentToken.value === 'async') {
if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeStar && !shorthand) {···
// currentToken assigned outside of function
errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space before star'
});
}
✓ Negative was executed (else)
}···

if (afterStar) {
Branch LogicalExpression
✓ Was returned
if (beforeStar && !shorthand) {
✓ Was returned
if (beforeStar && !shorthand) {
if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space before star'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (afterStar) {···
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space after star'
});
}
✓ Negative was executed (else)
}···
});
if (afterStar) {
Branch IfStatement
✗ Positive was not executed (if)
if (shorthand) {···
currentToken = file.getPrevToken(currentToken);
} else {
✓ Negative was executed (else)
} else {···
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}
errors.assert.noWhitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Illegal space after star'
});
}
});
}
};
disallow-spaces-in-named-function-expression.js
/**
* Disallows space before `()` or `{}` in named function expressions.
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "disallowSpacesInNamedFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var x = function a(){};
* ```
*
* ##### Invalid
*
* ```js
* var x = function a() {};
* var x = function a (){};
* var x = function a () {};
* ```
*/
var assert = require('assert');
Function (anonymous_644)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_645)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
'or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
'or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_646)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInNamedFunctionExpression';
},
getOptionName: function() {
return 'disallowSpacesInNamedFunctionExpression';
},
Function (anonymous_647)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node.id;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

// named function expressions only
if (node.id) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_648)
✓ Was called
file.iterateNodesByType(['FunctionExpression'], function(node) {···
var functionNode = node.id;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

// named function expressions only
if (node.id) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
}
});
file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node.id;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
}
✓ Negative was executed (else)
}···

// named function expressions only
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}
// named function expressions only
Branch IfStatement
✓ Positive was executed (if)
if (node.id) {···
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
}
✗ Negative was not executed (else)
}···
});
if (node.id) {
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.noWhitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.noWhitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Illegal space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
}
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.noWhitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Illegal space before opening curly brace'
});
}
}
});
}
};
disallow-spaces-inside-array-brackets.js
/**
* Disallows space after opening array square bracket and before closing.
* Reports only on arrays, not on property accessors.
* Use [disallowSpacesInsideBrackets](http://jscs.info/rule/disallowSpacesInsideBrackets.html)
* to report on all brackets.
*
* Types: `Boolean`, `String` or `Object`
*
* Values: `"all"` or `true` for strict mode, `"nested"` (*deprecated* use `"allExcept": [ "[", "]" ]`)
* ignores closing brackets in a row.
*
* #### Example
*
* ```js
* "disallowSpacesInsideArrayBrackets": "all"
*
* // or
*
* "disallowSpacesInsideArrayBrackets": {
* "allExcept": [ "[", "]", "{", "}" ]
* }
* ```
*
* ##### Valid for mode `"all"`
*
* ```js
* var x = [[1]];
* var x = a[ 0 ]; // Property accessor not an array
* ```
*
*
* ##### Valid for mode `"nested"`
*
* ```js
* var x = [ [1] ];
* ```
*
* ##### Valid for mode `"allExcept"`
*
* ```js
* var x = [ [1] ];
* var x = [ { a: 1 } ];
* ```
*
* ##### Invalid
*
* ```js
* var x = [ [ 1 ] ];
* ```
*/
var assert = require('assert');
Function (anonymous_649)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_650)
✓ Was called
configure: function(value) {···
var mode;
var modes = {
'all': true,
'nested': true
};
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule' +
' requires string value "all" or "nested" or object';

if (typeof value === 'string' || value === true) {
assert(modes[value === true ? 'all' : value], error);

} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
mode = value;
}

if (mode === 'nested') {
this._exceptions['['] = this._exceptions[']'] = true;
}
},
configure: function(value) {
var mode;
var modes = {
'all': true,
'nested': true
};
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule' +
' requires string value "all" or "nested" or object';
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'string' || value === true) {···
assert(modes[value === true ? 'all' : value], error);

} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
assert(false, error);
}
Branch LogicalExpression
✓ Was returned
if (typeof value === 'string' || value === true) {
✓ Was returned
if (typeof value === 'string' || value === true) {
if (typeof value === 'string' || value === true) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
assert(modes[value === true ? 'all' : value], error);
✓ Negative was returned (: ...)
assert(modes[value === true ? 'all' : value], error);
assert(modes[value === true ? 'all' : value], error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
✓ Negative was executed (else)
} else {···
mode = value;
}
if (isObject) {
Function (anonymous_651)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✓ Was returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
} else {
mode = value;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'nested') {···
this._exceptions['['] = this._exceptions[']'] = true;
}
✓ Negative was executed (else)
}···
},
if (mode === 'nested') {
this._exceptions['['] = this._exceptions[']'] = true;
}
},
Function (anonymous_652)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideArrayBrackets';
},
getOptionName: function() {
return 'disallowSpacesInsideArrayBrackets';
},
Function (anonymous_653)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateNodesByType('ArrayExpression', function(node) {
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});

// Skip for empty array brackets
if (afterOpen.value === ']') {
return;
}

if (!(afterOpen.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: openBracket,
nextToken: afterOpen,
message: 'Illegal space after opening bracket'
});
}

if (!(beforeClose.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: beforeClose,
nextToken: closeBracket,
message: 'Illegal space before closing bracket'
});
}
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_654)
✓ Was called
file.iterateNodesByType('ArrayExpression', function(node) {···
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});

// Skip for empty array brackets
if (afterOpen.value === ']') {
return;
}

if (!(afterOpen.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: openBracket,
nextToken: afterOpen,
message: 'Illegal space after opening bracket'
});
}

if (!(beforeClose.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: beforeClose,
nextToken: closeBracket,
message: 'Illegal space before closing bracket'
});
}
});
file.iterateNodesByType('ArrayExpression', function(node) {
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (afterOpen.value === ']') {···
return;
}
✓ Negative was executed (else)
}···

if (!(afterOpen.value in exceptions)) {
if (afterOpen.value === ']') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!(afterOpen.value in exceptions)) {···
errors.assert.noWhitespaceBetween({
token: openBracket,
nextToken: afterOpen,
message: 'Illegal space after opening bracket'
});
}
✓ Negative was executed (else)
}···

if (!(beforeClose.value in exceptions)) {
if (!(afterOpen.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: openBracket,
nextToken: afterOpen,
message: 'Illegal space after opening bracket'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (!(beforeClose.value in exceptions)) {···
errors.assert.noWhitespaceBetween({
token: beforeClose,
nextToken: closeBracket,
message: 'Illegal space before closing bracket'
});
}
✓ Negative was executed (else)
}···
});
if (!(beforeClose.value in exceptions)) {
errors.assert.noWhitespaceBetween({
token: beforeClose,
nextToken: closeBracket,
message: 'Illegal space before closing bracket'
});
}
});
}
};
disallow-spaces-inside-brackets.js
/**
* Disallows space after opening square bracket and before closing.
* Reports on all on brackets, even on property accessors.
* Use [disallowSpacesInsideArrayBrackets](http://jscs.info/rule/disallowSpacesInsideArrayBrackets.html)
* to exclude property accessors.
*
* Types: `Boolean` or `Object`
*
* Values: `true` for strict mode, or `"allExcept": [ "[", "]" ]`
* ignores closing brackets in a row.
*
* #### Example
*
* ```js
* "disallowSpacesInsideBrackets": true
*
* // or
*
* "disallowSpacesInsideBrackets": {
* "allExcept": [ "[", "]", "{", "}" ]
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = [[1]];
* var x = a[1];
* ```
*
* ##### Valid for mode `{ allExcept": [ "[", "]", "{", "}" ] }`
*
* ```js
* var x = [ [1] ];
* var x = [ { a: 1 } ];
* ```
*
* ##### Invalid
*
* ```js
* var x = [ [ 1 ] ];
* ```
*/
var assert = require('assert');
Function (anonymous_655)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_656)
✓ Was called
configure: function(value) {···
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule requires string value true or object';

if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
configure: function(value) {
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule requires string value true or object';
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true, error);
}
if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (isObject) {
Function (anonymous_657)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✓ Was returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
Function (anonymous_658)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideBrackets';
},
getOptionName: function() {
return 'disallowSpacesInsideBrackets';
},
Function (anonymous_659)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.getSourceCode();

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === ']') {
return;
}

errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening bracket'
});
});

file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.getSourceCode();

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === '[') {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing bracket'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_660)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {···
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.getSourceCode();

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === ']') {
return;
}

errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.getSourceCode();
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty array brackets
if (value in exceptions) {
return;
}
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (value === ']') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (value === ']') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening bracket'
});
});
Function (anonymous_661)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {···
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.getSourceCode();

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === '[') {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.getSourceCode();
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty array brackets
if (value in exceptions) {
return;
}
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (value === '[') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (value === '[') {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing bracket'
});
});
}
};
disallow-spaces-inside-imported-object-braces.js
/**
* Disallow space after opening object curly brace and before closing in import statements.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpacesInsideImportedObjectBraces": true
* ```
*
* ##### Valid
*
* ```js
* import {foo, bar} from 'foo-bar';
*
* import {foo as f, bar} from 'foo-bar';
* ```
*
* ##### Invalid
*
* ```js
* import { foo, bar } from 'foo-bar';
*
* import { foo as f, bar } from 'foo-bar';
* ```
*/
var assert = require('assert');
Function (anonymous_662)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_663)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_664)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideImportedObjectBraces';
},
getOptionName: function() {
return 'disallowSpacesInsideImportedObjectBraces';
},
Function (anonymous_665)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ImportDeclaration'], function(node) {

if (!node.specifiers) {
return;
}

node.specifiers.forEach(function(specifier) {

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.noWhitespaceBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
message: 'Illegal space after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.noWhitespaceBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
message: 'Illegal space before closing curly brace'
});
}
});
});
}
check: function(file, errors) {
Function (anonymous_666)
✓ Was called
file.iterateNodesByType(['ImportDeclaration'], function(node) {···

if (!node.specifiers) {
return;
}

node.specifiers.forEach(function(specifier) {

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.noWhitespaceBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
message: 'Illegal space after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.noWhitespaceBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
message: 'Illegal space before closing curly brace'
});
}
});
});
file.iterateNodesByType(['ImportDeclaration'], function(node) {
Branch IfStatement
✗ Positive was not executed (if)
if (!node.specifiers) {···
return;
}
✓ Negative was executed (else)
}···

node.specifiers.forEach(function(specifier) {
if (!node.specifiers) {
return;
}
Function (anonymous_667)
✓ Was called
node.specifiers.forEach(function(specifier) {···

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.noWhitespaceBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
message: 'Illegal space after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.noWhitespaceBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
message: 'Illegal space before closing curly brace'
});
}
});
node.specifiers.forEach(function(specifier) {
Branch IfStatement
✓ Positive was executed (if)
if (specifier.type !== 'ImportSpecifier') {···
return;
}
✓ Negative was executed (else)
}···

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
if (specifier.type !== 'ImportSpecifier') {
return;
}
var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());
Branch IfStatement
✓ Positive was executed (if)
if (maybeOpeningBrace.value === '{') {···
errors.assert.noWhitespaceBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
message: 'Illegal space after opening curly brace'
});
}
✓ Negative was executed (else)
}···

if (maybeClosingBrace.value === '}') {
if (maybeOpeningBrace.value === '{') {
errors.assert.noWhitespaceBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
message: 'Illegal space after opening curly brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (maybeClosingBrace.value === '}') {···
errors.assert.noWhitespaceBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
message: 'Illegal space before closing curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (maybeClosingBrace.value === '}') {
errors.assert.noWhitespaceBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
message: 'Illegal space before closing curly brace'
});
}
});
});
}
};
disallow-spaces-inside-object-brackets.js
/**
* Disallows space after opening object curly brace and before closing.
*
* Types: `Object`, `Boolean` or `String`
*
* Values: `"all"` or `true` for strict mode, `"nested"` (*deprecated* use `"allExcept": ['}']`)
* ignores closing brackets in a row.
*
* #### Example
*
* ```js
* "disallowSpacesInsideObjectBrackets": {
* "allExcept": [ "}", ")" ]
* }
*
* // or
* "disallowSpacesInsideObjectBrackets": true | "all" | "nested"
* ```
*
* ##### Valid for mode `"all"`
*
* ```js
* var x = {a: {b: 1}};
* ```
*
* ##### Valid for mode `"nested"`
*
* ```js
* var x = {a: {b: 1} };
* ```
*
* ##### Valid for mode `"allExcept": ["}"]`
*
* ```js
* var x = {a: {b: 1} };
* ```
*
* ##### Invalid
*
* ```js
* var x = { a: { b: 1 } };
* ```
*/
var assert = require('assert');
Function (anonymous_668)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_669)
✓ Was called
configure: function(value) {···
var mode;
var modes = {
'all': true,
'nested': true
};
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule' +
' requires string "all" or "nested", true value or object';

if (typeof value === 'string' || value === true) {
assert(modes[value === true ? 'all' : value], error);

} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
mode = value;
}

if (mode === 'nested') {
this._exceptions['}'] = true;
}
},
configure: function(value) {
var mode;
var modes = {
'all': true,
'nested': true
};
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule' +
' requires string "all" or "nested", true value or object';
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'string' || value === true) {···
assert(modes[value === true ? 'all' : value], error);

} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
assert(false, error);
}
Branch LogicalExpression
✓ Was returned
if (typeof value === 'string' || value === true) {
✓ Was returned
if (typeof value === 'string' || value === true) {
if (typeof value === 'string' || value === true) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
assert(modes[value === true ? 'all' : value], error);
✓ Negative was returned (: ...)
assert(modes[value === true ? 'all' : value], error);
assert(modes[value === true ? 'all' : value], error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
✓ Negative was executed (else)
} else {···
mode = value;
}
if (isObject) {
Function (anonymous_670)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✓ Was returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
} else {
mode = value;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'nested') {···
this._exceptions['}'] = true;
}
✓ Negative was executed (else)
}···
},
if (mode === 'nested') {
this._exceptions['}'] = true;
}
},
Function (anonymous_671)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideObjectBrackets';
},
getOptionName: function() {
return 'disallowSpacesInsideObjectBrackets';
},
Function (anonymous_672)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

errors.assert.noWhitespaceBetween({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal space after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);

if (prevToken.value in exceptions) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: closingBracket,
message: 'Illegal space before closing curly brace'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_673)
✓ Was called
file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {···
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

errors.assert.noWhitespaceBetween({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal space after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);

if (prevToken.value in exceptions) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: closingBracket,
message: 'Illegal space before closing curly brace'
});
});
file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);
errors.assert.noWhitespaceBetween({
token: openingBracket,
nextToken: nextToken,
message: 'Illegal space after opening curly brace'
});
var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (prevToken.value in exceptions) {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: closingBracket,
message: 'Illegal space before closing curly brace'
});
});
}
};
disallow-spaces-inside-parentheses.js
/**
* Disallows space after opening round bracket and before closing.
*
* Types: `Boolean` or `Object`
*
* Values: Either `true` or Object with `"only"` property as an array of tokens
*
* #### Example
*
* ```js
* "disallowSpacesInsideParentheses": true
* ```
*
* ##### Valid for `true` value
*
* ```js
* var x = (1 + 2) * 3;
* ```
*
* ##### Valid for `only` value
*
* ```js
* "disallowSpacesInsideParentheses": { "only": [ "{", "}", "\"" ] }
* ```
* ```js
* var x = ( 1 + 2 );
* var x = foo({});
* var x = foo("1");
* ```
*
* ##### Invalid
*
* ```js
* var x = foo( {} );
* ```
*/
var assert = require('assert');
Function (anonymous_674)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_675)
✓ Was called
configure: function(option) {···
var isObject = typeof option === 'object';

var error = this.getOptionName() + ' option requires' +
' true or object value with "only" properties ';

// backcompat for 1.10: {all: true} #1027
if (isObject && option.all === true) {
option = true;
}

if (typeof option === 'boolean') {
assert(option === true, error);
} else if (isObject) {
assert('only' in option, error);
} else {
assert(false, error);
}

this._onlySingleQuote = false;
this._onlyDoubleQuote = false;
this._only = null;

if (option.only) {
this._only = {};

(option.only).forEach(function(value) {
if (value === '\'') {
this._onlySingleQuote = true;
}

if (value === '"') {
this._onlyDoubleQuote = true;
}

this._only[value] = true;
}, this);
}
},
configure: function(option) {
var isObject = typeof option === 'object';
var error = this.getOptionName() + ' option requires' +
' true or object value with "only" properties ';
// backcompat for 1.10: {all: true} #1027
Branch IfStatement
✓ Positive was executed (if)
if (isObject && option.all === true) {···
option = true;
}
✓ Negative was executed (else)
}···

if (typeof option === 'boolean') {
Branch LogicalExpression
✓ Was returned
if (isObject && option.all === true) {
✓ Was returned
if (isObject && option.all === true) {
if (isObject && option.all === true) {
option = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (typeof option === 'boolean') {···
assert(option === true, error);
} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert('only' in option, error);
} else {
assert(false, error);
}
if (typeof option === 'boolean') {
assert(option === true, error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert('only' in option, error);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert('only' in option, error);
} else {
assert(false, error);
}
this._onlySingleQuote = false;
this._onlyDoubleQuote = false;
this._only = null;
Branch IfStatement
✓ Positive was executed (if)
if (option.only) {···
this._only = {};

(option.only).forEach(function(value) {
if (value === '\'') {
this._onlySingleQuote = true;
}

if (value === '"') {
this._onlyDoubleQuote = true;
}

this._only[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (option.only) {
this._only = {};
Function (anonymous_676)
✓ Was called
(option.only).forEach(function(value) {···
if (value === '\'') {
this._onlySingleQuote = true;
}

if (value === '"') {
this._onlyDoubleQuote = true;
}

this._only[value] = true;
}, this);
(option.only).forEach(function(value) {
Branch IfStatement
✓ Positive was executed (if)
if (value === '\'') {···
this._onlySingleQuote = true;
}
✓ Negative was executed (else)
}···

if (value === '"') {
if (value === '\'') {
this._onlySingleQuote = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (value === '"') {···
this._onlyDoubleQuote = true;
}
✓ Negative was executed (else)
}···

this._only[value] = true;
if (value === '"') {
this._onlyDoubleQuote = true;
}
this._only[value] = true;
}, this);
}
},
Function (anonymous_677)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideParentheses';
},
getOptionName: function() {
return 'disallowSpacesInsideParentheses';
},
Function (anonymous_678)
✓ Was called
check: function(file, errors) {···
var only = this._only;
var singleQuote = this._onlySingleQuote;
var doubleQuote = this._onlyDoubleQuote;
var alreadyAdded = [];

file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();
var shouldReturn = true;

if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
shouldReturn = false;
}

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
shouldReturn = false;
}

if (only && value in only) {
shouldReturn = false;
}

if (!only) {
shouldReturn = false;
}

if (shouldReturn) {
return;
}

var isAdded = errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening round bracket'
});

if (isAdded) {
alreadyAdded.push(token);
}
});

file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();
var shouldReturn = true;

// Do not check already found errors, like "function ( ) { ..."
if (alreadyAdded.indexOf(prevToken) > -1) {
return;
}

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
shouldReturn = false;
}

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
shouldReturn = false;
}

if (only) {
if (value in only) {
shouldReturn = false;
}

if (
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
) {
shouldReturn = true;
}
} else {
shouldReturn = false;
}

if (shouldReturn) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing round bracket'
});
});
}
check: function(file, errors) {
var only = this._only;
var singleQuote = this._onlySingleQuote;
var doubleQuote = this._onlyDoubleQuote;
var alreadyAdded = [];
Function (anonymous_679)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {···
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();
var shouldReturn = true;

if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
shouldReturn = false;
}

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
shouldReturn = false;
}

if (only && value in only) {
shouldReturn = false;
}

if (!only) {
shouldReturn = false;
}

if (shouldReturn) {
return;
}

var isAdded = errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening round bracket'
});

if (isAdded) {
alreadyAdded.push(token);
}
});
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();
var shouldReturn = true;
Branch IfStatement
✓ Positive was executed (if)
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (only && value in only) {
Branch LogicalExpression
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
Branch LogicalExpression
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (only && value in only) {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (!only) {
Branch LogicalExpression
✓ Was returned
if (only && value in only) {
✓ Was returned
if (only && value in only) {
if (only && value in only) {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (!only) {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (shouldReturn) {
if (!only) {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (shouldReturn) {···
return;
}
✓ Negative was executed (else)
}···

var isAdded = errors.assert.noWhitespaceBetween({
if (shouldReturn) {
return;
}
var isAdded = errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening round bracket'
});
Branch IfStatement
✓ Positive was executed (if)
if (isAdded) {···
alreadyAdded.push(token);
}
✓ Negative was executed (else)
}···
});
if (isAdded) {
alreadyAdded.push(token);
}
});
Function (anonymous_680)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();
var shouldReturn = true;

// Do not check already found errors, like "function ( ) { ..."
if (alreadyAdded.indexOf(prevToken) > -1) {
return;
}

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
shouldReturn = false;
}

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
shouldReturn = false;
}

if (only) {
if (value in only) {
shouldReturn = false;
}

if (
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
) {
shouldReturn = true;
}
} else {
shouldReturn = false;
}

if (shouldReturn) {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing round bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();
var shouldReturn = true;
// Do not check already found errors, like "function ( ) { ..."
Branch IfStatement
✓ Positive was executed (if)
if (alreadyAdded.indexOf(prevToken) > -1) {···
return;
}
✓ Negative was executed (else)
}···

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
if (alreadyAdded.indexOf(prevToken) > -1) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (only) {
Branch LogicalExpression
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
Branch LogicalExpression
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (only) {···
if (value in only) {
shouldReturn = false;
}

if (
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
) {
shouldReturn = true;
}
} else {
✓ Negative was executed (else)
} else {···
shouldReturn = false;
}
if (only) {
Branch IfStatement
✓ Positive was executed (if)
if (value in only) {···
shouldReturn = false;
}
✓ Negative was executed (else)
}···

if (
if (value in only) {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
) {···
shouldReturn = true;
}
✓ Negative was executed (else)
}···
} else {
if (
Branch LogicalExpression
✓ Was returned
prevToken.parentElement.type === 'MemberExpression'
✓ Was returned
value === ']' &&
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
) {
shouldReturn = true;
}
} else {
shouldReturn = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (shouldReturn) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (shouldReturn) {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing round bracket'
});
});
}
};
disallow-spaces-inside-parenthesized-expression.js
/**
* Disallows space after opening and before closing grouping parentheses.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`: always disallow spaces inside grouping parentheses
* - `Object`:
* - `"allExcept"`: `[ "{", "}", "function" ]` Ignore parenthesized objects and functions
*
* #### Example
*
* ```js
* "disallowSpacesInsideParenthesizedExpression": true
*
* // or
*
* "disallowSpacesInsideParenthesizedExpression": {
* "allExcept": [ "{", "}" ]
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = (1 + obj.size) * (2);
* ```
*
* ##### Valid for mode `{ allExcept": [ "{", "}", "function" ] }`
*
* ```js
* var x = (options || { x: true } ).x;
* var global = ( function() { return this; } )();
* ```
*
* ##### Invalid
*
* ```js
* var x = ( 1 + obj.size ) * ( 2 );
* ```
*/
var assert = require('assert');
var TokenCategorizer = require('../token-categorizer');
Function (anonymous_681)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_682)
✓ Was called
configure: function(value) {···
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule requires string value true or object';

if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
configure: function(value) {
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule requires string value true or object';
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true, error);
}
if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (isObject) {
Function (anonymous_683)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
Function (anonymous_684)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideParenthesizedExpression';
},
getOptionName: function() {
return 'disallowSpacesInsideParenthesizedExpression';
},
Function (anonymous_685)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.isComment ?
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;

// Skip empty parentheses and explicit exceptions
if (value === ')' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening grouping parenthesis'
});
});

file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.isComment ?
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;

// Skip empty parentheses and explicit exceptions
if (value === '(' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing grouping parenthesis'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_686)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {···
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.isComment ?
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;

// Skip empty parentheses and explicit exceptions
if (value === ')' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening grouping parenthesis'
});
});
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
Branch ConditionalExpression
✓ Positive was returned (? ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
✓ Negative was returned (: ...)
nextToken.value;
var value = nextToken.isComment ?
Branch ConditionalExpression
✓ Positive was returned (? ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
✓ Negative was returned (: ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;
// Skip empty parentheses and explicit exceptions
Branch IfStatement
✓ Positive was executed (if)
if (value === ')' || value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip non-expression parentheses
Branch LogicalExpression
✓ Was returned
if (value === ')' || value in exceptions) {
✓ Was returned
if (value === ')' || value in exceptions) {
if (value === ')' || value in exceptions) {
return;
}
// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
Branch IfStatement
✓ Positive was executed (if)
if (type !== 'ParenthesizedExpression') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (type !== 'ParenthesizedExpression') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Illegal space after opening grouping parenthesis'
});
});
Function (anonymous_687)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.isComment ?
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;

// Skip empty parentheses and explicit exceptions
if (value === '(' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing grouping parenthesis'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
Branch ConditionalExpression
✓ Positive was returned (? ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
✓ Negative was returned (: ...)
prevToken.value;
var value = prevToken.isComment ?
Branch ConditionalExpression
✓ Positive was returned (? ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
✓ Negative was returned (: ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;
// Skip empty parentheses and explicit exceptions
Branch IfStatement
✓ Positive was executed (if)
if (value === '(' || value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip non-expression parentheses
Branch LogicalExpression
✓ Was returned
if (value === '(' || value in exceptions) {
✓ Was returned
if (value === '(' || value in exceptions) {
if (value === '(' || value in exceptions) {
return;
}
// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
Branch IfStatement
✓ Positive was executed (if)
if (type !== 'ParenthesizedExpression') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.noWhitespaceBetween({
if (type !== 'ParenthesizedExpression') {
return;
}
errors.assert.noWhitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Illegal space before closing grouping parenthesis'
});
});
}
};
token-categorizer.js
var assert = require('assert');
var FUNCTION_TYPE_RE = /Function/;
var PAREN_KEYWORD_TYPE_RE = /Statement$|^CatchClause$/;
var NO_PAREN_KEYWORD_TYPE_RE = /^ExpressionStatement$|^ReturnStatement$|^ThrowStatement$/;
var QUASI_STATEMENT_TYPE_RE = /Statement$|Declaration$/;
Function nodeContains
✓ Was called
function nodeContains(node, token) {···
var currentNode = token.parentElement;
while (currentNode) {
if (currentNode === node) {
return true;
}
currentNode = currentNode.parentElement;
}
return false;
}
function nodeContains(node, token) {
var currentNode = token.parentElement;
while (currentNode) {
Branch IfStatement
✗ Positive was not executed (if)
if (currentNode === node) {···
return true;
}
✓ Negative was executed (else)
}···
currentNode = currentNode.parentElement;
if (currentNode === node) {
return true;
}
currentNode = currentNode.parentElement;
}
return false;
}
/**
* Returns the type of AST node or ECMAScript production in which the provided
* open parenthesis token is included.
*
* @param {Object} token
* @returns {String}
*/
Function (anonymous_689)
✓ Was called
exports.categorizeOpenParen = function(token) {···
assert(token.value === '(', 'Input token must be a parenthesis');
var node = token.parentElement;
var nodeType = node.type;
var prevToken = token.getPreviousCodeToken();

// Outermost grouping parenthesis
if (!prevToken) {
return 'ParenthesizedExpression';
}

// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
!NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {

return 'Statement';
}

// Part of a function definition (declaration, expression, method, etc.)
if (FUNCTION_TYPE_RE.test(nodeType) &&

// Name is optional for function expressions
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {

return 'Function';
}

// Part of a call expression
var prevNode = prevToken.parentElement;
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&

// Must not be inside an arguments list or other grouping parentheses
prevToken.value !== ',' && prevToken.value !== '(' &&

// If the callee is parenthesized (e.g., `(foo.bar)()`), prevNode will match node
// Otherwise (e.g., `foo.bar()`), prevToken must be the last token of the callee node
(prevNode === node || prevToken === node.callee.getLastToken())) {

return 'CallExpression';
}

// All remaining cases are grouping parentheses
return 'ParenthesizedExpression';
};
exports.categorizeOpenParen = function(token) {
assert(token.value === '(', 'Input token must be a parenthesis');
var node = token.parentElement;
var nodeType = node.type;
var prevToken = token.getPreviousCodeToken();
// Outermost grouping parenthesis
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken) {···
return 'ParenthesizedExpression';
}
✓ Negative was executed (else)
}···

// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
if (!prevToken) {
return 'ParenthesizedExpression';
}
// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
Branch IfStatement
✓ Positive was executed (if)
!NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {···

return 'Statement';
}
✓ Negative was executed (else)
}···

// Part of a function definition (declaration, expression, method, etc.)
Branch LogicalExpression
✓ Was returned
!NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
✓ Was returned
if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
Branch LogicalExpression
✓ Was returned
if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
✓ Was returned
if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
!NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
return 'Statement';
}
// Part of a function definition (declaration, expression, method, etc.)
Branch IfStatement
✓ Positive was executed (if)
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {···

return 'Function';
}
✓ Negative was executed (else)
}···

// Part of a call expression
Branch LogicalExpression
✓ Was returned
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {
✓ Was returned
if (FUNCTION_TYPE_RE.test(nodeType) &&
if (FUNCTION_TYPE_RE.test(nodeType) &&
// Name is optional for function expressions
Branch LogicalExpression
✓ Was returned
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {
✓ Was returned
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {
(prevToken.type === 'Identifier' || prevToken.value === 'function')) {
return 'Function';
}
// Part of a call expression
var prevNode = prevToken.parentElement;
Branch IfStatement
✓ Positive was executed (if)
(prevNode === node || prevToken === node.callee.getLastToken())) {···

return 'CallExpression';
}
✓ Negative was executed (else)
}···

// All remaining cases are grouping parentheses
Branch LogicalExpression
✓ Was returned
(prevNode === node || prevToken === node.callee.getLastToken())) {
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&···

// Must not be inside an arguments list or other grouping parentheses
prevToken.value !== ',' && prevToken.value !== '(' &&
Branch LogicalExpression
✓ Was returned
prevToken.value !== ',' && prevToken.value !== '(' &&
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&···

// Must not be inside an arguments list or other grouping parentheses
prevToken.value !== ',' && prevToken.value !== '(' &&
Branch LogicalExpression
✓ Was returned
prevToken.value !== ',' && prevToken.value !== '(' &&
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&
Branch LogicalExpression
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&
// Must not be inside an arguments list or other grouping parentheses
prevToken.value !== ',' && prevToken.value !== '(' &&
// If the callee is parenthesized (e.g., `(foo.bar)()`), prevNode will match node
// Otherwise (e.g., `foo.bar()`), prevToken must be the last token of the callee node
Branch LogicalExpression
✓ Was returned
(prevNode === node || prevToken === node.callee.getLastToken())) {
✓ Was returned
(prevNode === node || prevToken === node.callee.getLastToken())) {
(prevNode === node || prevToken === node.callee.getLastToken())) {
return 'CallExpression';
}
// All remaining cases are grouping parentheses
return 'ParenthesizedExpression';
};
/**
* Returns the type of AST node or ECMAScript production in which the provided
* close parenthesis token is included.
*
* @param {Object} token
* @returns {String}
*/
Function (anonymous_690)
✓ Was called
exports.categorizeCloseParen = function(token) {···
assert(token.value === ')', 'Input token must be a parenthesis');
var node = token.parentElement;
var nodeType = node.type;
var nextToken = token.getNextCodeToken();

// Terminal statement
if (nextToken.type === 'EOF') {
switch (nodeType) {
case 'DoWhileStatement':
return 'Statement';
case 'CallExpression':
case 'NewExpression':
return 'CallExpression';
default:
return 'ParenthesizedExpression';
}
}

// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
// Closing parentheses for `switch` and `catch` must be followed by "{"
// Closing parentheses for `do..while` may be the last punctuation inside a block
if (nextToken.value === '{' || nextToken.value === '}') {
return 'Statement';
}

// Closing parentheses for other statements must be followed by a statement or declaration
var nextNode = nextToken.parentElement;
while (!nodeContains(nextNode, token)) {
if (QUASI_STATEMENT_TYPE_RE.test(nextNode.type)) {
return 'Statement';
}
nextNode = nextNode.parentElement;
}
}

// Part of a function definition (declaration, expression, method, etc.)
if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {
return 'Function';
}

// Part of a call expression
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression')) {
var openParen = node.callee.getNextToken();
if (openParen.parentElement === node && node.lastChild === token) {
return 'CallExpression';
}
}

// All remaining cases are grouping parentheses
return 'ParenthesizedExpression';
};
exports.categorizeCloseParen = function(token) {
assert(token.value === ')', 'Input token must be a parenthesis');
var node = token.parentElement;
var nodeType = node.type;
var nextToken = token.getNextCodeToken();
// Terminal statement
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'EOF') {···
switch (nodeType) {
case 'DoWhileStatement':
return 'Statement';
case 'CallExpression':
case 'NewExpression':
return 'CallExpression';
default:
return 'ParenthesizedExpression';
}
}
✓ Negative was executed (else)
}···

// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
if (nextToken.type === 'EOF') {
Branch SwitchStatement
✓ Was evaluated
case 'DoWhileStatement':···
return 'Statement';
✓ Was evaluated
case 'CallExpression':
✓ Was evaluated
case 'NewExpression':···
return 'CallExpression';
✓ Was evaluated
default:···
return 'ParenthesizedExpression';
switch (nodeType) {
case 'DoWhileStatement':
return 'Statement';
case 'CallExpression':
case 'NewExpression':
return 'CallExpression';
default:
return 'ParenthesizedExpression';
}
}
// Part of a parentheses-bearing statement (if, with, while, switch, etc.)
Branch IfStatement
✓ Positive was executed (if)
if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {···
// Closing parentheses for `switch` and `catch` must be followed by "{"
// Closing parentheses for `do..while` may be the last punctuation inside a block
if (nextToken.value === '{' || nextToken.value === '}') {
return 'Statement';
}

// Closing parentheses for other statements must be followed by a statement or declaration
var nextNode = nextToken.parentElement;
while (!nodeContains(nextNode, token)) {
if (QUASI_STATEMENT_TYPE_RE.test(nextNode.type)) {
return 'Statement';
}
nextNode = nextNode.parentElement;
}
}
✓ Negative was executed (else)
}···

// Part of a function definition (declaration, expression, method, etc.)
Branch LogicalExpression
✓ Was returned
if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
✓ Was returned
if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
// Closing parentheses for `switch` and `catch` must be followed by "{"
// Closing parentheses for `do..while` may be the last punctuation inside a block
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value === '{' || nextToken.value === '}') {···
return 'Statement';
}
✓ Negative was executed (else)
}···

// Closing parentheses for other statements must be followed by a statement or declaration
Branch LogicalExpression
✓ Was returned
if (nextToken.value === '{' || nextToken.value === '}') {
✓ Was returned
if (nextToken.value === '{' || nextToken.value === '}') {
if (nextToken.value === '{' || nextToken.value === '}') {
return 'Statement';
}
// Closing parentheses for other statements must be followed by a statement or declaration
var nextNode = nextToken.parentElement;
while (!nodeContains(nextNode, token)) {
Branch IfStatement
✓ Positive was executed (if)
if (QUASI_STATEMENT_TYPE_RE.test(nextNode.type)) {···
return 'Statement';
}
✗ Negative was not executed (else)
}···
nextNode = nextNode.parentElement;
if (QUASI_STATEMENT_TYPE_RE.test(nextNode.type)) {
return 'Statement';
}
nextNode = nextNode.parentElement;
}
}
// Part of a function definition (declaration, expression, method, etc.)
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {···
return 'Function';
}
✓ Negative was executed (else)
}···

// Part of a call expression
Branch LogicalExpression
✓ Was returned
if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {
✓ Was returned
if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {
if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {
return 'Function';
}
// Part of a call expression
Branch IfStatement
✓ Positive was executed (if)
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression')) {···
var openParen = node.callee.getNextToken();
if (openParen.parentElement === node && node.lastChild === token) {
return 'CallExpression';
}
}
✓ Negative was executed (else)
}···

// All remaining cases are grouping parentheses
Branch LogicalExpression
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression')) {
✓ Was returned
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression')) {
if ((nodeType === 'CallExpression' || nodeType === 'NewExpression')) {
var openParen = node.callee.getNextToken();
Branch IfStatement
✓ Positive was executed (if)
if (openParen.parentElement === node && node.lastChild === token) {···
return 'CallExpression';
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (openParen.parentElement === node && node.lastChild === token) {
✗ Was not returned
if (openParen.parentElement === node && node.lastChild === token) {
if (openParen.parentElement === node && node.lastChild === token) {
return 'CallExpression';
}
}
// All remaining cases are grouping parentheses
return 'ParenthesizedExpression';
};
disallow-spaces-inside-template-string-placeholders.js
/**
* Disallows spaces before and after curly brace inside template string placeholders.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowSpacesInsideTemplateStringPlaceholders": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* `Hello ${name}!`
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* `Hello ${ name}!`
* `Hello ${name }!`
* `Hello ${ name }!`
* ```
*/
var assert = require('assert');
Function (anonymous_691)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_692)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_693)
✓ Was called
getOptionName: function() {···
return 'disallowSpacesInsideTemplateStringPlaceholders';
},
getOptionName: function() {
return 'disallowSpacesInsideTemplateStringPlaceholders';
},
Function (anonymous_694)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('TemplateLiteral', function(node) {
node.childElements
.filter(function(element) {
return element.isToken && element.type === 'Punctuator';
})
.forEach(function(element) {
if (element.value === '${' && element.nextSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element,
nextToken: element.getNextCodeToken(),
message: 'Illegal space after "${"'
});
}
if (element.value === '}' && element.previousSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element.getPreviousCodeToken(),
nextToken: element,
message: 'Illegal space before "}"'
});
}
});
});
}
check: function(file, errors) {
Function (anonymous_695)
✓ Was called
file.iterateNodesByType('TemplateLiteral', function(node) {···
node.childElements
.filter(function(element) {
return element.isToken && element.type === 'Punctuator';
})
.forEach(function(element) {
if (element.value === '${' && element.nextSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element,
nextToken: element.getNextCodeToken(),
message: 'Illegal space after "${"'
});
}
if (element.value === '}' && element.previousSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element.getPreviousCodeToken(),
nextToken: element,
message: 'Illegal space before "}"'
});
}
});
});
file.iterateNodesByType('TemplateLiteral', function(node) {
node.childElements
Function (anonymous_696)
✓ Was called
.filter(function(element) {···
return element.isToken && element.type === 'Punctuator';
})
.filter(function(element) {
Branch LogicalExpression
✓ Was returned
return element.isToken && element.type === 'Punctuator';
✓ Was returned
return element.isToken && element.type === 'Punctuator';
return element.isToken && element.type === 'Punctuator';
})
Function (anonymous_697)
✓ Was called
.forEach(function(element) {···
if (element.value === '${' && element.nextSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element,
nextToken: element.getNextCodeToken(),
message: 'Illegal space after "${"'
});
}
if (element.value === '}' && element.previousSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element.getPreviousCodeToken(),
nextToken: element,
message: 'Illegal space before "}"'
});
}
});
.forEach(function(element) {
Branch IfStatement
✓ Positive was executed (if)
if (element.value === '${' && element.nextSibling.isWhitespace) {···
errors.assert.noWhitespaceBetween({
token: element,
nextToken: element.getNextCodeToken(),
message: 'Illegal space after "${"'
});
}
✓ Negative was executed (else)
}···
if (element.value === '}' && element.previousSibling.isWhitespace) {
Branch LogicalExpression
✓ Was returned
if (element.value === '${' && element.nextSibling.isWhitespace) {
✓ Was returned
if (element.value === '${' && element.nextSibling.isWhitespace) {
if (element.value === '${' && element.nextSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element,
nextToken: element.getNextCodeToken(),
message: 'Illegal space after "${"'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (element.value === '}' && element.previousSibling.isWhitespace) {···
errors.assert.noWhitespaceBetween({
token: element.getPreviousCodeToken(),
nextToken: element,
message: 'Illegal space before "}"'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (element.value === '}' && element.previousSibling.isWhitespace) {
✓ Was returned
if (element.value === '}' && element.previousSibling.isWhitespace) {
if (element.value === '}' && element.previousSibling.isWhitespace) {
errors.assert.noWhitespaceBetween({
token: element.getPreviousCodeToken(),
nextToken: element,
message: 'Illegal space before "}"'
});
}
});
});
}
};
disallow-tabs.js
/**
* Disallows tabs everywhere.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "disallowTabs": true
* ```
*
* ##### Valid
*
* ```js
* if (true) {
* \s\sfoo();
* }
* ```
*
* ##### Invalid
*
* ```js
* if (true){
* \tfoo();
* }
* ```
*/
var assert = require('assert');
Function (anonymous_698)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_699)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_700)
✓ Was called
getOptionName: function() {···
return 'disallowTabs';
},
getOptionName: function() {
return 'disallowTabs';
},
Function (anonymous_701)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByType('Whitespace', function(whitespace) {
var match = whitespace.value.match(/\t/);
if (match) {
errors.add('Tab found', whitespace, match.index);
}
});
}
check: function(file, errors) {
Function (anonymous_702)
✓ Was called
file.iterateTokensByType('Whitespace', function(whitespace) {···
var match = whitespace.value.match(/\t/);
if (match) {
errors.add('Tab found', whitespace, match.index);
}
});
file.iterateTokensByType('Whitespace', function(whitespace) {
var match = whitespace.value.match(/\t/);
Branch IfStatement
✓ Positive was executed (if)
if (match) {···
errors.add('Tab found', whitespace, match.index);
}
✓ Negative was executed (else)
}···
});
if (match) {
errors.add('Tab found', whitespace, match.index);
}
});
}
};
disallow-trailing-comma.js
/**
* Disallows an extra comma following the final element of an array or object literal.
*
* Type: `Boolean`
*
* Value: `true`
*
* JSHint: [`es3`](http://jshint.com/docs/options/#es3)
*
* #### Example
*
* ```js
* "disallowTrailingComma": true
* ```
*
* ##### Valid
*
* ```js
* var foo = [1, 2, 3];
* var bar = {a: "a", b: "b"}
* const [1, 2, 3];
* const {a: "a", b: "b"}
* ```
*
* ##### Invalid
*
* ```js
* var foo = [1, 2, 3, ];
* var bar = {a: "a", b: "b", }
* ```
*/
var assert = require('assert');
Function (anonymous_703)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_704)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_705)
✓ Was called
getOptionName: function() {···
return 'disallowTrailingComma';
},
getOptionName: function() {
return 'disallowTrailingComma';
},
Function (anonymous_706)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType([
'ObjectExpression', 'ArrayExpression',
'ObjectPattern', 'ArrayPattern'
], function(node) {
var closingToken = file.getLastNodeToken(node);
var comma = closingToken.getPreviousCodeToken();

if (comma.type === 'Punctuator' && comma.value === ',') {
errors.add(
'Extra comma following the final element of an array or object literal',
comma
);
}
});
},
check: function(file, errors) {
file.iterateNodesByType([
'ObjectExpression', 'ArrayExpression',
'ObjectPattern', 'ArrayPattern'
Function (anonymous_707)
✓ Was called
], function(node) {···
var closingToken = file.getLastNodeToken(node);
var comma = closingToken.getPreviousCodeToken();

if (comma.type === 'Punctuator' && comma.value === ',') {
errors.add(
'Extra comma following the final element of an array or object literal',
comma
);
}
});
], function(node) {
var closingToken = file.getLastNodeToken(node);
var comma = closingToken.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (comma.type === 'Punctuator' && comma.value === ',') {···
errors.add(
'Extra comma following the final element of an array or object literal',
comma
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (comma.type === 'Punctuator' && comma.value === ',') {
✓ Was returned
if (comma.type === 'Punctuator' && comma.value === ',') {
if (comma.type === 'Punctuator' && comma.value === ',') {
errors.add(
'Extra comma following the final element of an array or object literal',
comma
);
}
});
},
Function (anonymous_708)
✓ Was called
_fix: function(file, error) {···
error.element.remove();
}
_fix: function(file, error) {
error.element.remove();
}
};
disallow-trailing-whitespace.js
/**
* Requires all lines to end on a non-whitespace character
*
* Types: `Boolean` or `String`
*
* Values:
* - `true`
* - `"ignoreEmptyLines"`: (default: `false`) allow whitespace on empty lines
*
* JSHint: [`trailing`](http://jshint.com/docs/options/#trailing)
*
* #### Example
*
* ```js
* "disallowTrailingWhitespace": true
* ```
*
* ##### Valid
*
* ```js
* var foo = "blah blah";
* ```
*
* ##### Invalid
*
* ```js
* var foo = "blah blah"; //<-- whitespace character here
* ```
*
* ##### Valid for `true`
*
* ```js
* foo = 'bar';
*
* foo = 'baz';
* ```
*
* ##### Invalid for `true` but Valid for `ignoreEmptyLines`
*
* ```js
* foo = 'bar';
* \t
* foo = 'baz';
* ```
*/
var assert = require('assert');
var Token = require('cst').Token;
Function (anonymous_709)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_710)
✓ Was called
configure: function(options) {···
assert(
options === true || options === 'ignoreEmptyLines',
this.getOptionName() + ' option requires a true value or "ignoreEmptyLines"'
);
this._ignoreEmptyLines = options === 'ignoreEmptyLines';
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'ignoreEmptyLines',
✓ Was returned
options === true || options === 'ignoreEmptyLines',
options === true || options === 'ignoreEmptyLines',
this.getOptionName() + ' option requires a true value or "ignoreEmptyLines"'
);
this._ignoreEmptyLines = options === 'ignoreEmptyLines';
},
Function (anonymous_711)
✓ Was called
getOptionName: function() {···
return 'disallowTrailingWhitespace';
},
getOptionName: function() {
return 'disallowTrailingWhitespace';
},
Function (anonymous_712)
✓ Was called
check: function(file, errors) {···
var program = file.getProgram();

if (!program) {
return;
}

var lastToken = program.getLastToken();
if (lastToken && lastToken.type === 'EOF') {
lastToken = lastToken.getPreviousToken();
}
program.selectTokensByType('Whitespace').forEach(function(whitespace) {
whitespace.getValueLineInfo().some(function(line, i) {
if (this._ignoreEmptyLines && i > 0) {
return true;
}
if (line.text && (line.lineBreak || whitespace === lastToken)) {
errors.cast({
message: 'Illegal trailing whitespace',
element: whitespace,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
program.selectTokensByType('CommentBlock').concat(program.selectTokensByType('CommentLine'))
.forEach(function(comment) {
var lines = comment.getValueLineInfo();
lines.forEach(function(line, i) {
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
return;
}
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
return;
}
if (line.text.match(/\s$/)) {
errors.cast({
message: 'Illegal trailing comment',
element: comment,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
},
check: function(file, errors) {
var program = file.getProgram();
Branch IfStatement
✗ Positive was not executed (if)
if (!program) {···
return;
}
✓ Negative was executed (else)
}···

var lastToken = program.getLastToken();
if (!program) {
return;
}
var lastToken = program.getLastToken();
Branch IfStatement
✓ Positive was executed (if)
if (lastToken && lastToken.type === 'EOF') {···
lastToken = lastToken.getPreviousToken();
}
✗ Negative was not executed (else)
}···
program.selectTokensByType('Whitespace').forEach(function(whitespace) {
Branch LogicalExpression
✓ Was returned
if (lastToken && lastToken.type === 'EOF') {
✗ Was not returned
if (lastToken && lastToken.type === 'EOF') {
if (lastToken && lastToken.type === 'EOF') {
lastToken = lastToken.getPreviousToken();
}
Function (anonymous_713)
✓ Was called
program.selectTokensByType('Whitespace').forEach(function(whitespace) {···
whitespace.getValueLineInfo().some(function(line, i) {
if (this._ignoreEmptyLines && i > 0) {
return true;
}
if (line.text && (line.lineBreak || whitespace === lastToken)) {
errors.cast({
message: 'Illegal trailing whitespace',
element: whitespace,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
program.selectTokensByType('Whitespace').forEach(function(whitespace) {
Function (anonymous_714)
✓ Was called
whitespace.getValueLineInfo().some(function(line, i) {···
if (this._ignoreEmptyLines && i > 0) {
return true;
}
if (line.text && (line.lineBreak || whitespace === lastToken)) {
errors.cast({
message: 'Illegal trailing whitespace',
element: whitespace,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
whitespace.getValueLineInfo().some(function(line, i) {
Branch IfStatement
✓ Positive was executed (if)
if (this._ignoreEmptyLines && i > 0) {···
return true;
}
✓ Negative was executed (else)
}···
if (line.text && (line.lineBreak || whitespace === lastToken)) {
Branch LogicalExpression
✓ Was returned
if (this._ignoreEmptyLines && i > 0) {
✓ Was returned
if (this._ignoreEmptyLines && i > 0) {
if (this._ignoreEmptyLines && i > 0) {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (line.text && (line.lineBreak || whitespace === lastToken)) {···
errors.cast({
message: 'Illegal trailing whitespace',
element: whitespace,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
✓ Negative was executed (else)
}···
}, this);
Branch LogicalExpression
✓ Was returned
if (line.text && (line.lineBreak || whitespace === lastToken)) {
✓ Was returned
if (line.text && (line.lineBreak || whitespace === lastToken)) {
Branch LogicalExpression
✓ Was returned
if (line.text && (line.lineBreak || whitespace === lastToken)) {
✓ Was returned
if (line.text && (line.lineBreak || whitespace === lastToken)) {
if (line.text && (line.lineBreak || whitespace === lastToken)) {
errors.cast({
message: 'Illegal trailing whitespace',
element: whitespace,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
program.selectTokensByType('CommentBlock').concat(program.selectTokensByType('CommentLine'))
Function (anonymous_715)
✓ Was called
.forEach(function(comment) {···
var lines = comment.getValueLineInfo();
lines.forEach(function(line, i) {
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
return;
}
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
return;
}
if (line.text.match(/\s$/)) {
errors.cast({
message: 'Illegal trailing comment',
element: comment,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
.forEach(function(comment) {
var lines = comment.getValueLineInfo();
Function (anonymous_716)
✓ Was called
lines.forEach(function(line, i) {···
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
return;
}
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
return;
}
if (line.text.match(/\s$/)) {
errors.cast({
message: 'Illegal trailing comment',
element: comment,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
lines.forEach(function(line, i) {
Branch IfStatement
✓ Positive was executed (if)
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {···
return;
}
✓ Negative was executed (else)
}···
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
Branch LogicalExpression
✓ Was returned
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
✓ Was returned
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
Branch LogicalExpression
✓ Was returned
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
✓ Was returned
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
if (i > 0 && this._ignoreEmptyLines && line.text.trim() === '') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (comment.type === 'CommentBlock' && i === lines.length - 1) {···
return;
}
✓ Negative was executed (else)
}···
if (line.text.match(/\s$/)) {
Branch LogicalExpression
✓ Was returned
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
✓ Was returned
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
if (comment.type === 'CommentBlock' && i === lines.length - 1) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (line.text.match(/\s$/)) {···
errors.cast({
message: 'Illegal trailing comment',
element: comment,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
✓ Negative was executed (else)
}···
}, this);
if (line.text.match(/\s$/)) {
errors.cast({
message: 'Illegal trailing comment',
element: comment,
offset: line.offset,
additional: {
lineNumber: i
}
});
}
}, this);
}, this);
},
Function (anonymous_717)
✓ Was called
_fix: function(file, error) {···
var element = error.element;
var newValue;
var lines = element.getValueLineInfo();
var line = lines[error.additional.lineNumber];
if (element.isWhitespace) {
line.text = '';
}
if (element.isComment) {
line.text = line.text.replace(/\s+$/, '');
}

newValue = lines.map(function(line) {
return line.text + (line.lineBreak || '');
}).join('');

var newElement = new Token(element.type, newValue);
element.parentElement.replaceChild(newElement, element);
}
_fix: function(file, error) {
var element = error.element;
var newValue;
var lines = element.getValueLineInfo();
var line = lines[error.additional.lineNumber];
Branch IfStatement
✓ Positive was executed (if)
if (element.isWhitespace) {···
line.text = '';
}
✓ Negative was executed (else)
}···
if (element.isComment) {
if (element.isWhitespace) {
line.text = '';
}
Branch IfStatement
✓ Positive was executed (if)
if (element.isComment) {···
line.text = line.text.replace(/\s+$/, '');
}
✓ Negative was executed (else)
}···

newValue = lines.map(function(line) {
if (element.isComment) {
line.text = line.text.replace(/\s+$/, '');
}
Function (anonymous_718)
✓ Was called
newValue = lines.map(function(line) {···
return line.text + (line.lineBreak || '');
}).join('');
newValue = lines.map(function(line) {
Branch LogicalExpression
✓ Was returned
return line.text + (line.lineBreak || '');
✓ Was returned
return line.text + (line.lineBreak || '');
return line.text + (line.lineBreak || '');
}).join('');
var newElement = new Token(element.type, newValue);
element.parentElement.replaceChild(newElement, element);
}
};
disallow-unused-params.js
/**
* Disallows unused params in function expression and function declaration.
*
* Types: `Boolean`
*
* Values: `true`
*
* #### Example
*
* ```js
* "disallowUnusedParams": true
* ```
*
* ##### Valid
*
* ```js
* function x(test) {
* return test;
* }
*
* var x = function(test) {
* return test;
* }
* ```
*
* ##### Invalid
*
* ```js
* function x(test) {
* }
*
* var x = function(test) {
* }
* ```
*/
var assert = require('assert');
Function getUnusedNodes
✓ Was called
function getUnusedNodes(node, variableMap, groupIfPossible) {···
if (node.type === 'AssignmentPattern') {
return getUnusedNodes(node.left, variableMap, groupIfPossible);
}

if (node.type === 'Identifier') {
var variable = variableMap[node.name];

var hasUsages = variable.getReferences().some(function(reference) {
return !variable.getDefinitions().some(function(definition) {
return reference.node === definition.node;
});
});

if (hasUsages) {
return [];
}

return [node];
}

if (node.type === 'RestElement') {
var restUnusedNodes = getUnusedNodes(node.argument, variableMap, groupIfPossible);
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
return [node];
}
return restUnusedNodes;
}

if (node.type === 'ArrayPattern') {
var unusedArrayNodes = [];
node.elements.forEach(function(element) {
if (element) {
unusedArrayNodes = unusedArrayNodes.concat(getUnusedNodes(element, variableMap, groupIfPossible));
return;
}
unusedArrayNodes.push(null);
});
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {
if (node.elements.every(function(element, index) {
return unusedArrayNodes[index] === element;
})) {
return [node];
}
}
return unusedArrayNodes.filter(function(node) { return node; });
}

if (node.type === 'ObjectPattern') {
var unusedObjectNodes = [];
node.properties.forEach(function(property) {
unusedObjectNodes = unusedObjectNodes.concat(getUnusedNodes(property.value, variableMap, groupIfPossible));
});
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {
if (node.properties.every(function(property, index) {
return unusedObjectNodes[index] === property.value;
})) {
return [node];
}
}
return unusedObjectNodes;
}

return [];
}
function getUnusedNodes(node, variableMap, groupIfPossible) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'AssignmentPattern') {···
return getUnusedNodes(node.left, variableMap, groupIfPossible);
}
✓ Negative was executed (else)
}···

if (node.type === 'Identifier') {
if (node.type === 'AssignmentPattern') {
return getUnusedNodes(node.left, variableMap, groupIfPossible);
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'Identifier') {···
var variable = variableMap[node.name];

var hasUsages = variable.getReferences().some(function(reference) {
return !variable.getDefinitions().some(function(definition) {
return reference.node === definition.node;
});
});

if (hasUsages) {
return [];
}

return [node];
}
✓ Negative was executed (else)
}···

if (node.type === 'RestElement') {
if (node.type === 'Identifier') {
var variable = variableMap[node.name];
Function (anonymous_720)
✓ Was called
var hasUsages = variable.getReferences().some(function(reference) {···
return !variable.getDefinitions().some(function(definition) {
return reference.node === definition.node;
});
});
var hasUsages = variable.getReferences().some(function(reference) {
Function (anonymous_721)
✓ Was called
return !variable.getDefinitions().some(function(definition) {···
return reference.node === definition.node;
});
return !variable.getDefinitions().some(function(definition) {
return reference.node === definition.node;
});
});
Branch IfStatement
✓ Positive was executed (if)
if (hasUsages) {···
return [];
}
✓ Negative was executed (else)
}···

return [node];
if (hasUsages) {
return [];
}
return [node];
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'RestElement') {···
var restUnusedNodes = getUnusedNodes(node.argument, variableMap, groupIfPossible);
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
return [node];
}
return restUnusedNodes;
}
✓ Negative was executed (else)
}···

if (node.type === 'ArrayPattern') {
if (node.type === 'RestElement') {
var restUnusedNodes = getUnusedNodes(node.argument, variableMap, groupIfPossible);
Branch IfStatement
✓ Positive was executed (if)
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {···
return [node];
}
✗ Negative was not executed (else)
}···
return restUnusedNodes;
Branch LogicalExpression
✓ Was returned
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
✗ Was not returned
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
Branch LogicalExpression
✓ Was returned
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
✗ Was not returned
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
if (groupIfPossible && restUnusedNodes.length === 1 && node.argument === restUnusedNodes[0]) {
return [node];
}
return restUnusedNodes;
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'ArrayPattern') {···
var unusedArrayNodes = [];
node.elements.forEach(function(element) {
if (element) {
unusedArrayNodes = unusedArrayNodes.concat(getUnusedNodes(element, variableMap, groupIfPossible));
return;
}
unusedArrayNodes.push(null);
});
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {
if (node.elements.every(function(element, index) {
return unusedArrayNodes[index] === element;
})) {
return [node];
}
}
return unusedArrayNodes.filter(function(node) { return node; });
}
✓ Negative was executed (else)
}···

if (node.type === 'ObjectPattern') {
if (node.type === 'ArrayPattern') {
var unusedArrayNodes = [];
Function (anonymous_722)
✓ Was called
node.elements.forEach(function(element) {···
if (element) {
unusedArrayNodes = unusedArrayNodes.concat(getUnusedNodes(element, variableMap, groupIfPossible));
return;
}
unusedArrayNodes.push(null);
});
node.elements.forEach(function(element) {
Branch IfStatement
✓ Positive was executed (if)
if (element) {···
unusedArrayNodes = unusedArrayNodes.concat(getUnusedNodes(element, variableMap, groupIfPossible));
return;
}
✓ Negative was executed (else)
}···
unusedArrayNodes.push(null);
if (element) {
unusedArrayNodes = unusedArrayNodes.concat(getUnusedNodes(element, variableMap, groupIfPossible));
return;
}
unusedArrayNodes.push(null);
});
Branch IfStatement
✓ Positive was executed (if)
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {···
if (node.elements.every(function(element, index) {
return unusedArrayNodes[index] === element;
})) {
return [node];
}
}
✓ Negative was executed (else)
}···
return unusedArrayNodes.filter(function(node) { return node; });
Branch LogicalExpression
✓ Was returned
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {
✓ Was returned
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {
if (groupIfPossible && unusedArrayNodes.length === node.elements.length) {
Function (anonymous_723)
✓ Was called
if (node.elements.every(function(element, index) {···
return unusedArrayNodes[index] === element;
})) {
Branch IfStatement
✓ Positive was executed (if)
})) {···
return [node];
}
✓ Negative was executed (else)
}···
}
if (node.elements.every(function(element, index) {
return unusedArrayNodes[index] === element;
})) {
return [node];
}
}
Function (anonymous_724)
✓ Was called
return unusedArrayNodes.filter(function(node) { return node; });
return unusedArrayNodes.filter(function(node) { return node; });
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'ObjectPattern') {···
var unusedObjectNodes = [];
node.properties.forEach(function(property) {
unusedObjectNodes = unusedObjectNodes.concat(getUnusedNodes(property.value, variableMap, groupIfPossible));
});
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {
if (node.properties.every(function(property, index) {
return unusedObjectNodes[index] === property.value;
})) {
return [node];
}
}
return unusedObjectNodes;
}
✗ Negative was not executed (else)
}···

return [];
if (node.type === 'ObjectPattern') {
var unusedObjectNodes = [];
Function (anonymous_725)
✓ Was called
node.properties.forEach(function(property) {···
unusedObjectNodes = unusedObjectNodes.concat(getUnusedNodes(property.value, variableMap, groupIfPossible));
});
node.properties.forEach(function(property) {
unusedObjectNodes = unusedObjectNodes.concat(getUnusedNodes(property.value, variableMap, groupIfPossible));
});
Branch IfStatement
✓ Positive was executed (if)
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {···
if (node.properties.every(function(property, index) {
return unusedObjectNodes[index] === property.value;
})) {
return [node];
}
}
✓ Negative was executed (else)
}···
return unusedObjectNodes;
Branch LogicalExpression
✓ Was returned
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {
✓ Was returned
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {
if (groupIfPossible && unusedObjectNodes.length === node.properties.length) {
Function (anonymous_726)
✓ Was called
if (node.properties.every(function(property, index) {···
return unusedObjectNodes[index] === property.value;
})) {
Branch IfStatement
✓ Positive was executed (if)
})) {···
return [node];
}
✗ Negative was not executed (else)
}···
}
if (node.properties.every(function(property, index) {
return unusedObjectNodes[index] === property.value;
})) {
return [node];
}
}
return unusedObjectNodes;
}
return [];
}
Function isComma
✓ Was called
function isComma(token) {···
return token.type === 'Punctuator' && token.value === ',';
}
function isComma(token) {
Branch LogicalExpression
✓ Was returned
return token.type === 'Punctuator' && token.value === ',';
✗ Was not returned
return token.type === 'Punctuator' && token.value === ',';
return token.type === 'Punctuator' && token.value === ',';
}
Function removeWithCommaIfNecessary
✓ Was called
function removeWithCommaIfNecessary(node, removeForwards) {···
var previousCodeToken = node.getPreviousCodeToken();
if (isComma(previousCodeToken)) {
node.parentElement.removeChildren(previousCodeToken, node);
return;
}

var nextCodeToken = node.getNextCodeToken();
if (removeForwards && isComma(nextCodeToken)) {
node.parentElement.removeChildren(node, nextCodeToken);
return;
}

var previousNode = node;
while (previousNode.previousSibling.isToken && !previousNode.previousSibling.isCode) {
previousNode = previousNode.previousSibling;
}
var nextNode = node;
while (nextNode.nextSibling.isToken && !nextNode.nextSibling.isCode) {
nextNode = nextNode.nextSibling;
}

node.parentElement.removeChild(previousNode, nextNode);
}
function removeWithCommaIfNecessary(node, removeForwards) {
var previousCodeToken = node.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (isComma(previousCodeToken)) {···
node.parentElement.removeChildren(previousCodeToken, node);
return;
}
✓ Negative was executed (else)
}···

var nextCodeToken = node.getNextCodeToken();
if (isComma(previousCodeToken)) {
node.parentElement.removeChildren(previousCodeToken, node);
return;
}
var nextCodeToken = node.getNextCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (removeForwards && isComma(nextCodeToken)) {···
node.parentElement.removeChildren(node, nextCodeToken);
return;
}
✓ Negative was executed (else)
}···

var previousNode = node;
Branch LogicalExpression
✓ Was returned
if (removeForwards && isComma(nextCodeToken)) {
✓ Was returned
if (removeForwards && isComma(nextCodeToken)) {
if (removeForwards && isComma(nextCodeToken)) {
node.parentElement.removeChildren(node, nextCodeToken);
return;
}
var previousNode = node;
Branch LogicalExpression
✓ Was returned
while (previousNode.previousSibling.isToken && !previousNode.previousSibling.isCode) {
✗ Was not returned
while (previousNode.previousSibling.isToken && !previousNode.previousSibling.isCode) {
while (previousNode.previousSibling.isToken && !previousNode.previousSibling.isCode) {
previousNode = previousNode.previousSibling;
}
var nextNode = node;
Branch LogicalExpression
✓ Was returned
while (nextNode.nextSibling.isToken && !nextNode.nextSibling.isCode) {
✗ Was not returned
while (nextNode.nextSibling.isToken && !nextNode.nextSibling.isCode) {
while (nextNode.nextSibling.isToken && !nextNode.nextSibling.isCode) {
nextNode = nextNode.nextSibling;
}
node.parentElement.removeChild(previousNode, nextNode);
}
Function (anonymous_729)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_730)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_731)
✓ Was called
getOptionName: function() {···
return 'disallowUnusedParams';
},
getOptionName: function() {
return 'disallowUnusedParams';
},
Function (anonymous_732)
✓ Was called
check: function(file, errors) {···

function reportError(node) {
if (node.type === 'Identifier') {
errors.add('Param `' + node.name + '` is not used', node);
} else {
errors.add('Pattern is not used', node);
}
}

file.iterateNodesByType(
['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'],
function(node) {
var variableMap = file.getScopes().acquire(node).getVariables()
.filter(function(variable) {
return variable.type === 'Parameter';
})
.reduce(function(obj, variable) {
obj[variable.name] = variable;
return obj;
}, {});

var params = node.params;
var reportUnusedDirectParams = true;

for (var i = params.length - 1; i >= 0; i--) {
var param = params[i];

if (!reportUnusedDirectParams && param.type === 'Identifier') {
continue;
}

var unusedNodes = getUnusedNodes(param, variableMap, reportUnusedDirectParams);

unusedNodes.forEach(reportError);

if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {
reportUnusedDirectParams = false;
}
}
}
);
},
check: function(file, errors) {
Function reportError
✓ Was called
function reportError(node) {···
if (node.type === 'Identifier') {
errors.add('Param `' + node.name + '` is not used', node);
} else {
errors.add('Pattern is not used', node);
}
}
function reportError(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'Identifier') {···
errors.add('Param `' + node.name + '` is not used', node);
} else {
✓ Negative was executed (else)
} else {···
errors.add('Pattern is not used', node);
}
if (node.type === 'Identifier') {
errors.add('Param `' + node.name + '` is not used', node);
} else {
errors.add('Pattern is not used', node);
}
}
file.iterateNodesByType(
['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'],
Function (anonymous_734)
✓ Was called
function(node) {···
var variableMap = file.getScopes().acquire(node).getVariables()
.filter(function(variable) {
return variable.type === 'Parameter';
})
.reduce(function(obj, variable) {
obj[variable.name] = variable;
return obj;
}, {});

var params = node.params;
var reportUnusedDirectParams = true;

for (var i = params.length - 1; i >= 0; i--) {
var param = params[i];

if (!reportUnusedDirectParams && param.type === 'Identifier') {
continue;
}

var unusedNodes = getUnusedNodes(param, variableMap, reportUnusedDirectParams);

unusedNodes.forEach(reportError);

if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {
reportUnusedDirectParams = false;
}
}
}
function(node) {
var variableMap = file.getScopes().acquire(node).getVariables()
Function (anonymous_735)
✓ Was called
.filter(function(variable) {···
return variable.type === 'Parameter';
})
.filter(function(variable) {
return variable.type === 'Parameter';
})
Function (anonymous_736)
✓ Was called
.reduce(function(obj, variable) {···
obj[variable.name] = variable;
return obj;
}, {});
.reduce(function(obj, variable) {
obj[variable.name] = variable;
return obj;
}, {});
var params = node.params;
var reportUnusedDirectParams = true;
for (var i = params.length - 1; i >= 0; i--) {
var param = params[i];
Branch IfStatement
✓ Positive was executed (if)
if (!reportUnusedDirectParams && param.type === 'Identifier') {···
continue;
}
✓ Negative was executed (else)
}···

var unusedNodes = getUnusedNodes(param, variableMap, reportUnusedDirectParams);
Branch LogicalExpression
✓ Was returned
if (!reportUnusedDirectParams && param.type === 'Identifier') {
✓ Was returned
if (!reportUnusedDirectParams && param.type === 'Identifier') {
if (!reportUnusedDirectParams && param.type === 'Identifier') {
continue;
}
var unusedNodes = getUnusedNodes(param, variableMap, reportUnusedDirectParams);
unusedNodes.forEach(reportError);
Branch IfStatement
✓ Positive was executed (if)
if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {···
reportUnusedDirectParams = false;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {
✓ Was returned
if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {
if (unusedNodes.length !== 1 || unusedNodes[0] !== param) {
reportUnusedDirectParams = false;
}
}
}
);
},
Function (anonymous_737)
✓ Was called
_fix: function(file, error) {···
var node = error.element;

var parentElement = node.parentElement;
if (!parentElement) {
return;
}

if (
parentElement.type === 'FunctionExpression' ||
parentElement.type === 'FunctionDeclaration' ||
parentElement.type === 'ArrowFunctionExpression'
) {
removeWithCommaIfNecessary(node, false);
return;
}

if (parentElement.type === 'ObjectProperty') {
removeWithCommaIfNecessary(parentElement, true);
return;
}

if (parentElement.type === 'ArrayPattern') {
removeWithCommaIfNecessary(node, false);
if (
parentElement.elements.length > 0 &&
parentElement.elements.every(function(element) {
return !element;
})
) {
parentElement.removeChildren(
parentElement.firstChild.nextSibling,
parentElement.lastChild.previousSibling
);
}
}
}
_fix: function(file, error) {
var node = error.element;
var parentElement = node.parentElement;
Branch IfStatement
✗ Positive was not executed (if)
if (!parentElement) {···
return;
}
✓ Negative was executed (else)
}···

if (
if (!parentElement) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
) {···
removeWithCommaIfNecessary(node, false);
return;
}
✓ Negative was executed (else)
}···

if (parentElement.type === 'ObjectProperty') {
if (
Branch LogicalExpression
✓ Was returned
parentElement.type === 'ArrowFunctionExpression'
✓ Was returned
parentElement.type === 'FunctionExpression' ||···
parentElement.type === 'FunctionDeclaration' ||
Branch LogicalExpression
✓ Was returned
parentElement.type === 'FunctionDeclaration' ||
✓ Was returned
parentElement.type === 'FunctionExpression' ||
parentElement.type === 'FunctionExpression' ||
parentElement.type === 'FunctionDeclaration' ||
parentElement.type === 'ArrowFunctionExpression'
) {
removeWithCommaIfNecessary(node, false);
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'ObjectProperty') {···
removeWithCommaIfNecessary(parentElement, true);
return;
}
✓ Negative was executed (else)
}···

if (parentElement.type === 'ArrayPattern') {
if (parentElement.type === 'ObjectProperty') {
removeWithCommaIfNecessary(parentElement, true);
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'ArrayPattern') {···
removeWithCommaIfNecessary(node, false);
if (
parentElement.elements.length > 0 &&
parentElement.elements.every(function(element) {
return !element;
})
) {
parentElement.removeChildren(
parentElement.firstChild.nextSibling,
parentElement.lastChild.previousSibling
);
}
}
✗ Negative was not executed (else)
}···
}
if (parentElement.type === 'ArrayPattern') {
removeWithCommaIfNecessary(node, false);
Branch IfStatement
✓ Positive was executed (if)
) {···
parentElement.removeChildren(
parentElement.firstChild.nextSibling,
parentElement.lastChild.previousSibling
);
}
✓ Negative was executed (else)
}···
}
if (
Branch LogicalExpression
✓ Was returned
parentElement.elements.every(function(element) {···
return !element;
})
✓ Was returned
parentElement.elements.length > 0 &&
parentElement.elements.length > 0 &&
Function (anonymous_738)
✓ Was called
parentElement.elements.every(function(element) {···
return !element;
})
parentElement.elements.every(function(element) {
return !element;
})
) {
parentElement.removeChildren(
parentElement.firstChild.nextSibling,
parentElement.lastChild.previousSibling
);
}
}
}
};
disallow-unused-variables.js
/**
* Disallows unused variables defined with var, let or const.
*
* Types: `Boolean`
*
* Values: `true`
*
* #### Example
*
* ```js
* "disallowUnusedVariables": true
* ```
*
* ##### Valid
*
* ```js
* var x=1;
*
* function getX() {
* return x;
* }
*
* ```
*
* ##### Invalid
*
* ```js
* var x=1;
*
* function getX() {
* return true;
* }
*
* ```
*/
var assert = require('assert');
Function (anonymous_739)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_740)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_741)
✓ Was called
getOptionName: function() {···
return 'disallowUnusedVariables';
},
getOptionName: function() {
return 'disallowUnusedVariables';
},
Function (anonymous_742)
✓ Was called
check: function(file, errors) {···
var program = file.getProgram();
var variableList = [];
var nodesToCheck = [];
var unusedNodes = [];

function reportError(node) {
errors.add('Variable `' + node.name + '` is not used', node);
}

function isVariableGood(variable) {
var parentCheck = function(node) {
if (node.parentElement) {
if (node.parentElement.type === 'VariableDeclaration') {
var grandparentElement = node.parentElement.parentElement;

return grandparentElement.type !== 'ExportNamedDeclaration';
} else if (
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
} else {
return false;
}
};

var useVariable = variable.getDefinitions().some(function checkVariableDefinition(definition) {
return parentCheck(definition.node);
});

return useVariable;
}

function getVariablesInAllScopes(scope) {
var variableList = [];

var iterateChildScopes = function(scope) {
scope.getVariables().forEach(function(variable) {
variableList.push(variable);
});

scope.childScopes.forEach(function(childScope) {
return iterateChildScopes(childScope);
});
};

iterateChildScopes(scope);

return variableList;
}

// Get all variables in all scopes.
variableList = getVariablesInAllScopes(file.getScopes().acquire(program));

// Check if variables are what we want to check..
variableList.reduce(function(acc, variable) {
if (isVariableGood(variable)) {
acc.push(variable);
}

return acc;
}, nodesToCheck);

// Check if variables are used.
nodesToCheck.reduce(function checkVariableReferences(acc, variable) {
if (variable.getReferences().length === 1) {
variable.getDefinitions().forEach(function addUnusedVariable(definition) {
acc.push(definition.node);
});
}

return acc;
}, unusedNodes);

unusedNodes.forEach(reportError);
},
check: function(file, errors) {
var program = file.getProgram();
var variableList = [];
var nodesToCheck = [];
var unusedNodes = [];
Function reportError
✓ Was called
function reportError(node) {···
errors.add('Variable `' + node.name + '` is not used', node);
}
function reportError(node) {
errors.add('Variable `' + node.name + '` is not used', node);
}
Function isVariableGood
✓ Was called
function isVariableGood(variable) {···
var parentCheck = function(node) {
if (node.parentElement) {
if (node.parentElement.type === 'VariableDeclaration') {
var grandparentElement = node.parentElement.parentElement;

return grandparentElement.type !== 'ExportNamedDeclaration';
} else if (
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
} else {
return false;
}
};

var useVariable = variable.getDefinitions().some(function checkVariableDefinition(definition) {
return parentCheck(definition.node);
});

return useVariable;
}
function isVariableGood(variable) {
Function (anonymous_745)
✓ Was called
var parentCheck = function(node) {···
if (node.parentElement) {
if (node.parentElement.type === 'VariableDeclaration') {
var grandparentElement = node.parentElement.parentElement;

return grandparentElement.type !== 'ExportNamedDeclaration';
} else if (
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
} else {
return false;
}
};
var parentCheck = function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.parentElement) {···
if (node.parentElement.type === 'VariableDeclaration') {
var grandparentElement = node.parentElement.parentElement;

return grandparentElement.type !== 'ExportNamedDeclaration';
} else if (
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
} else {
✗ Negative was not executed (else)
} else {···
return false;
}
if (node.parentElement) {
Branch IfStatement
✓ Positive was executed (if)
if (node.parentElement.type === 'VariableDeclaration') {···
var grandparentElement = node.parentElement.parentElement;

return grandparentElement.type !== 'ExportNamedDeclaration';
} else if (
✓ Negative was executed (else)
} else if (···
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
if (node.parentElement.type === 'VariableDeclaration') {
var grandparentElement = node.parentElement.parentElement;
return grandparentElement.type !== 'ExportNamedDeclaration';
Branch IfStatement
✓ Positive was executed (if)
) {···
return parentCheck(node.parentElement);
}
✓ Negative was executed (else)
}···
} else {
} else if (
Branch LogicalExpression
✓ Was returned
node.parentElement.isPattern
✓ Was returned
node.parentElement.type === 'VariableDeclarator' ||···
node.parentElement.type === 'ObjectProperty' ||
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'ObjectProperty' ||
✓ Was returned
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'VariableDeclarator' ||
node.parentElement.type === 'ObjectProperty' ||
node.parentElement.isPattern
) {
return parentCheck(node.parentElement);
}
} else {
return false;
}
};
Function checkVariableDefinition
✓ Was called
var useVariable = variable.getDefinitions().some(function checkVariableDefinition(definition) {···
return parentCheck(definition.node);
});
var useVariable = variable.getDefinitions().some(function checkVariableDefinition(definition) {
return parentCheck(definition.node);
});
return useVariable;
}
Function getVariablesInAllScopes
✓ Was called
function getVariablesInAllScopes(scope) {···
var variableList = [];

var iterateChildScopes = function(scope) {
scope.getVariables().forEach(function(variable) {
variableList.push(variable);
});

scope.childScopes.forEach(function(childScope) {
return iterateChildScopes(childScope);
});
};

iterateChildScopes(scope);

return variableList;
}
function getVariablesInAllScopes(scope) {
var variableList = [];
Function (anonymous_748)
✓ Was called
var iterateChildScopes = function(scope) {···
scope.getVariables().forEach(function(variable) {
variableList.push(variable);
});

scope.childScopes.forEach(function(childScope) {
return iterateChildScopes(childScope);
});
};
var iterateChildScopes = function(scope) {
Function (anonymous_749)
✓ Was called
scope.getVariables().forEach(function(variable) {···
variableList.push(variable);
});
scope.getVariables().forEach(function(variable) {
variableList.push(variable);
});
Function (anonymous_750)
✓ Was called
scope.childScopes.forEach(function(childScope) {···
return iterateChildScopes(childScope);
});
scope.childScopes.forEach(function(childScope) {
return iterateChildScopes(childScope);
});
};
iterateChildScopes(scope);
return variableList;
}
// Get all variables in all scopes.
variableList = getVariablesInAllScopes(file.getScopes().acquire(program));
// Check if variables are what we want to check..
Function (anonymous_751)
✓ Was called
variableList.reduce(function(acc, variable) {···
if (isVariableGood(variable)) {
acc.push(variable);
}

return acc;
}, nodesToCheck);
variableList.reduce(function(acc, variable) {
Branch IfStatement
✓ Positive was executed (if)
if (isVariableGood(variable)) {···
acc.push(variable);
}
✓ Negative was executed (else)
}···

return acc;
if (isVariableGood(variable)) {
acc.push(variable);
}
return acc;
}, nodesToCheck);
// Check if variables are used.
Function checkVariableReferences
✓ Was called
nodesToCheck.reduce(function checkVariableReferences(acc, variable) {···
if (variable.getReferences().length === 1) {
variable.getDefinitions().forEach(function addUnusedVariable(definition) {
acc.push(definition.node);
});
}

return acc;
}, unusedNodes);
nodesToCheck.reduce(function checkVariableReferences(acc, variable) {
Branch IfStatement
✓ Positive was executed (if)
if (variable.getReferences().length === 1) {···
variable.getDefinitions().forEach(function addUnusedVariable(definition) {
acc.push(definition.node);
});
}
✓ Negative was executed (else)
}···

return acc;
if (variable.getReferences().length === 1) {
Function addUnusedVariable
✓ Was called
variable.getDefinitions().forEach(function addUnusedVariable(definition) {···
acc.push(definition.node);
});
variable.getDefinitions().forEach(function addUnusedVariable(definition) {
acc.push(definition.node);
});
}
return acc;
}, unusedNodes);
unusedNodes.forEach(reportError);
},
Function (anonymous_754)
✓ Was called
_fix: function(file, error) {···
var node = error.element;

while (node.type !== 'VariableDeclaration') {
node = node.parentElement;
}

node.parentElement.removeChild(node);
error.fixed = true;
}
_fix: function(file, error) {
var node = error.element;
while (node.type !== 'VariableDeclaration') {
node = node.parentElement;
}
node.parentElement.removeChild(node);
error.fixed = true;
}
};
disallow-var.js
/**
* Disallows declaring variables with `var`.
*
* Types: `Boolean`
*
* Values: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "disallowVar": true
* ```
*
* ##### Valid
*
* ```js
* let foo;
* const bar;
* ```
*
* ##### Invalid
*
* ```js
* var baz;
* ```
*/
var assert = require('assert');
Function (anonymous_755)
✓ Was called
module.exports = function() { };
module.exports = function() { };
module.exports.prototype = {
Function (anonymous_756)
✓ Was called
configure: function(option) {···
assert(option === true, this.getOptionName() + ' requires a true value');
},
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},
Function (anonymous_757)
✓ Was called
getOptionName: function() {···
return 'disallowVar';
},
getOptionName: function() {
return 'disallowVar';
},
Function (anonymous_758)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('VariableDeclaration', function(node) {
for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];

if (thisDeclaration.parentElement.kind === 'var') {
errors.add('Variable declarations should use `let` or `const` not `var`', node);
}
}
});
}
check: function(file, errors) {
Function (anonymous_759)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···
for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];

if (thisDeclaration.parentElement.kind === 'var') {
errors.add('Variable declarations should use `let` or `const` not `var`', node);
}
}
});
file.iterateNodesByType('VariableDeclaration', function(node) {
for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];
Branch IfStatement
✓ Positive was executed (if)
if (thisDeclaration.parentElement.kind === 'var') {···
errors.add('Variable declarations should use `let` or `const` not `var`', node);
}
✓ Negative was executed (else)
}···
}
if (thisDeclaration.parentElement.kind === 'var') {
errors.add('Variable declarations should use `let` or `const` not `var`', node);
}
}
});
}
};
disallow-yoda-conditions.js
/**
* Requires the variable to be the left hand operator when doing a boolean comparison
*
* Type: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to disallow yoda conditions for most possible comparison operators
*
* #### Example
*
* ```js
* "disallowYodaConditions": [
* "==",
* "===",
* "!=",
* "!=="
* ]
* ```
*
* ##### Valid
*
* ```js
* if (a == 1) {
* return
* }
* ```
*
* ##### Invalid
*
* ```js
* if (1 == a) {
* return
* }
* ```
*/
var assert = require('assert');
Function (anonymous_760)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_761)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = ['==', '===', '!=', '!=='];
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = ['==', '===', '!=', '!=='];
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = ['==', '===', '!=', '!=='];
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_762)
✓ Was called
getOptionName: function() {···
return 'disallowYodaConditions';
},
getOptionName: function() {
return 'disallowYodaConditions';
},
Function (anonymous_763)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;
file.iterateNodesByType('BinaryExpression', function(node) {
if (operators[node.operator]) {
if (
node.left.type.indexOf('Literal') > -1 ||
(node.left.type === 'Identifier' && node.left.name === 'undefined')
) {
errors.add('Yoda condition', node.left);
}
}
});
}
check: function(file, errors) {
var operators = this._operatorIndex;
Function (anonymous_764)
✓ Was called
file.iterateNodesByType('BinaryExpression', function(node) {···
if (operators[node.operator]) {
if (
node.left.type.indexOf('Literal') > -1 ||
(node.left.type === 'Identifier' && node.left.name === 'undefined')
) {
errors.add('Yoda condition', node.left);
}
}
});
file.iterateNodesByType('BinaryExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (operators[node.operator]) {···
if (
node.left.type.indexOf('Literal') > -1 ||
(node.left.type === 'Identifier' && node.left.name === 'undefined')
) {
errors.add('Yoda condition', node.left);
}
}
✓ Negative was executed (else)
}···
});
if (operators[node.operator]) {
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add('Yoda condition', node.left);
}
✓ Negative was executed (else)
}···
}
if (
Branch LogicalExpression
✓ Was returned
(node.left.type === 'Identifier' && node.left.name === 'undefined')
✓ Was returned
node.left.type.indexOf('Literal') > -1 ||
node.left.type.indexOf('Literal') > -1 ||
Branch LogicalExpression
✓ Was returned
(node.left.type === 'Identifier' && node.left.name === 'undefined')
✓ Was returned
(node.left.type === 'Identifier' && node.left.name === 'undefined')
(node.left.type === 'Identifier' && node.left.name === 'undefined')
) {
errors.add('Yoda condition', node.left);
}
}
});
}
};
jsdoc.js
/**
* Validate jsdoc comments
*
* ## Usage
*
* ```json
* {
* "jsDoc": {
* "checkAnnotations": "closurecompiler",
* "checkTypes": "strictNativeCase",
* "enforceExistence": "exceptExports"
* ...
* }
* }
* ```
*
* ## Rules
*
* ### checkAnnotations
*
* Checks tag names are valid.
*
* There are 3 presets for `Closure Compiler`, `JSDoc3` and `JSDuck5`.
*
* By default it allows any tag from any preset. You can pass `Object`
* to select preset with `preset` field and add custom tags with `extra` field.
*
* Type: `Boolean` or `String` or `{"preset": String, "extra": Object}`
* (see [tag values](#user-content-tag-values)).
*
* Values: `true`, `"closurecompiler"`, `"jsdoc3"`, `"jsduck5"`, `Object`
*
* Context: `file`
*
* Tags: `*`
*
* #### Tag values
*
* `extra` field should contains tags in keys and there are options for values:
* - `false` means tag available with no value
* - `true` means tag available with any value
* - `"some"` means tag available and requires some value
*
* See also [tag presets](https://github.com/jscs-dev/jscs-jsdoc/tree/master/lib/tags).
*
* #### Example
*
* ```js
* "checkAnnotations": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @chainable
* * @param {string} message
* * @return {string}
* *\/
* function _f() {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @pororo
* * @lalala
* *\/
* function _f() {}
* ```
*
* #### Example 2
*
* ```js
* "checkAnnotations": {
* "preset": "jsdoc3",
* "extra": {
* "boomer": false
* }
* }
* ```
*
* ##### Valid
*
* ```js
* /**
* * @boomer
* * @argument {String}
* *\/
* function _f() {}
* ```
*
* ##### Invalid
*
* ```js
* /** @still-invalid *\/
* ```
*
* ### checkParamExistence
*
* Checks all parameters are documented.
*
* Type: `Boolean`
*
* Values: `true`
*
*
* #### Example
*
* ```js
* "checkParamExistence": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {string} message
* * @return {string}
* *\/
* function _f ( message ) {
* return true;
* }
*
* /**
* * @inheritdoc
* *\/
* function _f ( message ) {
* return true;
* }
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @return {string}
* *\/
* function _f ( message ) {
* return true;
* }
* ```
*
* ### checkParamNames
*
* Checks param names in jsdoc and in function declaration are equal.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `param`, `arg`, `argument`
*
* #### Example
*
* ```js
* "checkParamNames": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} message
* * @param {Number|Object} [line]
* *\/
* function method(message, line) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @param {String} msg
* * @param {Number|Object} [line]
* *\/
* function method(message) {}
* ```
*
* ### requireParamTypes
*
* Checks params in jsdoc contains type.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `param`, `arg`, `argument`
*
* #### Example
*
* ```js
* "requireParamTypes": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} message
* *\/
* function method() {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @param message
* *\/
* function method() {}
* ```
*
* ### checkRedundantParams
*
* Reports redundant params in jsdoc.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `param`, `arg`, `argument`
*
* #### Example
*
* ```js
* "checkRedundantParams": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} message
* *\/
* function method(message) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @param {String} message
* *\/
* function method() {}
* ```
*
* ### checkReturnTypes
*
* Checks for differences between the jsdoc and actual return types if both exist.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `return`, `returns`
*
* #### Example
*
* ```js
* "checkReturnTypes": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @returns {String}
* *\/
* function method() {
* return 'foo';
* }
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @returns {String}
* *\/
* function method(f) {
* if (f) {
* return true;
* }
* return 1;
* }
* ```
*
* ### checkRedundantReturns
*
* Report statements for functions without return.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `return`, `returns`
*
* #### Example
*
* ```js
* "checkRedundantReturns": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @returns {string}
* *\/
* function f() {
* return 'yes';
* }
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @returns {string}
* *\/
* function f() {
* // no return here
* }
* ```
*
* ### requireReturnTypes
*
* Checks returns in jsdoc contains type
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `return`, `returns`
*
* #### Example
*
* ```js
* "requireReturnTypes": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @returns {String}
* *\/
* function method() {}
*
* /**
* * no @return
* *\/
* function method() {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @returns
* *\/
* function method() {}
* ```
*
* ### checkTypes
*
* Reports invalid types for bunch of tags.
*
* The `strictNativeCase` mode checks that case of natives is the same as in this
* list: `boolean`, `number`, `string`, `Object`, `Array`, `Date`, `RegExp`.
*
* The `capitalizedNativeCase` mode checks that the first letter in all native
* types and primitives is uppercased except the case with `function` in google
* closure format: `{function(...)}`
*
* Type: `Boolean` or `String`
*
* Values: `true` or `"strictNativeCase"` or `"capitalizedNativeCase"`
*
* Context: `*`
*
* Tags: `typedef`, `type`, `param`, `return`, `returns`, `enum`, `var`, `prop`,
* `property`, `arg`, `argument`, `cfg`, `lends`, `extends`, `implements`, `define`
*
* #### Example
*
* ```js
* "checkTypes": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @typedef {Object} ObjectLike
* * @property {boolean} hasFlag
* * @property {string} name
* *\/
*
* /** @type {number} *\/
* var bar = 1;
*
* /** @const {number} *\/
* var FOO = 2;
*
* /**
* * @const
* * @type {number}
* *\/
* var BAZ = 3;
*
* /**
* * @param {SomeX} x
* * @returns {string}
* *\/
* function method(x) {}
* ```
*
* ##### Invalid
*
* ```js
* /** @type {some~number} *\/
* var x = 1;
*
* /**
* * @param {function(redundantName: Number)} x
* *\/
* function method(x) {}
*
* /**
* * @param {Number|Boolean|object|array} x invalid for strictNativeCase
* *\/
* function method(x) {}
* ```
*
* ```js
* /** @type {some~number} *\/
* var x = 1;
* ```
*
* ### checkRedundantAccess
*
* Reports redundant access declarations.
*
* Type: `Boolean` or `String`
*
* Values: `true` or `"enforceLeadingUnderscore"` or `"enforceTrailingUnderscore"`
*
* Context: `functions`
*
* Tags: `access`, `private`, `protected`, `public`
*
* #### Example
*
* ```js
* "checkRedundantAccess": true
* "checkRedundantAccess": "enforceLeadingUnderscore"
* ```
*
* ##### Valid for true, "enforceLeadingUnderscore"
*
* ```js
* /**
* * @access private
* *\/
* function _f() {}
*
* /**
* * @access public
* *\/
* function f() {}
* ```
*
* ##### Invalid for true
*
* ```js
* /**
* * @private
* * @access private
* *\/
* function _f() {}
* ```
*
* ##### Invalid for "enforceLeadingUnderscore"
*
* ```js
* /**
* * @private
* *\/
* function _f() {}
* ```
*
* ### leadingUnderscoreAccess
*
* Checks access declaration is set for `_underscored` function names
*
* Ignores a bunch of popular identifiers:
* `__filename`, `__dirname`, `__proto__`, `__defineGetter__`, `super_`,
* `__constructor`, etc.
*
* Type: `Boolean` or `String`
*
* Values: `true` (means not public), `"private"`, `"protected"`
*
* Context: `functions`
*
* Tags: `access`, `private`, `protected`, `public`
*
* #### Example
*
* ```js
* "leadingUnderscoreAccess": "protected"
* ```
*
* ##### Valid
*
* ```js
* /**
* * @protected
* *\/
* function _f() {}
* ```
*
* ##### Invalid
*
* ```js
* function _g() {}
*
* /**
* * @private
* *\/
* function _e() {}
* ```
*
* ### enforceExistence
*
* Checks jsdoc block exists.
*
* Type: `Boolean`, `String` or `Object`
*
* Values:
* - `true`
* - `"exceptExports"` (*deprecated* use `"allExcept": ["exports"]`)
* - `Object`:
* - `"allExcept"` array of exceptions:
* - `"expressions"` skip expression functions
* - `"exports"` skip `module.exports = function () {};`
* - `"paramless-procedures"` functions without parameters and with empty
* return statements will be skipped
*
* Context: `functions`
*
* #### Example
*
* ```js
* "enforceExistence": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @protected
* *\/
* function _f() {}
* ```
*
* ##### Invalid
*
* ```js
* function _g() {}
* ```
*
*
* ### requireHyphenBeforeDescription
*
* Checks a param description has a hyphen before it (checks for `- `).
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `param`, `arg`, `argument`
*
* #### Example
*
* ```js
* "requireHyphenBeforeDescription": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} - message
* *\/
* function method() {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @param {String} message
* *\/
* function method() {}
* ```
*
*
* ### requireNewlineAfterDescription
*
* Checks a doc comment description has padding newline.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `*`
*
* #### Example
*
* ```js
* "requireNewlineAfterDescription": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} msg - message
* *\/
* function method(msg) {}
*
* /**
* * Description
* *\/
* function method() {}
*
* /**
* * Description
* *
* * @param {String} msg - message
* *\/
* function method(msg) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * Description
* * @param {String} message
* *\/
* function method() {}
* ```
*
*
* ### disallowNewlineAfterDescription
*
* Checks a doc comment description has no padding newlines.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `*`
*
* #### Example
*
* ```js
* "disallowNewlineAfterDescription": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} msg - message
* *\/
* function method(msg) {}
*
* /**
* * Description
* *\/
* function method() {}
*
* /**
* * Description
* * @param {String} msg - message
* *\/
* function method(msg) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * Description
* *
* * @param {String} message
* *\/
* function method(message) {}
* ```
*
*
* ### requireDescriptionCompleteSentence
*
* Checks a doc comment description is a complete sentence.
*
* A complete sentence is defined as starting with an upper case letter and ending
* with a period.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `*`
*
* #### Example
*
* ```js
* "requireDescriptionCompleteSentence": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} msg - message
* *\/
* function method(msg) {}
*
* /**
* * Description.
* *\/
* function method() {}
*
* /**
* * (Description).
* *\/
* function method() {}
*
* /**
* * Description.
* *
* * @param {String} msg - message
* *\/
* function method(msg) {}
*
* /**
* * Description
* * on multiple lines are allowed.
* *
* * @param {String} msg - message
* *\/
* function method(msg) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * Description
* * @param {String} message
* *\/
* function method() {}
*
* /**
* * Description
* * On multiple lines should not start with an upper case.
* *
* * @param {String} - message
* *\/
* function method() {}
*
* /**
* * description starting with a lower case letter.
* * @param {String} message
* *\/
* function method() {}
*
* /**
* * Description period is offset .
* * @param {String} message
* *\/
* function method() {}
*
* /**
* * Description!
* * @param {String} message
* *\/
* function method() {}
* ```
*
*
* ### requireParamDescription
*
* Checks a param description exists.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `param`, `arg`, `argument`
*
* #### Example
*
* ```js
* "requireParamDescription": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @param {String} arg message
* *\/
* function method(arg) {}
*
* /**
* * @param arg message
* *\/
* function method(arg) {}
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @param {String} arg
* *\/
* function method(arg) {}
*
* /**
* * @param arg
* *\/
* function method(arg) {}
* ```
*
*
* ### requireReturnDescription
*
* Checks a return description exists.
*
* Type: `Boolean`
*
* Values: `true`
*
* Context: `functions`
*
* Tags: `return`, `returns`
*
* #### Example
*
* ```js
* "requireReturnDescription": true
* ```
*
* ##### Valid
*
* ```js
* /**
* * @returns {Boolean} Method result.
* *\/
* function method() {
* return false;
* }
*
* /**
* * @returns {String} method result
* *\/
* function method() {
* return 'Hello!';
* }
* ```
*
* ##### Invalid
*
* ```js
* /**
* * @returns {Boolean}
* *\/
* function method() {
* return false;
* }
* ```
*
*/
module.exports = require('jscs-jsdoc/lib/rules/validate-jsdoc');
maximum-line-length.js
/**
* Requires all lines to be at most the number of characters specified
*
* Types: `Integer` or `Object`
*
* Values:
* - `Integer`: lines should be at most the number of characters specified
* - `Object`:
* - `value`: (required) lines should be at most the number of characters specified
* - `tabSize`: (default: `1`) considered the tab character as number of specified spaces
* - `allExcept`: (default: `[]`) an array of conditions that will exempt a line
* - `regex`: allows regular expression literals to break the rule
* - `comments`: allows comments to break the rule
* - `urlComments`: allows comments with long urls to break the rule
* - `functionSignature`: allows function definitions to break the rule
* - `require`: allows require expressions to break the rule
* - `allowRegex`: *deprecated* use `allExcept: ["regex"]` instead
* - `allowComments`: *deprecated* use `allExcept: ["comments"]` instead
* - `allowUrlComments`: *deprecated* use `allExcept: ["urlComments"]` instead
*
* JSHint: [`maxlen`](http://jshint.com/docs/options/#maxlen)
*
* #### Example
*
* ```js
* "maximumLineLength": 40
* ```
*
* ##### Valid
*
* ```js
* var aLineOf40Chars = 123456789012345678;
* ```
*
* ##### Invalid
*
* ```js
* var aLineOf41Chars = 1234567890123456789;
* ```
*
* #### Example for allExcept functionSignature
*
* ```js
* "maximumLineLength": { "value": 40, "allExcept": [ "functionSignature" ] }
* ```
*
* ##### Valid
*
* ```js
* var f = function(with, many, _many_, arguments) { .... };
* let f = x => x * x * x * x * x * x * x * x;
* (function(foo, bar, baz, quux, cuttlefish) {
* function namesNaamesNaaamesNaaaames() {
* ...
* }
* })();
* const longNameIgnoredAsWell = (a, b) => a * b;
* class X { myLongMethodName(withPossiblyManyArgs) { ... } };
* ```
*
* ##### Invalid
*
* ```js
* function x() { // valid
* return "function_bodies_are_not_protected";
* }
* ```
*/
var assert = require('assert');
Function (anonymous_765)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_766)
✓ Was called
configure: function(maximumLineLength) {···
this._tabSize = '';
this._allowRegex = false;
this._allowComments = false;
this._allowUrlComments = false;
this._allowRequire = false;

if (typeof maximumLineLength === 'object') {
assert(
typeof maximumLineLength.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);

this._maximumLineLength = maximumLineLength.value;
var tabSize = maximumLineLength.tabSize || 0;

while (tabSize--) {
this._tabSize += ' ';
}

var exceptions = maximumLineLength.allExcept || [];
this._allowRegex = (exceptions.indexOf('regex') !== -1);
this._allowComments = (exceptions.indexOf('comments') !== -1);
this._allowUrlComments = (exceptions.indexOf('urlComments') !== -1);
this._allowFunctionSignature = (exceptions.indexOf('functionSignature') !== -1);
this._allowRequire = (exceptions.indexOf('require') !== -1);

if (maximumLineLength.hasOwnProperty('allowRegex')) {
this._allowRegex = (maximumLineLength.allowRegex === true);
}
if (maximumLineLength.hasOwnProperty('allowComments')) {
this._allowComments = (maximumLineLength.allowComments === true);
}
if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
}

} else {
assert(
typeof maximumLineLength === 'number',
this.getOptionName() + ' option requires number value or options object'
);

this._maximumLineLength = maximumLineLength;
}
},
configure: function(maximumLineLength) {
this._tabSize = '';
this._allowRegex = false;
this._allowComments = false;
this._allowUrlComments = false;
this._allowRequire = false;
Branch IfStatement
✓ Positive was executed (if)
if (typeof maximumLineLength === 'object') {···
assert(
typeof maximumLineLength.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);

this._maximumLineLength = maximumLineLength.value;
var tabSize = maximumLineLength.tabSize || 0;

while (tabSize--) {
this._tabSize += ' ';
}

var exceptions = maximumLineLength.allExcept || [];
this._allowRegex = (exceptions.indexOf('regex') !== -1);
this._allowComments = (exceptions.indexOf('comments') !== -1);
this._allowUrlComments = (exceptions.indexOf('urlComments') !== -1);
this._allowFunctionSignature = (exceptions.indexOf('functionSignature') !== -1);
this._allowRequire = (exceptions.indexOf('require') !== -1);

if (maximumLineLength.hasOwnProperty('allowRegex')) {
this._allowRegex = (maximumLineLength.allowRegex === true);
}
if (maximumLineLength.hasOwnProperty('allowComments')) {
this._allowComments = (maximumLineLength.allowComments === true);
}
if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
}

} else {
✓ Negative was executed (else)
} else {···
assert(
typeof maximumLineLength === 'number',
this.getOptionName() + ' option requires number value or options object'
);

this._maximumLineLength = maximumLineLength;
}
if (typeof maximumLineLength === 'object') {
assert(
typeof maximumLineLength.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);
this._maximumLineLength = maximumLineLength.value;
Branch LogicalExpression
✓ Was returned
var tabSize = maximumLineLength.tabSize || 0;
✓ Was returned
var tabSize = maximumLineLength.tabSize || 0;
var tabSize = maximumLineLength.tabSize || 0;
while (tabSize--) {
this._tabSize += ' ';
}
Branch LogicalExpression
✓ Was returned
var exceptions = maximumLineLength.allExcept || [];
✓ Was returned
var exceptions = maximumLineLength.allExcept || [];
var exceptions = maximumLineLength.allExcept || [];
this._allowRegex = (exceptions.indexOf('regex') !== -1);
this._allowComments = (exceptions.indexOf('comments') !== -1);
this._allowUrlComments = (exceptions.indexOf('urlComments') !== -1);
this._allowFunctionSignature = (exceptions.indexOf('functionSignature') !== -1);
this._allowRequire = (exceptions.indexOf('require') !== -1);
Branch IfStatement
✓ Positive was executed (if)
if (maximumLineLength.hasOwnProperty('allowRegex')) {···
this._allowRegex = (maximumLineLength.allowRegex === true);
}
✓ Negative was executed (else)
}···
if (maximumLineLength.hasOwnProperty('allowComments')) {
if (maximumLineLength.hasOwnProperty('allowRegex')) {
this._allowRegex = (maximumLineLength.allowRegex === true);
}
Branch IfStatement
✓ Positive was executed (if)
if (maximumLineLength.hasOwnProperty('allowComments')) {···
this._allowComments = (maximumLineLength.allowComments === true);
}
✓ Negative was executed (else)
}···
if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
if (maximumLineLength.hasOwnProperty('allowComments')) {
this._allowComments = (maximumLineLength.allowComments === true);
}
Branch IfStatement
✓ Positive was executed (if)
if (maximumLineLength.hasOwnProperty('allowUrlComments')) {···
this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
}
✓ Negative was executed (else)
}···

} else {
if (maximumLineLength.hasOwnProperty('allowUrlComments')) {
this._allowUrlComments = (maximumLineLength.allowUrlComments === true);
}
} else {
assert(
typeof maximumLineLength === 'number',
this.getOptionName() + ' option requires number value or options object'
);
this._maximumLineLength = maximumLineLength;
}
},
Function (anonymous_767)
✓ Was called
getOptionName: function() {···
return 'maximumLineLength';
},
getOptionName: function() {
return 'maximumLineLength';
},
Function (anonymous_768)
✓ Was called
check: function(file, errors) {···
var maximumLineLength = this._maximumLineLength;

var line;
var lines = this._allowComments ?
file.getLinesWithCommentsRemoved() : file.getLines();

// This check should not be destructive
lines = lines.slice();

var removeLoc = function(tokenOrNode) {

// Just in case (See #2107 for example)
if (!tokenOrNode) {
return;
}

for (var i = tokenOrNode.getLoc().start.line; i <= tokenOrNode.getLoc().end.line; i++) {
lines[i - 1] = '';
}
};

if (this._allowRegex) {
file.iterateTokensByType('RegularExpression', function(token) {
removeLoc(token);
});
}

if (this._allowUrlComments) {
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
for (var i = comment.getLoc().start.line; i <= comment.getLoc().end.line; i++) {
lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
}
});
}

if (this._allowFunctionSignature) {
file.iterateNodesByType('FunctionDeclaration', function(node) {

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});

file.iterateNodesByType('ClassMethod', function(node) {
removeLoc(node.key);
});

file.iterateNodesByType(['ArrowFunctionExpression', 'FunctionExpression'], function(node) {

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
}

if (this._allowRequire) {
file.iterateNodesByType('CallExpression', function(node) {
if (node.callee.name === 'require') {
removeLoc(node);
}
});
}

for (var i = 0, l = lines.length; i < l; i++) {
line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];

if (line.length > maximumLineLength) {
errors.add(
'Line must be at most ' + maximumLineLength + ' characters',
file.getLastTokenOnLine(i + 1, { includeComments: true })
);
}
}
}
check: function(file, errors) {
var maximumLineLength = this._maximumLineLength;
var line;
Branch ConditionalExpression
✓ Positive was returned (? ...)
file.getLinesWithCommentsRemoved() : file.getLines();
✓ Negative was returned (: ...)
file.getLinesWithCommentsRemoved() : file.getLines();
var lines = this._allowComments ?
file.getLinesWithCommentsRemoved() : file.getLines();
// This check should not be destructive
lines = lines.slice();
Function (anonymous_769)
✓ Was called
var removeLoc = function(tokenOrNode) {···

// Just in case (See #2107 for example)
if (!tokenOrNode) {
return;
}

for (var i = tokenOrNode.getLoc().start.line; i <= tokenOrNode.getLoc().end.line; i++) {
lines[i - 1] = '';
}
};
var removeLoc = function(tokenOrNode) {
// Just in case (See #2107 for example)
Branch IfStatement
✓ Positive was executed (if)
if (!tokenOrNode) {···
return;
}
✓ Negative was executed (else)
}···

for (var i = tokenOrNode.getLoc().start.line; i <= tokenOrNode.getLoc().end.line; i++) {
if (!tokenOrNode) {
return;
}
for (var i = tokenOrNode.getLoc().start.line; i <= tokenOrNode.getLoc().end.line; i++) {
lines[i - 1] = '';
}
};
Branch IfStatement
✓ Positive was executed (if)
if (this._allowRegex) {···
file.iterateTokensByType('RegularExpression', function(token) {
removeLoc(token);
});
}
✓ Negative was executed (else)
}···

if (this._allowUrlComments) {
if (this._allowRegex) {
Function (anonymous_770)
✓ Was called
file.iterateTokensByType('RegularExpression', function(token) {···
removeLoc(token);
});
file.iterateTokensByType('RegularExpression', function(token) {
removeLoc(token);
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._allowUrlComments) {···
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
for (var i = comment.getLoc().start.line; i <= comment.getLoc().end.line; i++) {
lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
}
});
}
✓ Negative was executed (else)
}···

if (this._allowFunctionSignature) {
if (this._allowUrlComments) {
Function (anonymous_771)
✓ Was called
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {···
for (var i = comment.getLoc().start.line; i <= comment.getLoc().end.line; i++) {
lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
}
});
file.iterateTokensByType(['CommentLine', 'CommentBlock'], function(comment) {
for (var i = comment.getLoc().start.line; i <= comment.getLoc().end.line; i++) {
lines[i - 1] = lines[i - 1].replace(/(http|https|ftp):\/\/[^\s$]+/, '');
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._allowFunctionSignature) {···
file.iterateNodesByType('FunctionDeclaration', function(node) {

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});

file.iterateNodesByType('ClassMethod', function(node) {
removeLoc(node.key);
});

file.iterateNodesByType(['ArrowFunctionExpression', 'FunctionExpression'], function(node) {

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
}
✓ Negative was executed (else)
}···

if (this._allowRequire) {
if (this._allowFunctionSignature) {
Function (anonymous_772)
✓ Was called
file.iterateNodesByType('FunctionDeclaration', function(node) {···

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
file.iterateNodesByType('FunctionDeclaration', function(node) {
// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
Function (anonymous_773)
✓ Was called
file.iterateNodesByType('ClassMethod', function(node) {···
removeLoc(node.key);
});
file.iterateNodesByType('ClassMethod', function(node) {
removeLoc(node.key);
});
Function (anonymous_774)
✓ Was called
file.iterateNodesByType(['ArrowFunctionExpression', 'FunctionExpression'], function(node) {···

// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
file.iterateNodesByType(['ArrowFunctionExpression', 'FunctionExpression'], function(node) {
// Need to remove the first line, because we can't be sure there's any id or params
lines[node.getLoc().start.line - 1] = '';
removeLoc(node.id);
node.params.forEach(removeLoc);
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._allowRequire) {···
file.iterateNodesByType('CallExpression', function(node) {
if (node.callee.name === 'require') {
removeLoc(node);
}
});
}
✓ Negative was executed (else)
}···

for (var i = 0, l = lines.length; i < l; i++) {
if (this._allowRequire) {
Function (anonymous_775)
✓ Was called
file.iterateNodesByType('CallExpression', function(node) {···
if (node.callee.name === 'require') {
removeLoc(node);
}
});
file.iterateNodesByType('CallExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.callee.name === 'require') {···
removeLoc(node);
}
✗ Negative was not executed (else)
}···
});
if (node.callee.name === 'require') {
removeLoc(node);
}
});
}
for (var i = 0, l = lines.length; i < l; i++) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];
✓ Negative was returned (: ...)
line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];
line = this._tabSize ? lines[i].replace(/\t/g, this._tabSize) : lines[i];
Branch IfStatement
✓ Positive was executed (if)
if (line.length > maximumLineLength) {···
errors.add(
'Line must be at most ' + maximumLineLength + ' characters',
file.getLastTokenOnLine(i + 1, { includeComments: true })
);
}
✓ Negative was executed (else)
}···
}
if (line.length > maximumLineLength) {
errors.add(
'Line must be at most ' + maximumLineLength + ' characters',
file.getLastTokenOnLine(i + 1, { includeComments: true })
);
}
}
}
};
maximum-number-of-lines.js
/**
* Requires the file to be at most the number of lines specified
*
* Types: `Integer` or `Object`
*
* Values:
* - `Integer`: file should be at most the number of lines specified
* - `Object`:
* - `value`: (required) lines should be at most the number of characters specified
* - `allExcept`: (default: `[]`) an array of conditions that will exempt a line
* - `comments`: allows comments to break the rule
*
* #### Example
*
* ```js
* "maximumNumberOfLines": 100
* ```
*/
var assert = require('assert');
Function (anonymous_776)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_777)
✓ Was called
configure: function(options) {···
this._allowComments = true;

if (typeof options === 'number') {
assert(
typeof options === 'number',
this.getOptionName() + ' option requires number value or options object'
);
this._maximumNumberOfLines = options;
} else {
assert(
typeof options.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);
this._maximumNumberOfLines = options.value;

var exceptions = options.allExcept || [];
this._allowComments = (exceptions.indexOf('comments') === -1);
}
},
configure: function(options) {
this._allowComments = true;
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'number') {···
assert(
typeof options === 'number',
this.getOptionName() + ' option requires number value or options object'
);
this._maximumNumberOfLines = options;
} else {
✓ Negative was executed (else)
} else {···
assert(
typeof options.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);
this._maximumNumberOfLines = options.value;

var exceptions = options.allExcept || [];
this._allowComments = (exceptions.indexOf('comments') === -1);
}
if (typeof options === 'number') {
assert(
typeof options === 'number',
this.getOptionName() + ' option requires number value or options object'
);
this._maximumNumberOfLines = options;
} else {
assert(
typeof options.value === 'number',
this.getOptionName() + ' option requires the "value" property to be defined'
);
this._maximumNumberOfLines = options.value;
Branch LogicalExpression
✓ Was returned
var exceptions = options.allExcept || [];
✓ Was returned
var exceptions = options.allExcept || [];
var exceptions = options.allExcept || [];
this._allowComments = (exceptions.indexOf('comments') === -1);
}
},
Function (anonymous_778)
✓ Was called
getOptionName: function() {···
return 'maximumNumberOfLines';
},
getOptionName: function() {
return 'maximumNumberOfLines';
},
Function (anonymous_779)
✓ Was called
check: function(file, errors) {···
var firstToken = file.getFirstToken({includeComments: true});
var lines = this._allowComments ?
file.getLines() : file.getLinesWithCommentsRemoved();

lines = lines.filter(function(line) {return line !== '';});

if (lines.length > this._maximumNumberOfLines) {
errors.add(
'File must be at most ' + this._maximumNumberOfLines + ' lines long',
firstToken,
firstToken.value.length
);
}
}
check: function(file, errors) {
var firstToken = file.getFirstToken({includeComments: true});
Branch ConditionalExpression
✓ Positive was returned (? ...)
file.getLines() : file.getLinesWithCommentsRemoved();
✓ Negative was returned (: ...)
file.getLines() : file.getLinesWithCommentsRemoved();
var lines = this._allowComments ?
file.getLines() : file.getLinesWithCommentsRemoved();
Function (anonymous_780)
✓ Was called
lines = lines.filter(function(line) {return line !== '';});
lines = lines.filter(function(line) {return line !== '';});
Branch IfStatement
✓ Positive was executed (if)
if (lines.length > this._maximumNumberOfLines) {···
errors.add(
'File must be at most ' + this._maximumNumberOfLines + ' lines long',
firstToken,
firstToken.value.length
);
}
✓ Negative was executed (else)
}···
}
if (lines.length > this._maximumNumberOfLines) {
errors.add(
'File must be at most ' + this._maximumNumberOfLines + ' lines long',
firstToken,
firstToken.value.length
);
}
}
};
require-aligned-multiline-params.js
/**
* Enforces indentation of parameters in multiline functions
*
* Types: `Boolean`, `String`, `Number`
*
* Values:
* - `true` to require parameters are aligned with the body of the function
* - `'firstParam'` to require parameters to be aligned with the first parameter
* - `Number` for the number of columns the parameters should be indented past the function body
*
* #### Example
*
* ```js
* "requireAlignedMultilineParams": true
* ```
*
* ##### Valid for `true`
*
* ```js
* var test = function(one, two,
* three, four, five,
* six, seven, eight) {
* console.log(a);
* };
* ```
*
* ##### Valid for `2`
*
* ```js
* var test = function(one, two,
* three, four, five,
* six, seven, eight) {
* console.log(a);
* };
* ```
*
* ##### Valid for `'firstParam'`
*
* ```js
* var test = function(one, two,
* three, four, five,
* six, seven, eight) {
* console.log(a);
* };
* ```
*
* ##### Invalid for `0`
*
* ```js
* var test = function(one, two,
* three, four, five,
* six, seven, eight) {
* console.log(a);
* };
* ```
*
*/
var assert = require('assert');
Function getNodeColumn
✓ Was called
function getNodeColumn(node) {···
var currentToken = node.getFirstToken().getPreviousToken();
var indentationLevel = 0;
while (currentToken) {
if (currentToken.getNewlineCount() > 0) {
var sourceCodeLines = currentToken.getSourceCodeLines();
indentationLevel += sourceCodeLines[sourceCodeLines.length - 1].length;
break;
}

indentationLevel += currentToken.getSourceCodeLength();

currentToken = currentToken.getPreviousToken();
}
return indentationLevel;
}
function getNodeColumn(node) {
var currentToken = node.getFirstToken().getPreviousToken();
var indentationLevel = 0;
while (currentToken) {
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.getNewlineCount() > 0) {···
var sourceCodeLines = currentToken.getSourceCodeLines();
indentationLevel += sourceCodeLines[sourceCodeLines.length - 1].length;
break;
}
✓ Negative was executed (else)
}···

indentationLevel += currentToken.getSourceCodeLength();
if (currentToken.getNewlineCount() > 0) {
var sourceCodeLines = currentToken.getSourceCodeLines();
indentationLevel += sourceCodeLines[sourceCodeLines.length - 1].length;
break;
}
indentationLevel += currentToken.getSourceCodeLength();
currentToken = currentToken.getPreviousToken();
}
return indentationLevel;
}
Function (anonymous_782)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_783)
✓ Was called
configure: function(option) {···
if (typeof option === 'number') {
this._indentationLevel = option;
} else if (typeof option === 'string') {
assert(
option === 'firstParam',
this.getOptionName() + ' option requires string value to be "firstParam"'
);

this._alignWithFirstParam = true;
} else if (option === true) {
this._indentationLevel = 0;
} else {
assert(
false,
this.getOptionName() + ' option requires a valid option'
);
}
},
configure: function(option) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof option === 'number') {···
this._indentationLevel = option;
} else if (typeof option === 'string') {
✓ Negative was executed (else)
} else if (typeof option === 'string') {···
assert(
option === 'firstParam',
this.getOptionName() + ' option requires string value to be "firstParam"'
);

this._alignWithFirstParam = true;
} else if (option === true) {
this._indentationLevel = 0;
} else {
assert(
false,
this.getOptionName() + ' option requires a valid option'
);
}
if (typeof option === 'number') {
this._indentationLevel = option;
Branch IfStatement
✓ Positive was executed (if)
} else if (typeof option === 'string') {···
assert(
option === 'firstParam',
this.getOptionName() + ' option requires string value to be "firstParam"'
);

this._alignWithFirstParam = true;
} else if (option === true) {
✓ Negative was executed (else)
} else if (option === true) {···
this._indentationLevel = 0;
} else {
assert(
false,
this.getOptionName() + ' option requires a valid option'
);
}
} else if (typeof option === 'string') {
assert(
option === 'firstParam',
this.getOptionName() + ' option requires string value to be "firstParam"'
);
this._alignWithFirstParam = true;
Branch IfStatement
✓ Positive was executed (if)
} else if (option === true) {···
this._indentationLevel = 0;
} else {
✓ Negative was executed (else)
} else {···
assert(
false,
this.getOptionName() + ' option requires a valid option'
);
}
} else if (option === true) {
this._indentationLevel = 0;
} else {
assert(
false,
this.getOptionName() + ' option requires a valid option'
);
}
},
Function (anonymous_784)
✓ Was called
getOptionName: function() {···
return 'requireAlignedMultilineParams';
},
getOptionName: function() {
return 'requireAlignedMultilineParams';
},
Function (anonymous_785)
✓ Was called
check: function(file, errors) {···
var _this = this;
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
var params = node.params;

// We can pass the check if there's no params
if (params.length === 0) {
return;
}

var firstParam = params[0];
var referenceColumn;
var body;

if (_this._alignWithFirstParam) {
referenceColumn = getNodeColumn(firstParam);
} else {

body = node.body.body[0];

// If function doesn't have a body just bail out (#1988)
if (!body) {
return;
}

referenceColumn = body.getLoc().start.column + _this._indentationLevel;
}

var previousParam = firstParam;
params.slice(1).forEach(function(param) {
if (!file.isOnTheSameLine(previousParam, param)) {
var paramColumn = getNodeColumn(param);
if (paramColumn !== referenceColumn) {
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}

previousParam = param;
}
});

});
}
check: function(file, errors) {
var _this = this;
Function (anonymous_786)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···
var params = node.params;

// We can pass the check if there's no params
if (params.length === 0) {
return;
}

var firstParam = params[0];
var referenceColumn;
var body;

if (_this._alignWithFirstParam) {
referenceColumn = getNodeColumn(firstParam);
} else {

body = node.body.body[0];

// If function doesn't have a body just bail out (#1988)
if (!body) {
return;
}

referenceColumn = body.getLoc().start.column + _this._indentationLevel;
}

var previousParam = firstParam;
params.slice(1).forEach(function(param) {
if (!file.isOnTheSameLine(previousParam, param)) {
var paramColumn = getNodeColumn(param);
if (paramColumn !== referenceColumn) {
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}

previousParam = param;
}
});

});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
var params = node.params;
// We can pass the check if there's no params
Branch IfStatement
✓ Positive was executed (if)
if (params.length === 0) {···
return;
}
✓ Negative was executed (else)
}···

var firstParam = params[0];
if (params.length === 0) {
return;
}
var firstParam = params[0];
var referenceColumn;
var body;
Branch IfStatement
✓ Positive was executed (if)
if (_this._alignWithFirstParam) {···
referenceColumn = getNodeColumn(firstParam);
} else {
✓ Negative was executed (else)
} else {···

body = node.body.body[0];

// If function doesn't have a body just bail out (#1988)
if (!body) {
return;
}

referenceColumn = body.getLoc().start.column + _this._indentationLevel;
}
if (_this._alignWithFirstParam) {
referenceColumn = getNodeColumn(firstParam);
} else {
body = node.body.body[0];
// If function doesn't have a body just bail out (#1988)
Branch IfStatement
✓ Positive was executed (if)
if (!body) {···
return;
}
✓ Negative was executed (else)
}···

referenceColumn = body.getLoc().start.column + _this._indentationLevel;
if (!body) {
return;
}
referenceColumn = body.getLoc().start.column + _this._indentationLevel;
}
var previousParam = firstParam;
Function (anonymous_787)
✓ Was called
params.slice(1).forEach(function(param) {···
if (!file.isOnTheSameLine(previousParam, param)) {
var paramColumn = getNodeColumn(param);
if (paramColumn !== referenceColumn) {
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}

previousParam = param;
}
});
params.slice(1).forEach(function(param) {
Branch IfStatement
✓ Positive was executed (if)
if (!file.isOnTheSameLine(previousParam, param)) {···
var paramColumn = getNodeColumn(param);
if (paramColumn !== referenceColumn) {
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}

previousParam = param;
}
✓ Negative was executed (else)
}···
});
if (!file.isOnTheSameLine(previousParam, param)) {
var paramColumn = getNodeColumn(param);
Branch IfStatement
✓ Positive was executed (if)
if (paramColumn !== referenceColumn) {···
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}
✓ Negative was executed (else)
}···

previousParam = param;
if (paramColumn !== referenceColumn) {
errors.assert.indentation({
token: param.getFirstToken(),
actual: paramColumn,
expected: referenceColumn,
indentChar: ' '
});
}
previousParam = param;
}
});
});
}
};
require-aligned-object-values.js
/**
* Requires proper alignment in object literals.
*
* Type: `String`
*
* Values:
* - `"all"` for strict mode,
* - `"ignoreFunction"` ignores objects if one of the property values is a function expression,
* - `"ignoreLineBreak"` ignores objects if there are line breaks between properties
*
* #### Example
*
* ```js
* "requireAlignedObjectValues": "all"
* ```
*
* ##### Valid
* ```js
* var x = {
* a : 1,
* bcd : 2,
* ef : 'str'
* };
* ```
* ##### Invalid
* ```js
* var x = {
* a : 1,
* bcd : 2,
* ef : 'str'
* };
* ```
*/
var assert = require('assert');
Function (anonymous_788)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_789)
✓ Was called
configure: function(mode) {···
var modes = {
'all': 'all',
'ignoreFunction': 'ignoreFunction',
'ignoreLineBreak': 'ignoreLineBreak',
'skipWithFunction': 'ignoreFunction',
'skipWithLineBreak': 'ignoreLineBreak'
};
assert(
typeof mode === 'string' && modes[mode],
this.getOptionName() + ' requires one of the following values: ' + Object.keys(modes).join(', ')
);
this._mode = modes[mode];
},
configure: function(mode) {
var modes = {
'all': 'all',
'ignoreFunction': 'ignoreFunction',
'ignoreLineBreak': 'ignoreLineBreak',
'skipWithFunction': 'ignoreFunction',
'skipWithLineBreak': 'ignoreLineBreak'
};
assert(
Branch LogicalExpression
✓ Was returned
typeof mode === 'string' && modes[mode],
✗ Was not returned
typeof mode === 'string' && modes[mode],
typeof mode === 'string' && modes[mode],
this.getOptionName() + ' requires one of the following values: ' + Object.keys(modes).join(', ')
);
this._mode = modes[mode];
},
Function (anonymous_790)
✓ Was called
getOptionName: function() {···
return 'requireAlignedObjectValues';
},
getOptionName: function() {
return 'requireAlignedObjectValues';
},
Function (anonymous_791)
✓ Was called
check: function(file, errors) {···
var mode = this._mode;

file.iterateNodesByType('ObjectExpression', function(node) {
if (node.getNewlineCount() === 0 || node.properties < 2) {
return;
}

var maxKeyEndPos = 0;
var prevKeyEndPos = 0;
var minColonPos = 0;
var tokens = [];
var skip = node.properties.some(function(property, index) {
if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return true;
}

if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
return true;
}

if (mode === 'ignoreLineBreak' && index > 0 &&
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {
return true;
}

prevKeyEndPos = maxKeyEndPos;
maxKeyEndPos = Math.max(maxKeyEndPos, property.key.getLoc().end.column);
var keyToken = file.getFirstNodeToken(property.key);
if (property.computed === true) {
while (keyToken.value !== ']') {
keyToken = file.getNextToken(keyToken);
}
}
var colon = file.getNextToken(keyToken);
if (prevKeyEndPos < maxKeyEndPos) {
minColonPos = colon.getLoc().start.column;
}
tokens.push({key: keyToken, colon: colon});
});

if (skip) {
return;
}

var space = minColonPos - maxKeyEndPos;
tokens.forEach(function(pair) {
errors.assert.spacesBetween({
token: pair.key,
nextToken: pair.colon,
exactly: maxKeyEndPos - pair.key.getLoc().end.column + space,
message: 'Alignment required'
});
});
});
}
check: function(file, errors) {
var mode = this._mode;
Function (anonymous_792)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
if (node.getNewlineCount() === 0 || node.properties < 2) {
return;
}

var maxKeyEndPos = 0;
var prevKeyEndPos = 0;
var minColonPos = 0;
var tokens = [];
var skip = node.properties.some(function(property, index) {
if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return true;
}

if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
return true;
}

if (mode === 'ignoreLineBreak' && index > 0 &&
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {
return true;
}

prevKeyEndPos = maxKeyEndPos;
maxKeyEndPos = Math.max(maxKeyEndPos, property.key.getLoc().end.column);
var keyToken = file.getFirstNodeToken(property.key);
if (property.computed === true) {
while (keyToken.value !== ']') {
keyToken = file.getNextToken(keyToken);
}
}
var colon = file.getNextToken(keyToken);
if (prevKeyEndPos < maxKeyEndPos) {
minColonPos = colon.getLoc().start.column;
}
tokens.push({key: keyToken, colon: colon});
});

if (skip) {
return;
}

var space = minColonPos - maxKeyEndPos;
tokens.forEach(function(pair) {
errors.assert.spacesBetween({
token: pair.key,
nextToken: pair.colon,
exactly: maxKeyEndPos - pair.key.getLoc().end.column + space,
message: 'Alignment required'
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.getNewlineCount() === 0 || node.properties < 2) {···
return;
}
✓ Negative was executed (else)
}···

var maxKeyEndPos = 0;
Branch LogicalExpression
✓ Was returned
if (node.getNewlineCount() === 0 || node.properties < 2) {
✓ Was returned
if (node.getNewlineCount() === 0 || node.properties < 2) {
if (node.getNewlineCount() === 0 || node.properties < 2) {
return;
}
var maxKeyEndPos = 0;
var prevKeyEndPos = 0;
var minColonPos = 0;
var tokens = [];
Function (anonymous_793)
✓ Was called
var skip = node.properties.some(function(property, index) {···
if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return true;
}

if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
return true;
}

if (mode === 'ignoreLineBreak' && index > 0 &&
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {
return true;
}

prevKeyEndPos = maxKeyEndPos;
maxKeyEndPos = Math.max(maxKeyEndPos, property.key.getLoc().end.column);
var keyToken = file.getFirstNodeToken(property.key);
if (property.computed === true) {
while (keyToken.value !== ']') {
keyToken = file.getNextToken(keyToken);
}
}
var colon = file.getNextToken(keyToken);
if (prevKeyEndPos < maxKeyEndPos) {
minColonPos = colon.getLoc().start.column;
}
tokens.push({key: keyToken, colon: colon});
});
var skip = node.properties.some(function(property, index) {
Branch IfStatement
✓ Positive was executed (if)
property.type === 'SpreadProperty') {···
return true;
}
✓ Negative was executed (else)
}···

if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
Branch LogicalExpression
✓ Was returned
property.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand || property.method ||
Branch LogicalExpression
✓ Was returned
if (property.shorthand || property.method ||
✓ Was returned
if (property.shorthand || property.method ||
if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {···
return true;
}
✓ Negative was executed (else)
}···

if (mode === 'ignoreLineBreak' && index > 0 &&
Branch LogicalExpression
✓ Was returned
if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
✓ Was returned
if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
if (mode === 'ignoreFunction' && property.value.type === 'FunctionExpression') {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {···
return true;
}
✓ Negative was executed (else)
}···

prevKeyEndPos = maxKeyEndPos;
Branch LogicalExpression
✓ Was returned
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {
✓ Was returned
if (mode === 'ignoreLineBreak' && index > 0 &&
Branch LogicalExpression
✓ Was returned
if (mode === 'ignoreLineBreak' && index > 0 &&
✓ Was returned
if (mode === 'ignoreLineBreak' && index > 0 &&
if (mode === 'ignoreLineBreak' && index > 0 &&
node.properties[index - 1].getLoc().end.line !== property.getLoc().start.line - 1) {
return true;
}
prevKeyEndPos = maxKeyEndPos;
maxKeyEndPos = Math.max(maxKeyEndPos, property.key.getLoc().end.column);
var keyToken = file.getFirstNodeToken(property.key);
Branch IfStatement
✓ Positive was executed (if)
if (property.computed === true) {···
while (keyToken.value !== ']') {
keyToken = file.getNextToken(keyToken);
}
}
✓ Negative was executed (else)
}···
var colon = file.getNextToken(keyToken);
if (property.computed === true) {
while (keyToken.value !== ']') {
keyToken = file.getNextToken(keyToken);
}
}
var colon = file.getNextToken(keyToken);
Branch IfStatement
✓ Positive was executed (if)
if (prevKeyEndPos < maxKeyEndPos) {···
minColonPos = colon.getLoc().start.column;
}
✓ Negative was executed (else)
}···
tokens.push({key: keyToken, colon: colon});
if (prevKeyEndPos < maxKeyEndPos) {
minColonPos = colon.getLoc().start.column;
}
tokens.push({key: keyToken, colon: colon});
});
Branch IfStatement
✓ Positive was executed (if)
if (skip) {···
return;
}
✓ Negative was executed (else)
}···

var space = minColonPos - maxKeyEndPos;
if (skip) {
return;
}
var space = minColonPos - maxKeyEndPos;
Function (anonymous_794)
✓ Was called
tokens.forEach(function(pair) {···
errors.assert.spacesBetween({
token: pair.key,
nextToken: pair.colon,
exactly: maxKeyEndPos - pair.key.getLoc().end.column + space,
message: 'Alignment required'
});
});
tokens.forEach(function(pair) {
errors.assert.spacesBetween({
token: pair.key,
nextToken: pair.colon,
exactly: maxKeyEndPos - pair.key.getLoc().end.column + space,
message: 'Alignment required'
});
});
});
}
};
require-anonymous-functions.js
/**
* Requires that a function expression be anonymous.
*
* Type: `Boolean`
*
* Values:
* - `true`
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'declarations'` ignores function declarations
*
* #### Example
*
* ```js
* "requireAnonymousFunctions": true
* ```
*
* ##### Valid
*
* ```js
* var a = function() {
*
* };
*
* $('#foo').click(function() {
*
* })
* ```
*
* ##### Invalid
*
* ```js
* var a = function foo() {
*
* };
*
* $('#foo').click(function bar() {
*
* });
* ```
*
* ##### Valid for `{ "allExcept": ["declarations"] }`
*
* ```js
* function foo() {
*
* }
*
* $('#foo').click(function() {
*
* })
* ```
*
*/
var assert = require('assert');
Function (anonymous_795)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_796)
✓ Was called
configure: function(options) {···
var optionName = this.getOptionName();

if (typeof options === 'object') {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
' item or be set to `true`');
this._exceptDeclarations = options.allExcept.indexOf('declarations') > -1;
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value or an object');
}
},
configure: function(options) {
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
' item or be set to `true`');
this._exceptDeclarations = options.allExcept.indexOf('declarations') > -1;
} else {
✓ Negative was executed (else)
} else {···
assert(options === true, this.getOptionName() + ' option requires either a true value or an object');
}
if (typeof options === 'object') {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
' item or be set to `true`');
this._exceptDeclarations = options.allExcept.indexOf('declarations') > -1;
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value or an object');
}
},
Function (anonymous_797)
✓ Was called
getOptionName: function() {···
return 'requireAnonymousFunctions';
},
getOptionName: function() {
return 'requireAnonymousFunctions';
},
Function (anonymous_798)
✓ Was called
check: function(file, errors) {···
var exceptDeclarations = this._exceptDeclarations;

file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {
if (exceptDeclarations && node.type === 'FunctionDeclaration') {
return;
}
if (node.id !== null) {
errors.add('Functions must not be named', node);
}
});
}
check: function(file, errors) {
var exceptDeclarations = this._exceptDeclarations;
Function (anonymous_799)
✓ Was called
file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {···
if (exceptDeclarations && node.type === 'FunctionDeclaration') {
return;
}
if (node.id !== null) {
errors.add('Functions must not be named', node);
}
});
file.iterateNodesByType(['FunctionExpression', 'FunctionDeclaration'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (exceptDeclarations && node.type === 'FunctionDeclaration') {···
return;
}
✓ Negative was executed (else)
}···
if (node.id !== null) {
Branch LogicalExpression
✓ Was returned
if (exceptDeclarations && node.type === 'FunctionDeclaration') {
✓ Was returned
if (exceptDeclarations && node.type === 'FunctionDeclaration') {
if (exceptDeclarations && node.type === 'FunctionDeclaration') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (node.id !== null) {···
errors.add('Functions must not be named', node);
}
✓ Negative was executed (else)
}···
});
if (node.id !== null) {
errors.add('Functions must not be named', node);
}
});
}
};
require-array-destructuring.js
/**
* Requires that variable assignment from array values are * destructured.
*
* Type: `Boolean`
*
* Values: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireArrayDestructuring": true
* ```
*
* ##### Valid
*
* ```js
* var colors = ['red', 'green', 'blue'];
* var [ red ] = colors;
*
* var attributes = {
* colors: ['red', 'green', 'blue'];
* };
*
* var [ red ] = attributes.colors;
* ```
*
* ##### Invalid
*
* ```js
* var colors = ['red', 'green', 'blue'];
* var red = colors[0];
*
* var attributes = {
* colors: ['red', 'green', 'blue'];
* };
*
* var red = attributes.colors[0];
* ```
*/
var assert = require('assert');
Function (anonymous_800)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_801)
✓ Was called
configure: function(option) {···
assert(option === true, this.getOptionName() + ' requires a true value');
},
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},
Function (anonymous_802)
✓ Was called
getOptionName: function() {···
return 'requireArrayDestructuring';
},
getOptionName: function() {
return 'requireArrayDestructuring';
},
Function (anonymous_803)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('VariableDeclaration', function(node) {

node.declarations.forEach(function(declaration) {
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
return;
}

var property = declaration.init.property || {};
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
errors.add('Use array destructuring', property);
}
});
});
}
check: function(file, errors) {
Function (anonymous_804)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···

node.declarations.forEach(function(declaration) {
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
return;
}

var property = declaration.init.property || {};
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
errors.add('Use array destructuring', property);
}
});
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Function (anonymous_805)
✓ Was called
node.declarations.forEach(function(declaration) {···
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
return;
}

var property = declaration.init.property || {};
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
errors.add('Use array destructuring', property);
}
});
node.declarations.forEach(function(declaration) {
Branch IfStatement
✓ Positive was executed (if)
if (!declaration.init || declaration.init.type !== 'MemberExpression') {···
return;
}
✓ Negative was executed (else)
}···

var property = declaration.init.property || {};
Branch LogicalExpression
✓ Was returned
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
✗ Was not returned
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
if (!declaration.init || declaration.init.type !== 'MemberExpression') {
return;
}
Branch LogicalExpression
✗ Was not returned
var property = declaration.init.property || {};
✓ Was returned
var property = declaration.init.property || {};
var property = declaration.init.property || {};
Branch IfStatement
✓ Positive was executed (if)
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {···
errors.add('Use array destructuring', property);
}
✗ Negative was not executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
✗ Was not returned
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
if (property.type.indexOf('Literal') > -1 && /^\d+$/.test(property.value)) {
errors.add('Use array destructuring', property);
}
});
});
}
};
require-arrow-functions.js
/**
* Requires that arrow functions are used instead of anonymous function expressions in callbacks.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireArrowFunctions": true
* ```
*
* ##### Valid
*
* ```js
* // arrow function
* [1, 2, 3].map((x) => {
* return x * x;
* });
* // function declaration
* function a(n) { return n + 1; }
* // getter/setter
* var x = { get y() {}, set y(y) {} }
* // object shorthand
* var x = { bar() {} }
* // class method
* class Foo { bar() {} }
* // function expression in a return statement
* function a(x) {
* return function(x) { return x };
* };
* // function expression in a variable declaration
* var a = function(x) { return x };
* ```
*
* ##### Invalid
*
* ```js
* // function expression in a callback
* [1, 2, 3].map(function (x) {
* return x * x;
* });
* ```
*/
var assert = require('assert');
Function (anonymous_806)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_807)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_808)
✓ Was called
getOptionName: function() {···
return 'requireArrowFunctions';
},
getOptionName: function() {
return 'requireArrowFunctions';
},
Function (anonymous_809)
✓ Was called
check: function(file, errors) {···

function isCallback(node) {
return node.type === 'FunctionExpression' && node.parentElement.type === 'CallExpression';
}

function isFunctionBindWithThis(node) {
return node.callee &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
node.arguments &&
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
}

file.iterateNodesByType(['FunctionExpression', 'CallExpression'], function(node) {
if (isCallback(node) || isFunctionBindWithThis(node)) {
errors.add('Use arrow functions instead of function expressions', node);
}

});
}
check: function(file, errors) {
Function isCallback
✓ Was called
function isCallback(node) {···
return node.type === 'FunctionExpression' && node.parentElement.type === 'CallExpression';
}
function isCallback(node) {
Branch LogicalExpression
✓ Was returned
return node.type === 'FunctionExpression' && node.parentElement.type === 'CallExpression';
✓ Was returned
return node.type === 'FunctionExpression' && node.parentElement.type === 'CallExpression';
return node.type === 'FunctionExpression' && node.parentElement.type === 'CallExpression';
}
Function isFunctionBindWithThis
✓ Was called
function isFunctionBindWithThis(node) {···
return node.callee &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
node.arguments &&
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
}
function isFunctionBindWithThis(node) {
Branch LogicalExpression
✗ Was not returned
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
node.arguments &&
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
Branch LogicalExpression
✗ Was not returned
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
node.arguments &&
Branch LogicalExpression
✗ Was not returned
node.arguments &&
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
Branch LogicalExpression
✗ Was not returned
node.callee.property.name === 'bind' &&
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
Branch LogicalExpression
✗ Was not returned
node.callee.property.type === 'Identifier' &&
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
Branch LogicalExpression
✓ Was returned
node.callee.object.type === 'FunctionExpression' &&
✓ Was returned
return node.callee &&···
node.callee.type === 'MemberExpression' &&
Branch LogicalExpression
✓ Was returned
node.callee.type === 'MemberExpression' &&
✓ Was returned
return node.callee &&
return node.callee &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'FunctionExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'bind' &&
node.arguments &&
node.arguments.length === 1 && node.arguments[0].type === 'ThisExpression';
}
Function (anonymous_812)
✓ Was called
file.iterateNodesByType(['FunctionExpression', 'CallExpression'], function(node) {···
if (isCallback(node) || isFunctionBindWithThis(node)) {
errors.add('Use arrow functions instead of function expressions', node);
}

});
file.iterateNodesByType(['FunctionExpression', 'CallExpression'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isCallback(node) || isFunctionBindWithThis(node)) {···
errors.add('Use arrow functions instead of function expressions', node);
}
✓ Negative was executed (else)
}···

});
Branch LogicalExpression
✓ Was returned
if (isCallback(node) || isFunctionBindWithThis(node)) {
✓ Was returned
if (isCallback(node) || isFunctionBindWithThis(node)) {
if (isCallback(node) || isFunctionBindWithThis(node)) {
errors.add('Use arrow functions instead of function expressions', node);
}
});
}
};
require-blocks-on-newline.js
/**
* Requires blocks to begin and end with a newline
*
* Types: `Boolean`, `Integer`, `Object`
*
* Values:
* - `true` validates all non-empty blocks
* - `Integer` specifies a minimum number of lines containing elements in the block before validating
* - `Object`:
* - `'includeComments'`
* - `true` includes comments as part of the validation
* - `'minLines'`
* - `Integer` specifies a minimum number of lines containing elements in the block before validating
*
* #### Examples
*
* ```js
* "requireBlocksOnNewline": true
* "requireBlocksOnNewline": 1
* "requireBlocksOnNewline": {
* "includeComments": true
* }
* "requireBlocksOnNewline": {
* "includeComments": true,
* "minLines": 1
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* if (true) {
* doSomething();
* }
* var abc = function() {};
* // or
* if (true) { //comments
* doSomething();
* }
* var abc = function() {};
* // or
* if (true) {
* doSomething();
* /** comments *\/
* }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) {doSomething();}
* ```
*
* ##### Valid for mode `1`
*
* ```js
* if (true) {
* doSomething();
* doSomethingElse();
* }
* if (true) { doSomething(); }
* var abc = function() {};
* // or
* if (true) { //comments
* doSomething();
* doSomethingElse();
* }
* if (true) { doSomething(); }
* var abc = function() {};
* ```
*
* ```js
* if (true) {
* doSomething();
* doSomethingElse();
* /** comments *\/
* }
* if (true) { doSomething(); }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) { doSomething(); doSomethingElse(); }
* ```
*
* ##### Valid for mode `{ includeComments: true }`
*
* ```js
* if (true) {
* //comments
* doSomething();
* }
* var abc = function() {};
* // or
* if (true) {
* doSomething();
* //comments
* }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) { //comments
* doSomething();
* }
* var abc = function() {};
* // or
* if (true) {
* doSomething();
* /** comments *\/}
* var abc = function() {};
* ```
*
* ##### Valid for mode `{ includeComments: true, minLines: 1 }`
*
* ```js
* if (true) {
* //comments
* doSomething();
* doSomethingElse();
* }
* if (true) { doSomething(); }
* var abc = function() {};
* // or
* if (true) {
* doSomething();
* doSomethingElse();
* //comments
* }
* if (true) { doSomething(); }
* var abc = function() {};
* ```
*
* ##### Invalid
* ```js
* if (true) { //comments
* doSomething();
* doSomethingElse();
* }
* if (true) { doSomething(); }
* var abc = function() {};
* // or
* if (true) {
* doSomething();
* doSomethingElse();
* /** comments *\/}
* if (true) { doSomething(); }
* var abc = function() {};
* ```
*
*/
var assert = require('assert');
Function hasCommentInBlock
✓ Was called
function hasCommentInBlock(block) {···
for (var i = 0; i < block.childElements.length; i++) {
if (block.childElements[i].isComment) {
return true;
}
}
return false;
}
function hasCommentInBlock(block) {
for (var i = 0; i < block.childElements.length; i++) {
Branch IfStatement
✓ Positive was executed (if)
if (block.childElements[i].isComment) {···
return true;
}
✓ Negative was executed (else)
}···
}
if (block.childElements[i].isComment) {
return true;
}
}
return false;
}
Function (anonymous_814)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_815)
✓ Was called
configure: function(options) {···
var optionType = typeof options;
assert(
options === true || optionType === 'number' || optionType === 'object',
this.getOptionName() + ' option requires the value true, an Integer or an object'
);

this._minLines = 0;
this._includeComments = false;
if (optionType === 'number') {
this._minLines = options;
} else if (optionType === 'object') {
assert(
options.includeComments === true,
this.getOptionName() + ' option requires includeComments property to be true for object'
);
this._includeComments = options.includeComments;

if (options.hasOwnProperty('minLines')) {
assert(
typeof options.minLines === 'number',
this.getOptionName() + ' option requires minLines property to be an integer for object'
);
this._minLines = options.minLines;
}
}

assert(
this._minLines >= 0,
this.getOptionName() + ' option requires minimum statements setting to be >= 0'
);
},
configure: function(options) {
var optionType = typeof options;
assert(
Branch LogicalExpression
✓ Was returned
options === true || optionType === 'number' || optionType === 'object',
✓ Was returned
options === true || optionType === 'number' || optionType === 'object',
Branch LogicalExpression
✓ Was returned
options === true || optionType === 'number' || optionType === 'object',
✓ Was returned
options === true || optionType === 'number' || optionType === 'object',
options === true || optionType === 'number' || optionType === 'object',
this.getOptionName() + ' option requires the value true, an Integer or an object'
);
this._minLines = 0;
this._includeComments = false;
Branch IfStatement
✓ Positive was executed (if)
if (optionType === 'number') {···
this._minLines = options;
} else if (optionType === 'object') {
✓ Negative was executed (else)
} else if (optionType === 'object') {···
assert(
options.includeComments === true,
this.getOptionName() + ' option requires includeComments property to be true for object'
);
this._includeComments = options.includeComments;

if (options.hasOwnProperty('minLines')) {
assert(
typeof options.minLines === 'number',
this.getOptionName() + ' option requires minLines property to be an integer for object'
);
this._minLines = options.minLines;
}
}
if (optionType === 'number') {
this._minLines = options;
Branch IfStatement
✓ Positive was executed (if)
} else if (optionType === 'object') {···
assert(
options.includeComments === true,
this.getOptionName() + ' option requires includeComments property to be true for object'
);
this._includeComments = options.includeComments;

if (options.hasOwnProperty('minLines')) {
assert(
typeof options.minLines === 'number',
this.getOptionName() + ' option requires minLines property to be an integer for object'
);
this._minLines = options.minLines;
}
}
✓ Negative was executed (else)
}···

assert(
} else if (optionType === 'object') {
assert(
options.includeComments === true,
this.getOptionName() + ' option requires includeComments property to be true for object'
);
this._includeComments = options.includeComments;
Branch IfStatement
✓ Positive was executed (if)
if (options.hasOwnProperty('minLines')) {···
assert(
typeof options.minLines === 'number',
this.getOptionName() + ' option requires minLines property to be an integer for object'
);
this._minLines = options.minLines;
}
✓ Negative was executed (else)
}···
}
if (options.hasOwnProperty('minLines')) {
assert(
typeof options.minLines === 'number',
this.getOptionName() + ' option requires minLines property to be an integer for object'
);
this._minLines = options.minLines;
}
}
assert(
this._minLines >= 0,
this.getOptionName() + ' option requires minimum statements setting to be >= 0'
);
},
Function (anonymous_816)
✓ Was called
getOptionName: function() {···
return 'requireBlocksOnNewline';
},
getOptionName: function() {
return 'requireBlocksOnNewline';
},
Function (anonymous_817)
✓ Was called
check: function(file, errors) {···
var minLines = this._minLines;
var includeComments = this._includeComments;

file.iterateNodesByType('BlockStatement', function(node) {
var hasComment = false;
if (includeComments === true) {
hasComment = hasCommentInBlock(node);
}

if (hasComment === false && node.body.length <= minLines) {
return;
}

var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket, { includeComments: includeComments });

errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket, { includeComments: includeComments });

errors.assert.differentLine({
token: prevToken,
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
}
check: function(file, errors) {
var minLines = this._minLines;
var includeComments = this._includeComments;
Function (anonymous_818)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
var hasComment = false;
if (includeComments === true) {
hasComment = hasCommentInBlock(node);
}

if (hasComment === false && node.body.length <= minLines) {
return;
}

var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket, { includeComments: includeComments });

errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket, { includeComments: includeComments });

errors.assert.differentLine({
token: prevToken,
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
file.iterateNodesByType('BlockStatement', function(node) {
var hasComment = false;
Branch IfStatement
✓ Positive was executed (if)
if (includeComments === true) {···
hasComment = hasCommentInBlock(node);
}
✓ Negative was executed (else)
}···

if (hasComment === false && node.body.length <= minLines) {
if (includeComments === true) {
hasComment = hasCommentInBlock(node);
}
Branch IfStatement
✓ Positive was executed (if)
if (hasComment === false && node.body.length <= minLines) {···
return;
}
✓ Negative was executed (else)
}···

var openingBracket = node.getFirstToken();
Branch LogicalExpression
✓ Was returned
if (hasComment === false && node.body.length <= minLines) {
✓ Was returned
if (hasComment === false && node.body.length <= minLines) {
if (hasComment === false && node.body.length <= minLines) {
return;
}
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket, { includeComments: includeComments });
errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});
var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket, { includeComments: includeComments });
errors.assert.differentLine({
token: prevToken,
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
}
};
require-camelcase-or-uppercase-identifiers.js
/**
* Requires identifiers to be camelCased or UPPERCASE_WITH_UNDERSCORES
*
* Types: `Boolean` or `String` or `Object`
*
* Values:
*
* - `true`
* - `"ignoreProperties"` allows an exception for object property names. Deprecated, Please use the `Object` value
* - `Object`:
* - `ignoreProperties`: boolean that allows an exception for object property names
* - `strict`: boolean that forces the first character to not be capitalized
* - `allowedPrefixes`: array of String, RegExp, or ESTree RegExpLiteral values permitted as prefixes
* - `allowedSuffixes`: array of String, RegExp, or ESTree RegExpLiteral values permitted as suffixes
* - `allExcept`: array of String, RegExp, or ESTree RegExpLiteral values permitted as exceptions
*
* JSHint: [`camelcase`](http://jshint.com/docs/options/#camelcase)
*
* #### Example
*
* ```js
* "requireCamelCaseOrUpperCaseIdentifiers": true
*
* "requireCamelCaseOrUpperCaseIdentifiers": {"ignoreProperties": true, "strict": true}
*
* "requireCamelCaseOrUpperCaseIdentifiers": {"allowedPrefixes": ["opt_", /pfx\d+_/]}
*
* "requireCamelCaseOrUpperCaseIdentifiers": {"allowedSuffixes": ["_dCel", {regex: {pattern: "_[kMG]?Hz"}}]}
*
* "requireCamelCaseOrUpperCaseIdentifiers": {"allExcept": ["var_args", {regex: {pattern: "^ignore", flags: "i"}}]}
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var camelCase = 0;
* var CamelCase = 1;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* var lower_case = 1;
* var Mixed_case = 2;
* var mixed_Case = 3;
* ```
*
* ##### Valid for mode `ignoreProperties`
*
* ```js
* var camelCase = 0;
* var CamelCase = 1;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* var obj.snake_case = 5;
* var camelCase = { snake_case: 6 };
* ```
*
* ##### Invalid for mode `ignoreProperties`
*
* ```js
* var lower_case = 1;
* var Mixed_case = 2;
* var mixed_Case = 3;
* var snake_case = { snake_case: 6 };
* ```
*
* ##### Valid for mode `strict`
*
* ```js
* var camelCase = 0;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* var obj.snake_case = 5;
* var camelCase = { snake_case: 6 };
* ```
*
* ##### Invalid for mode `strict`
*
* ```js
* var Mixed_case = 2;
* var Snake_case = { snake_case: 6 };
* var snake_case = { SnakeCase: 6 };
* ```
*
* ##### Valid for `{ allowedPrefix: ["opt_", /pfx\d+_/] }`
* ```js
* var camelCase = 0;
* var CamelCase = 1;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* var opt_camelCase = 5;
* var pfx32_camelCase = 6;
* ```
*
* ##### Invalid for `{ allowedPrefix: ["opt_", /pfx\d+/] }`
* ```js
* var lower_case = 1;
* var Mixed_case = 2;
* var mixed_Case = 3;
* var req_camelCase = 4;
* var pfx_CamelCase = 5;
* ```
*
* ##### Valid for `{ allowedSuffixes: ["_dCel", {regex:{pattern:"_[kMG]?Hz"}}] }`
* ```js
* var camelCase = 0;
* var CamelCase = 1;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* var camelCase_dCel = 5;
* var _camelCase_MHz = 6;
* ```
*
* ##### Invalid for `{ allowedSuffixes: ["_dCel", {regex:{pattern:"_[kMG]?Hz"}}] }`
* ```js
* var lower_case = 1;
* var Mixed_case = 2;
* var mixed_Case = 3;
* var camelCase_cCel = 4;
* var CamelCase_THz = 5;
* ```
*
* ##### Valid for `{ allExcept: ["var_args", {regex:{pattern:"^ignore",flags:"i"}}] }`
* ```js
* var camelCase = 0;
* var CamelCase = 1;
* var _camelCase = 2;
* var camelCase_ = 3;
* var UPPER_CASE = 4;
* var var_args = 5;
* var ignoreThis_Please = 6;
* var iGnOrEeThis_Too = 7;
* ```
*
* ##### Invalid for `{ allExcept: ["var_args", {regex:{pattern:"^ignore",flags:"i"}}] }`
* ```js
* var lower_case = 1;
* var Mixed_case = 2;
* var mixed_Case = 3;
* var var_arg = 4;
* var signore_per_favore = 5;
* ```
*/
var assert = require('assert');
// Convert an array of String or RegExp or ESTree RegExpLiteral values
// into an array of String or RegExp values. Returns falsy if the
// input does not match expectations.
Function processArrayOfStringOrRegExp
✓ Was called
function processArrayOfStringOrRegExp(iv) {···
if (!Array.isArray(iv)) {
return;
}
var rv = [];
var i = 0;
while (rv && (i < iv.length)) {
var elt = iv[i];
if (typeof elt === 'string') {
// string values OK
rv.push(elt);
} else if (elt instanceof RegExp) {
// existing RegExp OK
rv.push(elt);
} else if (elt && (typeof elt === 'object')) {
try {
// ESTree RegExpLiteral ok if it produces RegExp
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
} catch (e) {
// Not a valid RegExpLiteral
rv = null;
}
} else {
// Unknown value
rv = null;
}
++i;
}
return rv;
}
function processArrayOfStringOrRegExp(iv) {
Branch IfStatement
✓ Positive was executed (if)
if (!Array.isArray(iv)) {···
return;
}
✓ Negative was executed (else)
}···
var rv = [];
if (!Array.isArray(iv)) {
return;
}
var rv = [];
var i = 0;
Branch LogicalExpression
✓ Was returned
while (rv && (i < iv.length)) {
✓ Was returned
while (rv && (i < iv.length)) {
while (rv && (i < iv.length)) {
var elt = iv[i];
Branch IfStatement
✓ Positive was executed (if)
if (typeof elt === 'string') {···
// string values OK
rv.push(elt);
} else if (elt instanceof RegExp) {
✓ Negative was executed (else)
} else if (elt instanceof RegExp) {···
// existing RegExp OK
rv.push(elt);
} else if (elt && (typeof elt === 'object')) {
try {
// ESTree RegExpLiteral ok if it produces RegExp
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
} catch (e) {
// Not a valid RegExpLiteral
rv = null;
}
} else {
// Unknown value
rv = null;
}
if (typeof elt === 'string') {
// string values OK
rv.push(elt);
Branch IfStatement
✓ Positive was executed (if)
} else if (elt instanceof RegExp) {···
// existing RegExp OK
rv.push(elt);
} else if (elt && (typeof elt === 'object')) {
✓ Negative was executed (else)
} else if (elt && (typeof elt === 'object')) {···
try {
// ESTree RegExpLiteral ok if it produces RegExp
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
} catch (e) {
// Not a valid RegExpLiteral
rv = null;
}
} else {
// Unknown value
rv = null;
}
} else if (elt instanceof RegExp) {
// existing RegExp OK
rv.push(elt);
Branch IfStatement
✓ Positive was executed (if)
} else if (elt && (typeof elt === 'object')) {···
try {
// ESTree RegExpLiteral ok if it produces RegExp
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
} catch (e) {
// Not a valid RegExpLiteral
rv = null;
}
} else {
✓ Negative was executed (else)
} else {···
// Unknown value
rv = null;
}
Branch LogicalExpression
✓ Was returned
} else if (elt && (typeof elt === 'object')) {
✓ Was returned
} else if (elt && (typeof elt === 'object')) {
} else if (elt && (typeof elt === 'object')) {
try {
// ESTree RegExpLiteral ok if it produces RegExp
Branch LogicalExpression
✓ Was returned
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
✓ Was returned
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));
} catch (e) {
// Not a valid RegExpLiteral
rv = null;
}
} else {
// Unknown value
rv = null;
}
++i;
}
return rv;
}
// Return undefined or the start of the unprefixed value.
Function startAfterStringPrefix
✓ Was called
function startAfterStringPrefix(value, prefix) {···
var start = prefix.length;
if (start >= value.length) {
return;
}
if (value.substr(0, prefix.length) !== prefix) {
return;
}
return start;
}
function startAfterStringPrefix(value, prefix) {
var start = prefix.length;
Branch IfStatement
✓ Positive was executed (if)
if (start >= value.length) {···
return;
}
✓ Negative was executed (else)
}···
if (value.substr(0, prefix.length) !== prefix) {
if (start >= value.length) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (value.substr(0, prefix.length) !== prefix) {···
return;
}
✓ Negative was executed (else)
}···
return start;
if (value.substr(0, prefix.length) !== prefix) {
return;
}
return start;
}
// Return undefined or the start of the unprefixed value.
Function startAfterRegExpPrefix
✓ Was called
function startAfterRegExpPrefix(value, prefix) {···
var match = prefix.exec(value);
if (!match) {
return;
}
if (match.index !== 0) {
return;
}
return match[0].length;
}
function startAfterRegExpPrefix(value, prefix) {
var match = prefix.exec(value);
Branch IfStatement
✓ Positive was executed (if)
if (!match) {···
return;
}
✓ Negative was executed (else)
}···
if (match.index !== 0) {
if (!match) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (match.index !== 0) {···
return;
}
✓ Negative was executed (else)
}···
return match[0].length;
if (match.index !== 0) {
return;
}
return match[0].length;
}
// Return undefined or the end of the unsuffixed value.
Function endBeforeStringSuffix
✓ Was called
function endBeforeStringSuffix(value, suffix) {···
var ends = value.length - suffix.length;
if (ends <= 0) {
return;
}
if (value.substr(ends) !== suffix) {
return;
}
return ends;
}
function endBeforeStringSuffix(value, suffix) {
var ends = value.length - suffix.length;
Branch IfStatement
✓ Positive was executed (if)
if (ends <= 0) {···
return;
}
✓ Negative was executed (else)
}···
if (value.substr(ends) !== suffix) {
if (ends <= 0) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (value.substr(ends) !== suffix) {···
return;
}
✓ Negative was executed (else)
}···
return ends;
if (value.substr(ends) !== suffix) {
return;
}
return ends;
}
// Return undefined or the end of the unsuffixed value.
Function endBeforeRegExpSuffix
✓ Was called
function endBeforeRegExpSuffix(value, suffix) {···
var match = suffix.exec(value);
if (!match) {
return;
}
var ends = match.index;
if ((ends + match[0].length) !== value.length) {
return;
}
return ends;
}
function endBeforeRegExpSuffix(value, suffix) {
var match = suffix.exec(value);
Branch IfStatement
✓ Positive was executed (if)
if (!match) {···
return;
}
✓ Negative was executed (else)
}···
var ends = match.index;
if (!match) {
return;
}
var ends = match.index;
Branch IfStatement
✓ Positive was executed (if)
if ((ends + match[0].length) !== value.length) {···
return;
}
✓ Negative was executed (else)
}···
return ends;
if ((ends + match[0].length) !== value.length) {
return;
}
return ends;
}
// Return truthy iff the value matches the exception.
Function matchException
✓ Was called
function matchException(value, exception) {···
if (typeof exception === 'string') {
return (exception === value);
}
return exception.test(value);
}
function matchException(value, exception) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof exception === 'string') {···
return (exception === value);
}
✓ Negative was executed (else)
}···
return exception.test(value);
if (typeof exception === 'string') {
return (exception === value);
}
return exception.test(value);
}
Function (anonymous_825)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_826)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true || options === 'ignoreProperties',
this.getOptionName() + ' option requires a true value or `ignoreProperties`'
);
var _options = {
ignoreProperties: options === 'ignoreProperties' ? true : false,
strict: false
};
return this.configure(_options);
}

assert(
!options.hasOwnProperty('ignoreProperties') || typeof options.ignoreProperties === 'boolean',
this.getOptionName() + ' option should have boolean value for ignoreProperties'
);
this._ignoreProperties = options.ignoreProperties;

assert(
!options.hasOwnProperty('strict') || typeof options.strict === 'boolean',
this.getOptionName() + ' option should have boolean value for strict'
);
this._strict = options.strict;

var asre = processArrayOfStringOrRegExp(options.allowedPrefixes);
assert(
!options.hasOwnProperty('allowedPrefixes') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allowedPrefixes'
);
if (asre) {
this._allowedPrefixes = asre;
}

asre = processArrayOfStringOrRegExp(options.allowedSuffixes);
assert(
!options.hasOwnProperty('allowedSuffixes') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allowedSuffixes'
);
if (asre) {
this._allowedSuffixes = asre;
}

asre = processArrayOfStringOrRegExp(options.allExcept);
assert(
!options.hasOwnProperty('allExcept') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allExcept'
);
if (asre) {
this._allExcept = asre;
}

},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true || options === 'ignoreProperties',
this.getOptionName() + ' option requires a true value or `ignoreProperties`'
);
var _options = {
ignoreProperties: options === 'ignoreProperties' ? true : false,
strict: false
};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'ignoreProperties',
✓ Was returned
options === true || options === 'ignoreProperties',
options === true || options === 'ignoreProperties',
this.getOptionName() + ' option requires a true value or `ignoreProperties`'
);
var _options = {
Branch ConditionalExpression
✓ Positive was returned (? ...)
ignoreProperties: options === 'ignoreProperties' ? true : false,
✓ Negative was returned (: ...)
ignoreProperties: options === 'ignoreProperties' ? true : false,
ignoreProperties: options === 'ignoreProperties' ? true : false,
strict: false
};
return this.configure(_options);
}
assert(
Branch LogicalExpression
✓ Was returned
!options.hasOwnProperty('ignoreProperties') || typeof options.ignoreProperties === 'boolean',
✓ Was returned
!options.hasOwnProperty('ignoreProperties') || typeof options.ignoreProperties === 'boolean',
!options.hasOwnProperty('ignoreProperties') || typeof options.ignoreProperties === 'boolean',
this.getOptionName() + ' option should have boolean value for ignoreProperties'
);
this._ignoreProperties = options.ignoreProperties;
assert(
Branch LogicalExpression
✓ Was returned
!options.hasOwnProperty('strict') || typeof options.strict === 'boolean',
✓ Was returned
!options.hasOwnProperty('strict') || typeof options.strict === 'boolean',
!options.hasOwnProperty('strict') || typeof options.strict === 'boolean',
this.getOptionName() + ' option should have boolean value for strict'
);
this._strict = options.strict;
var asre = processArrayOfStringOrRegExp(options.allowedPrefixes);
assert(
Branch LogicalExpression
✓ Was returned
!options.hasOwnProperty('allowedPrefixes') || asre,
✓ Was returned
!options.hasOwnProperty('allowedPrefixes') || asre,
!options.hasOwnProperty('allowedPrefixes') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allowedPrefixes'
);
Branch IfStatement
✓ Positive was executed (if)
if (asre) {···
this._allowedPrefixes = asre;
}
✓ Negative was executed (else)
}···

asre = processArrayOfStringOrRegExp(options.allowedSuffixes);
if (asre) {
this._allowedPrefixes = asre;
}
asre = processArrayOfStringOrRegExp(options.allowedSuffixes);
assert(
Branch LogicalExpression
✓ Was returned
!options.hasOwnProperty('allowedSuffixes') || asre,
✓ Was returned
!options.hasOwnProperty('allowedSuffixes') || asre,
!options.hasOwnProperty('allowedSuffixes') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allowedSuffixes'
);
Branch IfStatement
✓ Positive was executed (if)
if (asre) {···
this._allowedSuffixes = asre;
}
✓ Negative was executed (else)
}···

asre = processArrayOfStringOrRegExp(options.allExcept);
if (asre) {
this._allowedSuffixes = asre;
}
asre = processArrayOfStringOrRegExp(options.allExcept);
assert(
Branch LogicalExpression
✓ Was returned
!options.hasOwnProperty('allExcept') || asre,
✓ Was returned
!options.hasOwnProperty('allExcept') || asre,
!options.hasOwnProperty('allExcept') || asre,
this.getOptionName() + ' option should have array of string or RegExp for allExcept'
);
Branch IfStatement
✓ Positive was executed (if)
if (asre) {···
this._allExcept = asre;
}
✓ Negative was executed (else)
}···

},
if (asre) {
this._allExcept = asre;
}
},
Function (anonymous_827)
✓ Was called
getOptionName: function() {···
return 'requireCamelCaseOrUpperCaseIdentifiers';
},
getOptionName: function() {
return 'requireCamelCaseOrUpperCaseIdentifiers';
},
Function (anonymous_828)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByType('Identifier', function(token) {
var value = token.value;

// Leading and trailing underscores signify visibility/scope and do not affect
// validation of the rule. Remove them to simplify the checks.
var isPrivate = (value[0] === '_');
value = value.replace(/^_+|_+$/g, '');

// Detect exceptions before stripping prefixes/suffixes.
if (this._allExcept) {
for (i = 0, len = this._allExcept.length; i < len; ++i) {
if (matchException(value, this._allExcept[i])) {
return;
}
}
}

// Strip at most one prefix permitted text from the identifier. This transformation
// cannot change an acceptable identifier into an unacceptable identifier so we can
// continue with the normal verification of whatever it produces.
var i;
var len;
if (this._allowedPrefixes) {
for (i = 0, len = this._allowedPrefixes.length; i < len; ++i) {
var prefix = this._allowedPrefixes[i];
var start;
if (typeof prefix === 'string') {
start = startAfterStringPrefix(value, prefix);
} else {
start = startAfterRegExpPrefix(value, prefix);
}
if (start !== undefined) {
value = value.substr(start);
break;
}
}
}

// As with prefix but for one suffix permitted text.
if (this._allowedSuffixes) {
for (i = 0, len = this._allowedSuffixes.length; i < len; ++i) {
var suffix = this._allowedSuffixes[i];
var ends;
if (typeof suffix === 'string') {
ends = endBeforeStringSuffix(value, suffix);
} else {
ends = endBeforeRegExpSuffix(value, suffix);
}
if (ends !== undefined) {
value = value.substr(0, ends);
break;
}
}
}

if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
if (!this._strict) {return;}
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
return;
}
}
if (this._ignoreProperties) {
var nextToken = file.getNextToken(token);
var prevToken = token.getPreviousCodeToken();

if (nextToken && nextToken.value === ':') {
return;
}

/* This enables an identifier to be snake cased via the object
* destructuring pattern. We must check to see if the identifier
* is being used to set values into an object to determine if
* this is a legal assignment.
* Example: ({camelCase: snake_case}) => camelCase.length
*/
if (prevToken && prevToken.value === ':') {
var node = token.parentElement;
var parentElement = node.parentElement;
if (parentElement && parentElement.type === 'ObjectProperty') {
var grandpa = parentElement.parentElement;
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
}

if (prevToken && (prevToken.value === '.' ||
prevToken.value === 'get' || prevToken.value === 'set')) {
return;
}
}
errors.add(
'All identifiers must be camelCase or UPPER_CASE',
token
);
}.bind(this));
}
check: function(file, errors) {
Function (anonymous_829)
✓ Was called
file.iterateTokensByType('Identifier', function(token) {···
var value = token.value;

// Leading and trailing underscores signify visibility/scope and do not affect
// validation of the rule. Remove them to simplify the checks.
var isPrivate = (value[0] === '_');
value = value.replace(/^_+|_+$/g, '');

// Detect exceptions before stripping prefixes/suffixes.
if (this._allExcept) {
for (i = 0, len = this._allExcept.length; i < len; ++i) {
if (matchException(value, this._allExcept[i])) {
return;
}
}
}

// Strip at most one prefix permitted text from the identifier. This transformation
// cannot change an acceptable identifier into an unacceptable identifier so we can
// continue with the normal verification of whatever it produces.
var i;
var len;
if (this._allowedPrefixes) {
for (i = 0, len = this._allowedPrefixes.length; i < len; ++i) {
var prefix = this._allowedPrefixes[i];
var start;
if (typeof prefix === 'string') {
start = startAfterStringPrefix(value, prefix);
} else {
start = startAfterRegExpPrefix(value, prefix);
}
if (start !== undefined) {
value = value.substr(start);
break;
}
}
}

// As with prefix but for one suffix permitted text.
if (this._allowedSuffixes) {
for (i = 0, len = this._allowedSuffixes.length; i < len; ++i) {
var suffix = this._allowedSuffixes[i];
var ends;
if (typeof suffix === 'string') {
ends = endBeforeStringSuffix(value, suffix);
} else {
ends = endBeforeRegExpSuffix(value, suffix);
}
if (ends !== undefined) {
value = value.substr(0, ends);
break;
}
}
}

if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
if (!this._strict) {return;}
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
return;
}
}
if (this._ignoreProperties) {
var nextToken = file.getNextToken(token);
var prevToken = token.getPreviousCodeToken();

if (nextToken && nextToken.value === ':') {
return;
}

/* This enables an identifier to be snake cased via the object
* destructuring pattern. We must check to see if the identifier
* is being used to set values into an object to determine if
* this is a legal assignment.
* Example: ({camelCase: snake_case}) => camelCase.length
*/
if (prevToken && prevToken.value === ':') {
var node = token.parentElement;
var parentElement = node.parentElement;
if (parentElement && parentElement.type === 'ObjectProperty') {
var grandpa = parentElement.parentElement;
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
}

if (prevToken && (prevToken.value === '.' ||
prevToken.value === 'get' || prevToken.value === 'set')) {
return;
}
}
errors.add(
'All identifiers must be camelCase or UPPER_CASE',
token
);
}.bind(this));
file.iterateTokensByType('Identifier', function(token) {
var value = token.value;
// Leading and trailing underscores signify visibility/scope and do not affect
// validation of the rule. Remove them to simplify the checks.
var isPrivate = (value[0] === '_');
value = value.replace(/^_+|_+$/g, '');
// Detect exceptions before stripping prefixes/suffixes.
Branch IfStatement
✓ Positive was executed (if)
if (this._allExcept) {···
for (i = 0, len = this._allExcept.length; i < len; ++i) {
if (matchException(value, this._allExcept[i])) {
return;
}
}
}
✓ Negative was executed (else)
}···

// Strip at most one prefix permitted text from the identifier. This transformation
if (this._allExcept) {
for (i = 0, len = this._allExcept.length; i < len; ++i) {
Branch IfStatement
✓ Positive was executed (if)
if (matchException(value, this._allExcept[i])) {···
return;
}
✓ Negative was executed (else)
}···
}
if (matchException(value, this._allExcept[i])) {
return;
}
}
}
// Strip at most one prefix permitted text from the identifier. This transformation
// cannot change an acceptable identifier into an unacceptable identifier so we can
// continue with the normal verification of whatever it produces.
var i;
var len;
Branch IfStatement
✓ Positive was executed (if)
if (this._allowedPrefixes) {···
for (i = 0, len = this._allowedPrefixes.length; i < len; ++i) {
var prefix = this._allowedPrefixes[i];
var start;
if (typeof prefix === 'string') {
start = startAfterStringPrefix(value, prefix);
} else {
start = startAfterRegExpPrefix(value, prefix);
}
if (start !== undefined) {
value = value.substr(start);
break;
}
}
}
✓ Negative was executed (else)
}···

// As with prefix but for one suffix permitted text.
if (this._allowedPrefixes) {
for (i = 0, len = this._allowedPrefixes.length; i < len; ++i) {
var prefix = this._allowedPrefixes[i];
var start;
Branch IfStatement
✓ Positive was executed (if)
if (typeof prefix === 'string') {···
start = startAfterStringPrefix(value, prefix);
} else {
✓ Negative was executed (else)
} else {···
start = startAfterRegExpPrefix(value, prefix);
}
if (typeof prefix === 'string') {
start = startAfterStringPrefix(value, prefix);
} else {
start = startAfterRegExpPrefix(value, prefix);
}
Branch IfStatement
✓ Positive was executed (if)
if (start !== undefined) {···
value = value.substr(start);
break;
}
✓ Negative was executed (else)
}···
}
if (start !== undefined) {
value = value.substr(start);
break;
}
}
}
// As with prefix but for one suffix permitted text.
Branch IfStatement
✓ Positive was executed (if)
if (this._allowedSuffixes) {···
for (i = 0, len = this._allowedSuffixes.length; i < len; ++i) {
var suffix = this._allowedSuffixes[i];
var ends;
if (typeof suffix === 'string') {
ends = endBeforeStringSuffix(value, suffix);
} else {
ends = endBeforeRegExpSuffix(value, suffix);
}
if (ends !== undefined) {
value = value.substr(0, ends);
break;
}
}
}
✓ Negative was executed (else)
}···

if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
if (this._allowedSuffixes) {
for (i = 0, len = this._allowedSuffixes.length; i < len; ++i) {
var suffix = this._allowedSuffixes[i];
var ends;
Branch IfStatement
✓ Positive was executed (if)
if (typeof suffix === 'string') {···
ends = endBeforeStringSuffix(value, suffix);
} else {
✓ Negative was executed (else)
} else {···
ends = endBeforeRegExpSuffix(value, suffix);
}
if (typeof suffix === 'string') {
ends = endBeforeStringSuffix(value, suffix);
} else {
ends = endBeforeRegExpSuffix(value, suffix);
}
Branch IfStatement
✓ Positive was executed (if)
if (ends !== undefined) {···
value = value.substr(0, ends);
break;
}
✓ Negative was executed (else)
}···
}
if (ends !== undefined) {
value = value.substr(0, ends);
break;
}
}
}
Branch IfStatement
✓ Positive was executed (if)
if (value.indexOf('_') === -1 || value.toUpperCase() === value) {···
if (!this._strict) {return;}
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
return;
}
}
✓ Negative was executed (else)
}···
if (this._ignoreProperties) {
Branch LogicalExpression
✓ Was returned
if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
✓ Was returned
if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
if (value.indexOf('_') === -1 || value.toUpperCase() === value) {
Branch IfStatement
✓ Positive was executed (if)
if (!this._strict) {return;}
✓ Negative was executed (else)
if (!this._strict) {return;}···
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
if (!this._strict) {return;}
Branch IfStatement
✓ Positive was executed (if)
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
✓ Was returned
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
Branch LogicalExpression
✓ Was returned
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
✓ Was returned
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
if (value.length === 0 || value[0].toUpperCase() !== value[0] || isPrivate) {
return;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (this._ignoreProperties) {···
var nextToken = file.getNextToken(token);
var prevToken = token.getPreviousCodeToken();

if (nextToken && nextToken.value === ':') {
return;
}

/* This enables an identifier to be snake cased via the object
* destructuring pattern. We must check to see if the identifier
* is being used to set values into an object to determine if
* this is a legal assignment.
* Example: ({camelCase: snake_case}) => camelCase.length
*/
if (prevToken && prevToken.value === ':') {
var node = token.parentElement;
var parentElement = node.parentElement;
if (parentElement && parentElement.type === 'ObjectProperty') {
var grandpa = parentElement.parentElement;
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
}

if (prevToken && (prevToken.value === '.' ||
prevToken.value === 'get' || prevToken.value === 'set')) {
return;
}
}
✓ Negative was executed (else)
}···
errors.add(
if (this._ignoreProperties) {
var nextToken = file.getNextToken(token);
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (nextToken && nextToken.value === ':') {···
return;
}
✓ Negative was executed (else)
}···

/* This enables an identifier to be snake cased via the object
Branch LogicalExpression
✓ Was returned
if (nextToken && nextToken.value === ':') {
✗ Was not returned
if (nextToken && nextToken.value === ':') {
if (nextToken && nextToken.value === ':') {
return;
}
/* This enables an identifier to be snake cased via the object
* destructuring pattern. We must check to see if the identifier
* is being used to set values into an object to determine if
* this is a legal assignment.
* Example: ({camelCase: snake_case}) => camelCase.length
*/
Branch IfStatement
✓ Positive was executed (if)
if (prevToken && prevToken.value === ':') {···
var node = token.parentElement;
var parentElement = node.parentElement;
if (parentElement && parentElement.type === 'ObjectProperty') {
var grandpa = parentElement.parentElement;
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
}
✓ Negative was executed (else)
}···

if (prevToken && (prevToken.value === '.' ||
Branch LogicalExpression
✓ Was returned
if (prevToken && prevToken.value === ':') {
✓ Was returned
if (prevToken && prevToken.value === ':') {
if (prevToken && prevToken.value === ':') {
var node = token.parentElement;
var parentElement = node.parentElement;
Branch IfStatement
✓ Positive was executed (if)
if (parentElement && parentElement.type === 'ObjectProperty') {···
var grandpa = parentElement.parentElement;
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
✗ Negative was not executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (parentElement && parentElement.type === 'ObjectProperty') {
✗ Was not returned
if (parentElement && parentElement.type === 'ObjectProperty') {
if (parentElement && parentElement.type === 'ObjectProperty') {
var grandpa = parentElement.parentElement;
Branch IfStatement
✓ Positive was executed (if)
if (grandpa && grandpa.type === 'ObjectPattern') {···
return;
}
✗ Negative was not executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (grandpa && grandpa.type === 'ObjectPattern') {
✗ Was not returned
if (grandpa && grandpa.type === 'ObjectPattern') {
if (grandpa && grandpa.type === 'ObjectPattern') {
return;
}
}
}
Branch IfStatement
✓ Positive was executed (if)
prevToken.value === 'get' || prevToken.value === 'set')) {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (prevToken && (prevToken.value === '.' ||···
prevToken.value === 'get' || prevToken.value === 'set')) {
✓ Was returned
if (prevToken && (prevToken.value === '.' ||
Branch LogicalExpression
✓ Was returned
prevToken.value === 'get' || prevToken.value === 'set')) {
✓ Was returned
if (prevToken && (prevToken.value === '.' ||···
prevToken.value === 'get' || prevToken.value === 'set')) {
Branch LogicalExpression
✓ Was returned
prevToken.value === 'get' || prevToken.value === 'set')) {
✓ Was returned
if (prevToken && (prevToken.value === '.' ||
if (prevToken && (prevToken.value === '.' ||
prevToken.value === 'get' || prevToken.value === 'set')) {
return;
}
}
errors.add(
'All identifiers must be camelCase or UPPER_CASE',
token
);
}.bind(this));
}
};
require-capitalized-comments.js
/**
* Requires the first alphabetical character of a comment to be uppercase, unless it is part of a multi-line textblock.
*
* This rule automatically ignores jscs, jshint, eslint and istanbul specific comments.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `Object`:
* - `allExcept`: array of quoted exceptions
* - `inlined`: Ignore comments in the middle of the code line
*
* #### Example
*
* ```js
* "requireCapitalizedComments": true
* ```
*
* ##### Valid:
*
* ```js
* // Valid
* //Valid
*
* /*
* Valid
* *\/
*
* /**
* * Valid
* *\/
*
* // A textblock is a set of lines
* // that starts with a capitalized letter
* // and has one or more non-capitalized lines
* // afterwards
*
* // A textblock may also have multiple lines.
* // Those lines can be uppercase as well to support
* // sentence breaks in textblocks
*
* // 123 or any non-alphabetical starting character
* // @are also valid anywhere
*
* // jscs: enable
* ```
*
* ##### Invalid:
*
* ```js
* // invalid
* //invalid
* /** invalid *\/
* /**
* * invalid
* *\/
* ```
*
* ```js
* "requireCapitalizedComments": { "allExcept": ["pragma"] }
* ```
*
* ##### Valid:
*
* ```js
* function sayHello() {
* /* pragma something *\/
*
* // I can now say hello in lots of statements, if I like.
* return "Hello";
* }
* ```
*
* ##### Valid:
*
* ```js
* function sayHello() {
* /* istanbul ignore next *\/
*
* // I'd like to ignore this statement in coverage reports.
* return "Hello";
* }
* ```
*
* ##### Invalid:
*
* ```js
* function sayHello() {
* /* otherPragma something *\/
*
* // i can now say hello in lots of statements, if I like.
* return "Hello";
* }
* ```
*
* ```js
* "requireCapitalizedComments": { "inlined": true }
* ```
* ##### Valid:
*
* ```js
* function sayHello( world /*internal*\/ ) {
* }
* ```
*/
var assert = require('assert');
var cst = require('cst');
var isPragma = require('../utils').isPragma;
var letterPattern = require('../../patterns/L');
var upperCasePattern = require('../../patterns/Lu');
Function (anonymous_830)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_831)
✓ Was called
configure: function(options) {···
var exceptions;

this.inlined = false;
this._isPragma = null;

var optionName = this.getOptionName();

var isObject = typeof options === 'object';
var error = optionName + ' option requires a true value ' +
'or an object with String[] `allExcept` property or true with `inlined`';

assert(
options === true ||
isObject,
error
);

if (isObject && options.allExcept) {
exceptions = options.allExcept;

// verify items in `allExcept` property in object are string values
assert(
Array.isArray(exceptions) &&
exceptions.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);

this._isPragma = isPragma(exceptions);
}

if (!this._isPragma) {
this._isPragma = isPragma();
}

if (isObject && options.inlined) {
this.inlined = true;
}

if (isObject && !options.allExcept && !options.inlined) {
assert(false, error);
}
},
configure: function(options) {
var exceptions;
this.inlined = false;
this._isPragma = null;
var optionName = this.getOptionName();
var isObject = typeof options === 'object';
var error = optionName + ' option requires a true value ' +
'or an object with String[] `allExcept` property or true with `inlined`';
assert(
Branch LogicalExpression
✓ Was returned
isObject,
✓ Was returned
options === true ||
options === true ||
isObject,
error
);
Branch IfStatement
✓ Positive was executed (if)
if (isObject && options.allExcept) {···
exceptions = options.allExcept;

// verify items in `allExcept` property in object are string values
assert(
Array.isArray(exceptions) &&
exceptions.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);

this._isPragma = isPragma(exceptions);
}
✓ Negative was executed (else)
}···

if (!this._isPragma) {
Branch LogicalExpression
✓ Was returned
if (isObject && options.allExcept) {
✓ Was returned
if (isObject && options.allExcept) {
if (isObject && options.allExcept) {
exceptions = options.allExcept;
// verify items in `allExcept` property in object are string values
assert(
Branch LogicalExpression
✓ Was returned
exceptions.every(function(el) { return typeof el === 'string'; }),
✗ Was not returned
Array.isArray(exceptions) &&
Array.isArray(exceptions) &&
Function (anonymous_832)
✓ Was called
exceptions.every(function(el) { return typeof el === 'string'; }),
exceptions.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);
this._isPragma = isPragma(exceptions);
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._isPragma) {···
this._isPragma = isPragma();
}
✓ Negative was executed (else)
}···

if (isObject && options.inlined) {
if (!this._isPragma) {
this._isPragma = isPragma();
}
Branch IfStatement
✓ Positive was executed (if)
if (isObject && options.inlined) {···
this.inlined = true;
}
✓ Negative was executed (else)
}···

if (isObject && !options.allExcept && !options.inlined) {
Branch LogicalExpression
✓ Was returned
if (isObject && options.inlined) {
✓ Was returned
if (isObject && options.inlined) {
if (isObject && options.inlined) {
this.inlined = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (isObject && !options.allExcept && !options.inlined) {···
assert(false, error);
}
✓ Negative was executed (else)
}···
},
Branch LogicalExpression
✓ Was returned
if (isObject && !options.allExcept && !options.inlined) {
✓ Was returned
if (isObject && !options.allExcept && !options.inlined) {
Branch LogicalExpression
✓ Was returned
if (isObject && !options.allExcept && !options.inlined) {
✓ Was returned
if (isObject && !options.allExcept && !options.inlined) {
if (isObject && !options.allExcept && !options.inlined) {
assert(false, error);
}
},
Function (anonymous_833)
✓ Was called
getOptionName: function() {···
return 'requireCapitalizedComments';
},
getOptionName: function() {
return 'requireCapitalizedComments';
},
Function (anonymous_834)
✓ Was called
_isUrl: function(comment) {···
var protocolParts = comment.value.split('://');

if (protocolParts.length === 1) {
return false;
}

return comment.value.indexOf(protocolParts[0]) === 0;
},
_isUrl: function(comment) {
var protocolParts = comment.value.split('://');
Branch IfStatement
✓ Positive was executed (if)
if (protocolParts.length === 1) {···
return false;
}
✓ Negative was executed (else)
}···

return comment.value.indexOf(protocolParts[0]) === 0;
if (protocolParts.length === 1) {
return false;
}
return comment.value.indexOf(protocolParts[0]) === 0;
},
Function (anonymous_835)
✓ Was called
_isException: function(comment) {···
return this._isPragma(comment.value);
},
_isException: function(comment) {
return this._isPragma(comment.value);
},
Function (anonymous_836)
✓ Was called
_isValid: function(comment) {···
var first = this._getFirstChar(comment);

return first && upperCasePattern.test(first);
},
_isValid: function(comment) {
var first = this._getFirstChar(comment);
Branch LogicalExpression
✓ Was returned
return first && upperCasePattern.test(first);
✗ Was not returned
return first && upperCasePattern.test(first);
return first && upperCasePattern.test(first);
},
Function (anonymous_837)
✓ Was called
_isLetter: function(comment) {···
var first = this._getFirstChar(comment);

return first && letterPattern.test(first);
},
_isLetter: function(comment) {
var first = this._getFirstChar(comment);
Branch LogicalExpression
✓ Was returned
return first && letterPattern.test(first);
✓ Was returned
return first && letterPattern.test(first);
return first && letterPattern.test(first);
},
Function (anonymous_838)
✓ Was called
_getFirstChar: function(comment) {···
return comment.value.replace(/[\n\s\*]/g, '')[0];
},
_getFirstChar: function(comment) {
return comment.value.replace(/[\n\s\*]/g, '')[0];
},
Function (anonymous_839)
✓ Was called
_isTextBlock: function(file, comment) {···
var prevComment = file.getPrevToken(comment, {includeComments: true});

if (prevComment) {
return prevComment.type === 'CommentLine' &&
!file.isOnTheSameLine(comment, prevComment) &&
prevComment.value.trim().length > 0;
}

return false;
},
_isTextBlock: function(file, comment) {
var prevComment = file.getPrevToken(comment, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (prevComment) {···
return prevComment.type === 'CommentLine' &&
!file.isOnTheSameLine(comment, prevComment) &&
prevComment.value.trim().length > 0;
}
✓ Negative was executed (else)
}···

return false;
if (prevComment) {
Branch LogicalExpression
✓ Was returned
prevComment.value.trim().length > 0;
✓ Was returned
return prevComment.type === 'CommentLine' &&···
!file.isOnTheSameLine(comment, prevComment) &&
Branch LogicalExpression
✓ Was returned
!file.isOnTheSameLine(comment, prevComment) &&
✓ Was returned
return prevComment.type === 'CommentLine' &&
return prevComment.type === 'CommentLine' &&
!file.isOnTheSameLine(comment, prevComment) &&
prevComment.value.trim().length > 0;
}
return false;
},
Function (anonymous_840)
✓ Was called
_shouldIgnoreIfInTheMiddle: function(file, comment) {···
if (!this.inlined) {
return false;
}

var firstToken = comment.getFirstToken();
var otherToken = firstToken.getPreviousNonWhitespaceToken();

return otherToken ? file.isOnTheSameLine(otherToken, firstToken) : false;
},
_shouldIgnoreIfInTheMiddle: function(file, comment) {
Branch IfStatement
✓ Positive was executed (if)
if (!this.inlined) {···
return false;
}
✓ Negative was executed (else)
}···

var firstToken = comment.getFirstToken();
if (!this.inlined) {
return false;
}
var firstToken = comment.getFirstToken();
var otherToken = firstToken.getPreviousNonWhitespaceToken();
Branch ConditionalExpression
✓ Positive was returned (? ...)
return otherToken ? file.isOnTheSameLine(otherToken, firstToken) : false;
✓ Negative was returned (: ...)
return otherToken ? file.isOnTheSameLine(otherToken, firstToken) : false;
return otherToken ? file.isOnTheSameLine(otherToken, firstToken) : false;
},
Function (anonymous_841)
✓ Was called
check: function(file, errors) {···
var _this = this;

function add(comment) {
errors.cast({
message: 'Comments must start with an uppercase letter, unless it is part of a textblock',
element: comment,
additional: comment
});
}

file.iterateTokensByType('CommentLine', function(comment) {
if (_this._isException(comment)) {
return;
}

if (_this._isUrl(comment)) {
return;
}

if (!_this._isLetter(comment)) {
return;
}

if (_this._isTextBlock(file, comment)) {
return;
}

if (_this._isValid(comment)) {
return;
}

add(comment);
});

file.iterateTokensByType('CommentBlock', function(comment) {
if (_this._isException(comment)) {
return;
}

if (_this._isUrl(comment)) {
return;
}

if (!_this._isLetter(comment)) {
return;
}

if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
return;
}

if (_this._isValid(comment)) {
return;
}

add(comment);
});
},
check: function(file, errors) {
var _this = this;
Function add
✓ Was called
function add(comment) {···
errors.cast({
message: 'Comments must start with an uppercase letter, unless it is part of a textblock',
element: comment,
additional: comment
});
}
function add(comment) {
errors.cast({
message: 'Comments must start with an uppercase letter, unless it is part of a textblock',
element: comment,
additional: comment
});
}
Function (anonymous_843)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
if (_this._isException(comment)) {
return;
}

if (_this._isUrl(comment)) {
return;
}

if (!_this._isLetter(comment)) {
return;
}

if (_this._isTextBlock(file, comment)) {
return;
}

if (_this._isValid(comment)) {
return;
}

add(comment);
});
file.iterateTokensByType('CommentLine', function(comment) {
Branch IfStatement
✓ Positive was executed (if)
if (_this._isException(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._isUrl(comment)) {
if (_this._isException(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._isUrl(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (!_this._isLetter(comment)) {
if (_this._isUrl(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!_this._isLetter(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._isTextBlock(file, comment)) {
if (!_this._isLetter(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._isTextBlock(file, comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._isValid(comment)) {
if (_this._isTextBlock(file, comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._isValid(comment)) {···
return;
}
✓ Negative was executed (else)
}···

add(comment);
if (_this._isValid(comment)) {
return;
}
add(comment);
});
Function (anonymous_844)
✓ Was called
file.iterateTokensByType('CommentBlock', function(comment) {···
if (_this._isException(comment)) {
return;
}

if (_this._isUrl(comment)) {
return;
}

if (!_this._isLetter(comment)) {
return;
}

if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
return;
}

if (_this._isValid(comment)) {
return;
}

add(comment);
});
file.iterateTokensByType('CommentBlock', function(comment) {
Branch IfStatement
✓ Positive was executed (if)
if (_this._isException(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._isUrl(comment)) {
if (_this._isException(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._isUrl(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (!_this._isLetter(comment)) {
if (_this._isUrl(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!_this._isLetter(comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
if (!_this._isLetter(comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._isValid(comment)) {
if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._isValid(comment)) {···
return;
}
✓ Negative was executed (else)
}···

add(comment);
if (_this._isValid(comment)) {
return;
}
add(comment);
});
},
Function (anonymous_845)
✓ Was called
_fix: function(file, error) {···
var comment = error.additional;
var first = this._getFirstChar(comment);

var newValue = comment.value.replace(first, first.toUpperCase());
var newComment = new cst.Token(comment.type, newValue);

comment.parentElement.replaceChild(newComment, comment);
}
_fix: function(file, error) {
var comment = error.additional;
var first = this._getFirstChar(comment);
var newValue = comment.value.replace(first, first.toUpperCase());
var newComment = new cst.Token(comment.type, newValue);
comment.parentElement.replaceChild(newComment, comment);
}
};
require-capitalized-constructors-new.js
/**
* Requires capitalized constructors to to use the `new` keyword
*
* Types: `Boolean` or `Object`
*
* Values: `true` or Object with `allExcept` Array of quoted identifiers which are exempted
*
* JSHint: [`newcap`](http://jshint.com/docs/options/#newcap)
*
* #### Example
*
* ```js
* "requireCapitalizedConstructorsNew": true
* "requireCapitalizedConstructorsNew": {
* "allExcept": ["SomethingNative"]
* }
* ```
*
* ##### Valid
*
* ```js
* var a = new B();
* var c = SomethingNative();
* ```
*
* ##### Invalid
*
* ```js
* var d = E();
* ```
*/
var assert = require('assert');
Function (anonymous_846)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_847)
✓ Was called
configure: function(options) {···
assert(
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);
this._allowedConstructors = {};

var allExcept = options.allExcept;
if (allExcept) {
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || Array.isArray(options.allExcept),
✓ Was returned
options === true || Array.isArray(options.allExcept),
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);
this._allowedConstructors = {};
var allExcept = options.allExcept;
Branch IfStatement
✓ Positive was executed (if)
if (allExcept) {···
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
✓ Negative was executed (else)
}···
},
if (allExcept) {
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
},
Function (anonymous_848)
✓ Was called
getOptionName: function() {···
return 'requireCapitalizedConstructorsNew';
},
getOptionName: function() {
return 'requireCapitalizedConstructorsNew';
},
Function (anonymous_849)
✓ Was called
check: function(file, errors) {···
var allowedConstructors = this._allowedConstructors;

file.iterateNodesByType('CallExpression', function(node) {
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toLowerCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should use the "new" keyword',
node.callee
);
}
});
}
check: function(file, errors) {
var allowedConstructors = this._allowedConstructors;
Function (anonymous_850)
✓ Was called
file.iterateNodesByType('CallExpression', function(node) {···
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toLowerCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should use the "new" keyword',
node.callee
);
}
});
file.iterateNodesByType('CallExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add(
'Constructor functions should use the "new" keyword',
node.callee
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
node.callee.name[0].toLowerCase() !== node.callee.name[0]
✓ Was returned
if (node.callee.type === 'Identifier' &&···
!allowedConstructors[node.callee.name] &&
Branch LogicalExpression
✓ Was returned
!allowedConstructors[node.callee.name] &&
✓ Was returned
if (node.callee.type === 'Identifier' &&
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toLowerCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should use the "new" keyword',
node.callee
);
}
});
}
};
require-capitalized-constructors.js
/**
* Requires constructors to be capitalized (except for `this`)
*
* Types: `Boolean` or `Object`
*
* Values: `true` or Object with `allExcept` Array of quoted identifiers which are exempted
*
* JSHint: [`newcap`](http://jshint.com/docs/options/#newcap)
*
* #### Example
*
* ```js
* "requireCapitalizedConstructors": true
* "requireCapitalizedConstructors": {
* "allExcept": ["somethingNative"]
* }
* ```
*
* ##### Valid
*
* ```js
* var a = new B();
* var c = new this();
* var d = new somethingNative();
* ```
*
* ##### Invalid
*
* ```js
* var d = new e();
* ```
*/
var assert = require('assert');
Function (anonymous_851)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_852)
✓ Was called
configure: function(options) {···
assert(
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);
this._allowedConstructors = {};

var allExcept = options.allExcept;
if (allExcept) {
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || Array.isArray(options.allExcept),
✓ Was returned
options === true || Array.isArray(options.allExcept),
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);
this._allowedConstructors = {};
var allExcept = options.allExcept;
Branch IfStatement
✓ Positive was executed (if)
if (allExcept) {···
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
✓ Negative was executed (else)
}···
},
if (allExcept) {
for (var i = 0, l = allExcept.length; i < l; i++) {
this._allowedConstructors[allExcept[i]] = true;
}
}
},
Function (anonymous_853)
✓ Was called
getOptionName: function() {···
return 'requireCapitalizedConstructors';
},
getOptionName: function() {
return 'requireCapitalizedConstructors';
},
Function (anonymous_854)
✓ Was called
check: function(file, errors) {···
var allowedConstructors = this._allowedConstructors;

file.iterateNodesByType('NewExpression', function(node) {
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toUpperCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should be capitalized',
node.callee
);
}
});
}
check: function(file, errors) {
var allowedConstructors = this._allowedConstructors;
Function (anonymous_855)
✓ Was called
file.iterateNodesByType('NewExpression', function(node) {···
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toUpperCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should be capitalized',
node.callee
);
}
});
file.iterateNodesByType('NewExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add(
'Constructor functions should be capitalized',
node.callee
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
node.callee.name[0].toUpperCase() !== node.callee.name[0]
✓ Was returned
if (node.callee.type === 'Identifier' &&···
!allowedConstructors[node.callee.name] &&
Branch LogicalExpression
✓ Was returned
!allowedConstructors[node.callee.name] &&
✓ Was returned
if (node.callee.type === 'Identifier' &&
if (node.callee.type === 'Identifier' &&
!allowedConstructors[node.callee.name] &&
node.callee.name[0].toUpperCase() !== node.callee.name[0]
) {
errors.add(
'Constructor functions should be capitalized',
node.callee
);
}
});
}
};
require-comma-before-line-break.js
/**
* Requires commas as last token on a line in lists.
*
* Type: `Boolean`
*
* Value: `true`
*
* JSHint: [`laxcomma`](http://www.jshint.com/docs/options/#laxcomma)
*
* #### Example
*
* ```js
* "requireCommaBeforeLineBreak": true
* ```
*
* ##### Valid
*
* ```js
* var x = {
* one: 1,
* two: 2
* };
* var y = { three: 3, four: 4};
* ```
*
* ##### Invalid
*
* ```js
* var x = {
* one: 1
* , two: 2
* };
* ```
*/
var assert = require('assert');
Function (anonymous_856)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_857)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_858)
✓ Was called
getOptionName: function() {···
return 'requireCommaBeforeLineBreak';
},
getOptionName: function() {
return 'requireCommaBeforeLineBreak';
},
Function (anonymous_859)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();

if (prevToken.value === ',') {
return;
}
errors.assert.sameLine({
token: prevToken,
nextToken: token,
message: 'Commas should not be placed on new line'
});
});
}
check: function(file, errors) {
Function (anonymous_860)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
var prevToken = token.getPreviousCodeToken();

if (prevToken.value === ',') {
return;
}
errors.assert.sameLine({
token: prevToken,
nextToken: token,
message: 'Commas should not be placed on new line'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value === ',') {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.sameLine({
if (prevToken.value === ',') {
return;
}
errors.assert.sameLine({
token: prevToken,
nextToken: token,
message: 'Commas should not be placed on new line'
});
});
}
};
require-curly-braces.js
/**
* Requires curly braces after statements.
*
* Types: `Array` or `Boolean` or `Object`
*
* Values:
* - Array of quoted keywords
* - `true` to require curly braces after the following keywords
* - `Object`
* - `'keywords'`
* - Array of quoted keywords
* - `'allExcept'`
* - Array of keywords inside of the block that would allow curly braces
* - Ex: ["return" , "continue", "break"]
*
* JSHint: [`curly`](http://jshint.com/docs/options/#curly)
*
* #### Example
*
* ```js
* "requireCurlyBraces": [
* "if",
* "else",
* "for",
* "while",
* "do",
* "try",
* "catch",
* "case",
* "default"
* ]
* ```
*
* ##### Valid
*
* ```js
* if (x) {
* x++;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (x) x++;
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').curlyBracedKeywords;
Function (anonymous_861)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_862)
✓ Was called
configure: function(options) {···
assert(
Array.isArray(options) || options === true || typeof options === 'object',
this.getOptionName() + ' option requires array, true value, or object'
);

var keywordMap = {
'return': 'ReturnStatement',
'break': 'BreakStatement',
'continue': 'ContinueStatement'
};

if (options === true) {
options = defaultKeywords;
}

if (!Array.isArray(options)) {
assert(
Array.isArray(options.allExcept),
this.getOptionName() + '.allExcept ' +
'property requires an array value'
);
assert(
Array.isArray(options.keywords) || options.keywords === true,
this.getOptionName() + '.keywords ' +
'property requires an array value or a value of true'
);

if (options.keywords === true) {
options.keywords = defaultKeywords;
}

this._exceptions = options.allExcept.map(function(statementType) {
return keywordMap[statementType];
});
options = options.keywords;
}

this._typeIndex = {};
for (var i = 0, l = options.length; i < l; i++) {
this._typeIndex[options[i]] = true;
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(options) || options === true || typeof options === 'object',
✓ Was returned
Array.isArray(options) || options === true || typeof options === 'object',
Branch LogicalExpression
✓ Was returned
Array.isArray(options) || options === true || typeof options === 'object',
✓ Was returned
Array.isArray(options) || options === true || typeof options === 'object',
Array.isArray(options) || options === true || typeof options === 'object',
this.getOptionName() + ' option requires array, true value, or object'
);
var keywordMap = {
'return': 'ReturnStatement',
'break': 'BreakStatement',
'continue': 'ContinueStatement'
};
Branch IfStatement
✓ Positive was executed (if)
if (options === true) {···
options = defaultKeywords;
}
✓ Negative was executed (else)
}···

if (!Array.isArray(options)) {
if (options === true) {
options = defaultKeywords;
}
Branch IfStatement
✓ Positive was executed (if)
if (!Array.isArray(options)) {···
assert(
Array.isArray(options.allExcept),
this.getOptionName() + '.allExcept ' +
'property requires an array value'
);
assert(
Array.isArray(options.keywords) || options.keywords === true,
this.getOptionName() + '.keywords ' +
'property requires an array value or a value of true'
);

if (options.keywords === true) {
options.keywords = defaultKeywords;
}

this._exceptions = options.allExcept.map(function(statementType) {
return keywordMap[statementType];
});
options = options.keywords;
}
✓ Negative was executed (else)
}···

this._typeIndex = {};
if (!Array.isArray(options)) {
assert(
Array.isArray(options.allExcept),
this.getOptionName() + '.allExcept ' +
'property requires an array value'
);
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(options.keywords) || options.keywords === true,
✓ Was returned
Array.isArray(options.keywords) || options.keywords === true,
Array.isArray(options.keywords) || options.keywords === true,
this.getOptionName() + '.keywords ' +
'property requires an array value or a value of true'
);
Branch IfStatement
✓ Positive was executed (if)
if (options.keywords === true) {···
options.keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._exceptions = options.allExcept.map(function(statementType) {
if (options.keywords === true) {
options.keywords = defaultKeywords;
}
Function (anonymous_863)
✓ Was called
this._exceptions = options.allExcept.map(function(statementType) {···
return keywordMap[statementType];
});
this._exceptions = options.allExcept.map(function(statementType) {
return keywordMap[statementType];
});
options = options.keywords;
}
this._typeIndex = {};
for (var i = 0, l = options.length; i < l; i++) {
this._typeIndex[options[i]] = true;
}
},
Function (anonymous_864)
✓ Was called
getOptionName: function() {···
return 'requireCurlyBraces';
},
getOptionName: function() {
return 'requireCurlyBraces';
},
Function (anonymous_865)
✓ Was called
check: function(file, errors) {···
var typeIndex = this._typeIndex;
var exceptions = this._exceptions;

function isNotABlockStatement(node) {
return node && node.type !== 'BlockStatement';
}

function addError(typeString, entity) {
errors.add(
typeString + ' statement without curly braces',
entity
);
}

function checkBody(type, typeString) {
file.iterateNodesByType(type, function(node) {
if (isNotABlockStatement(node.body)) {
addError(typeString, node);
}
});
}

if (typeIndex.if || typeIndex.else) {
file.iterateNodesByType('IfStatement', function(node) {
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
// console.log(node.firstChild.getSourceCode());
addError('If', node.firstChild);
}
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
node.alternate.type !== 'IfStatement' &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
addError('Else', node.alternate.getPreviousCodeToken());
}
});
}

if (typeIndex.case || typeIndex.default) {
file.iterateNodesByType('SwitchCase', function(node) {
// empty case statement
if (node.consequent.length === 0) {
return;
}

if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
return;
}

if (node.test === null && typeIndex.default) {
addError('Default', node);
}

if (node.test !== null && typeIndex.case) {
addError('Case', node);
}
});
}

if (typeIndex.while) {
checkBody('WhileStatement', 'While');
}

if (typeIndex.for) {
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}

if (typeIndex.do) {
checkBody('DoWhileStatement', 'Do while');
}

if (typeIndex.with) {
checkBody('WithStatement', 'With');
}
}
check: function(file, errors) {
var typeIndex = this._typeIndex;
var exceptions = this._exceptions;
Function isNotABlockStatement
✓ Was called
function isNotABlockStatement(node) {···
return node && node.type !== 'BlockStatement';
}
function isNotABlockStatement(node) {
Branch LogicalExpression
✓ Was returned
return node && node.type !== 'BlockStatement';
✓ Was returned
return node && node.type !== 'BlockStatement';
return node && node.type !== 'BlockStatement';
}
Function addError
✓ Was called
function addError(typeString, entity) {···
errors.add(
typeString + ' statement without curly braces',
entity
);
}
function addError(typeString, entity) {
errors.add(
typeString + ' statement without curly braces',
entity
);
}
Function checkBody
✓ Was called
function checkBody(type, typeString) {···
file.iterateNodesByType(type, function(node) {
if (isNotABlockStatement(node.body)) {
addError(typeString, node);
}
});
}
function checkBody(type, typeString) {
Function (anonymous_869)
✓ Was called
file.iterateNodesByType(type, function(node) {···
if (isNotABlockStatement(node.body)) {
addError(typeString, node);
}
});
file.iterateNodesByType(type, function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isNotABlockStatement(node.body)) {···
addError(typeString, node);
}
✓ Negative was executed (else)
}···
});
if (isNotABlockStatement(node.body)) {
addError(typeString, node);
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.if || typeIndex.else) {···
file.iterateNodesByType('IfStatement', function(node) {
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
// console.log(node.firstChild.getSourceCode());
addError('If', node.firstChild);
}
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
node.alternate.type !== 'IfStatement' &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
addError('Else', node.alternate.getPreviousCodeToken());
}
});
}
✓ Negative was executed (else)
}···

if (typeIndex.case || typeIndex.default) {
Branch LogicalExpression
✓ Was returned
if (typeIndex.if || typeIndex.else) {
✓ Was returned
if (typeIndex.if || typeIndex.else) {
if (typeIndex.if || typeIndex.else) {
Function (anonymous_870)
✓ Was called
file.iterateNodesByType('IfStatement', function(node) {···
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
// console.log(node.firstChild.getSourceCode());
addError('If', node.firstChild);
}
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
node.alternate.type !== 'IfStatement' &&
// check exceptions for if and else
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
addError('Else', node.alternate.getPreviousCodeToken());
}
});
file.iterateNodesByType('IfStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {···
// console.log(node.firstChild.getSourceCode());
addError('If', node.firstChild);
}
✓ Negative was executed (else)
}···
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
Branch LogicalExpression
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
✓ Was returned
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
Branch LogicalExpression
✓ Was returned
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
✓ Was returned
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
if (typeIndex.if && isNotABlockStatement(node.consequent) &&
// check exceptions for if and else
Branch LogicalExpression
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
// console.log(node.firstChild.getSourceCode());
addError('If', node.firstChild);
}
Branch IfStatement
✓ Positive was executed (if)
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {···
addError('Else', node.alternate.getPreviousCodeToken());
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
✓ Was returned
if (typeIndex.else && isNotABlockStatement(node.alternate) &&···
node.alternate.type !== 'IfStatement' &&
Branch LogicalExpression
✓ Was returned
node.alternate.type !== 'IfStatement' &&
✓ Was returned
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
Branch LogicalExpression
✓ Was returned
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
✓ Was returned
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
if (typeIndex.else && isNotABlockStatement(node.alternate) &&
node.alternate.type !== 'IfStatement' &&
// check exceptions for if and else
Branch LogicalExpression
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
✓ Was returned
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
!(exceptions && exceptions.indexOf(node.consequent.type) !== -1)) {
addError('Else', node.alternate.getPreviousCodeToken());
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.case || typeIndex.default) {···
file.iterateNodesByType('SwitchCase', function(node) {
// empty case statement
if (node.consequent.length === 0) {
return;
}

if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
return;
}

if (node.test === null && typeIndex.default) {
addError('Default', node);
}

if (node.test !== null && typeIndex.case) {
addError('Case', node);
}
});
}
✓ Negative was executed (else)
}···

if (typeIndex.while) {
Branch LogicalExpression
✓ Was returned
if (typeIndex.case || typeIndex.default) {
✓ Was returned
if (typeIndex.case || typeIndex.default) {
if (typeIndex.case || typeIndex.default) {
Function (anonymous_871)
✓ Was called
file.iterateNodesByType('SwitchCase', function(node) {···
// empty case statement
if (node.consequent.length === 0) {
return;
}

if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
return;
}

if (node.test === null && typeIndex.default) {
addError('Default', node);
}

if (node.test !== null && typeIndex.case) {
addError('Case', node);
}
});
file.iterateNodesByType('SwitchCase', function(node) {
// empty case statement
Branch IfStatement
✓ Positive was executed (if)
if (node.consequent.length === 0) {···
return;
}
✓ Negative was executed (else)
}···

if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
if (node.consequent.length === 0) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {···
return;
}
✓ Negative was executed (else)
}···

if (node.test === null && typeIndex.default) {
Branch LogicalExpression
✓ Was returned
if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
✓ Was returned
if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
if (node.consequent.length === 1 && node.consequent[0].type === 'BlockStatement') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (node.test === null && typeIndex.default) {···
addError('Default', node);
}
✓ Negative was executed (else)
}···

if (node.test !== null && typeIndex.case) {
Branch LogicalExpression
✓ Was returned
if (node.test === null && typeIndex.default) {
✓ Was returned
if (node.test === null && typeIndex.default) {
if (node.test === null && typeIndex.default) {
addError('Default', node);
}
Branch IfStatement
✓ Positive was executed (if)
if (node.test !== null && typeIndex.case) {···
addError('Case', node);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (node.test !== null && typeIndex.case) {
✓ Was returned
if (node.test !== null && typeIndex.case) {
if (node.test !== null && typeIndex.case) {
addError('Case', node);
}
});
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.while) {···
checkBody('WhileStatement', 'While');
}
✓ Negative was executed (else)
}···

if (typeIndex.for) {
if (typeIndex.while) {
checkBody('WhileStatement', 'While');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.for) {···
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}
✓ Negative was executed (else)
}···

if (typeIndex.do) {
if (typeIndex.for) {
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.do) {···
checkBody('DoWhileStatement', 'Do while');
}
✓ Negative was executed (else)
}···

if (typeIndex.with) {
if (typeIndex.do) {
checkBody('DoWhileStatement', 'Do while');
}
Branch IfStatement
✓ Positive was executed (if)
if (typeIndex.with) {···
checkBody('WithStatement', 'With');
}
✓ Negative was executed (else)
}···
}
if (typeIndex.with) {
checkBody('WithStatement', 'With');
}
}
};
require-dollar-before-jquery-assignment.js
/**
* Require a $ before variable names that are jquery assignments.
*
* Types: `Boolean` or `String`
*
* Values: `true` or `"ignoreProperties"`
*
* #### Example
*
* ```js
* "requireDollarBeforejQueryAssignment": true
* ```
*
* ##### Valid example for mode `true`
*
* ```js
* var $x = $(".foo");
* var y = {
* $x: $(".bar")
* };
* ```
*
* ##### Invalid example for mode `true`
*
* ```js
* var x = $(".foo");
* var y = {
* x: $(".bar")
* };
* ```
*
* ##### Valid example for mode `ignoreProperties`
*
* ```js
* var $x = $(".foo");
* var y = {
* x: $(".bar")
* };
* ```
*
* ##### Invalid example for mode `ignoreProperties`
*
* ```js
* var x = $(".foo");
* ```
*/
var assert = require('assert');
Function (anonymous_872)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
_ignoreProperties: false,
Function (anonymous_873)
✓ Was called
configure: function(options) {···
assert(
options === true || options === 'ignoreProperties',
this.getOptionName() + ' option requires true or "ignoreProperties" value, or should be removed'
);

this._ignoreProperties = (options === 'ignoreProperties');
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'ignoreProperties',
✓ Was returned
options === true || options === 'ignoreProperties',
options === true || options === 'ignoreProperties',
this.getOptionName() + ' option requires true or "ignoreProperties" value, or should be removed'
);
this._ignoreProperties = (options === 'ignoreProperties');
},
Function (anonymous_874)
✓ Was called
getOptionName: function() {···
return 'requireDollarBeforejQueryAssignment';
},
getOptionName: function() {
return 'requireDollarBeforejQueryAssignment';
},
Function (anonymous_875)
✓ Was called
check: function(file, errors) {···
var ignoreProperties = this._ignoreProperties;

file.iterateNodesByType(['VariableDeclarator', 'AssignmentExpression', 'ObjectExpression'], function(node) {
var type = node.type;
var left;
var varName;
var right;

function checkIfVarNameShouldStartWithDollar(varName, left, right) {

if (/^_?\$/.test(varName)) {
return;
}

if (!right || right.type !== 'CallExpression') {
return;
}

var nextToken = right.callee.firstChild;
if (nextToken.value !== '$') {
return;
}

nextToken = file.getNextToken(nextToken);
if (nextToken.value !== '(') {
return;
}

while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
nextToken = file.getNextToken(nextToken);
}

nextToken = file.getNextToken(nextToken);
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
errors.add(
'jQuery identifiers must start with a $',
left
);
}
}

if (type === 'VariableDeclarator') {
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
return;
}

left = node.id;
varName = left.name;
right = node.init;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else if (ignoreProperties) {
return;

} else if (type === 'AssignmentExpression') {
left = node.left;
if (left.computed || left.type === 'ArrayPattern') {
return;
}

varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
var props = node.properties;

if (!props) {
return;
}

props.forEach(function(prop) {
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}

});
}
check: function(file, errors) {
var ignoreProperties = this._ignoreProperties;
Function (anonymous_876)
✓ Was called
file.iterateNodesByType(['VariableDeclarator', 'AssignmentExpression', 'ObjectExpression'], function(node) {···
var type = node.type;
var left;
var varName;
var right;

function checkIfVarNameShouldStartWithDollar(varName, left, right) {

if (/^_?\$/.test(varName)) {
return;
}

if (!right || right.type !== 'CallExpression') {
return;
}

var nextToken = right.callee.firstChild;
if (nextToken.value !== '$') {
return;
}

nextToken = file.getNextToken(nextToken);
if (nextToken.value !== '(') {
return;
}

while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
nextToken = file.getNextToken(nextToken);
}

nextToken = file.getNextToken(nextToken);
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
errors.add(
'jQuery identifiers must start with a $',
left
);
}
}

if (type === 'VariableDeclarator') {
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
return;
}

left = node.id;
varName = left.name;
right = node.init;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else if (ignoreProperties) {
return;

} else if (type === 'AssignmentExpression') {
left = node.left;
if (left.computed || left.type === 'ArrayPattern') {
return;
}

varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
var props = node.properties;

if (!props) {
return;
}

props.forEach(function(prop) {
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}

});
file.iterateNodesByType(['VariableDeclarator', 'AssignmentExpression', 'ObjectExpression'], function(node) {
var type = node.type;
var left;
var varName;
var right;
Function checkIfVarNameShouldStartWithDollar
✓ Was called
function checkIfVarNameShouldStartWithDollar(varName, left, right) {···

if (/^_?\$/.test(varName)) {
return;
}

if (!right || right.type !== 'CallExpression') {
return;
}

var nextToken = right.callee.firstChild;
if (nextToken.value !== '$') {
return;
}

nextToken = file.getNextToken(nextToken);
if (nextToken.value !== '(') {
return;
}

while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
nextToken = file.getNextToken(nextToken);
}

nextToken = file.getNextToken(nextToken);
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
errors.add(
'jQuery identifiers must start with a $',
left
);
}
}
function checkIfVarNameShouldStartWithDollar(varName, left, right) {
Branch IfStatement
✓ Positive was executed (if)
if (/^_?\$/.test(varName)) {···
return;
}
✓ Negative was executed (else)
}···

if (!right || right.type !== 'CallExpression') {
if (/^_?\$/.test(varName)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!right || right.type !== 'CallExpression') {···
return;
}
✓ Negative was executed (else)
}···

var nextToken = right.callee.firstChild;
Branch LogicalExpression
✓ Was returned
if (!right || right.type !== 'CallExpression') {
✓ Was returned
if (!right || right.type !== 'CallExpression') {
if (!right || right.type !== 'CallExpression') {
return;
}
var nextToken = right.callee.firstChild;
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value !== '$') {···
return;
}
✓ Negative was executed (else)
}···

nextToken = file.getNextToken(nextToken);
if (nextToken.value !== '$') {
return;
}
nextToken = file.getNextToken(nextToken);
Branch IfStatement
✗ Positive was not executed (if)
if (nextToken.value !== '(') {···
return;
}
✓ Negative was executed (else)
}···

while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
if (nextToken.value !== '(') {
return;
}
Branch LogicalExpression
✓ Was returned
while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
✓ Was returned
while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
while (!(nextToken.type === 'Punctuator' && nextToken.value === ')')) {
nextToken = file.getNextToken(nextToken);
}
nextToken = file.getNextToken(nextToken);
Branch IfStatement
✓ Positive was executed (if)
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {···
errors.add(
'jQuery identifiers must start with a $',
left
);
}
✗ Negative was not executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
✗ Was not returned
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
Branch LogicalExpression
✓ Was returned
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
✓ Was returned
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
if (!nextToken || !(nextToken.type === 'Punctuator' && nextToken.value === '.')) {
errors.add(
'jQuery identifiers must start with a $',
left
);
}
}
Branch IfStatement
✓ Positive was executed (if)
if (type === 'VariableDeclarator') {···
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
return;
}

left = node.id;
varName = left.name;
right = node.init;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else if (ignoreProperties) {
✓ Negative was executed (else)
} else if (ignoreProperties) {···
return;

} else if (type === 'AssignmentExpression') {
left = node.left;
if (left.computed || left.type === 'ArrayPattern') {
return;
}

varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
var props = node.properties;

if (!props) {
return;
}

props.forEach(function(prop) {
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}
if (type === 'VariableDeclarator') {
Branch IfStatement
✓ Positive was executed (if)
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {···
return;
}
✓ Negative was executed (else)
}···

left = node.id;
Branch LogicalExpression
✓ Was returned
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
✓ Was returned
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
if (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern') {
return;
}
left = node.id;
varName = left.name;
right = node.init;
checkIfVarNameShouldStartWithDollar(varName, left, right);
Branch IfStatement
✓ Positive was executed (if)
} else if (ignoreProperties) {···
return;

} else if (type === 'AssignmentExpression') {
✓ Negative was executed (else)
} else if (type === 'AssignmentExpression') {···
left = node.left;
if (left.computed || left.type === 'ArrayPattern') {
return;
}

varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
var props = node.properties;

if (!props) {
return;
}

props.forEach(function(prop) {
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}
} else if (ignoreProperties) {
return;
Branch IfStatement
✓ Positive was executed (if)
} else if (type === 'AssignmentExpression') {···
left = node.left;
if (left.computed || left.type === 'ArrayPattern') {
return;
}

varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
✓ Negative was executed (else)
} else {// type === 'ObjectExpression'···
var props = node.properties;

if (!props) {
return;
}

props.forEach(function(prop) {
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}
} else if (type === 'AssignmentExpression') {
left = node.left;
Branch IfStatement
✓ Positive was executed (if)
if (left.computed || left.type === 'ArrayPattern') {···
return;
}
✓ Negative was executed (else)
}···

varName = left.name || left.property.name;
Branch LogicalExpression
✓ Was returned
if (left.computed || left.type === 'ArrayPattern') {
✓ Was returned
if (left.computed || left.type === 'ArrayPattern') {
if (left.computed || left.type === 'ArrayPattern') {
return;
}
Branch LogicalExpression
✓ Was returned
varName = left.name || left.property.name;
✓ Was returned
varName = left.name || left.property.name;
varName = left.name || left.property.name;
right = node.right;
checkIfVarNameShouldStartWithDollar(varName, left, right);
} else {// type === 'ObjectExpression'
var props = node.properties;
Branch IfStatement
✗ Positive was not executed (if)
if (!props) {···
return;
}
✓ Negative was executed (else)
}···

props.forEach(function(prop) {
if (!props) {
return;
}
Function (anonymous_878)
✓ Was called
props.forEach(function(prop) {···
left = prop.key;

if (!left || !left.name) {
return;
}

varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
props.forEach(function(prop) {
left = prop.key;
Branch IfStatement
✓ Positive was executed (if)
if (!left || !left.name) {···
return;
}
✓ Negative was executed (else)
}···

varName = left.name;
Branch LogicalExpression
✓ Was returned
if (!left || !left.name) {
✓ Was returned
if (!left || !left.name) {
if (!left || !left.name) {
return;
}
varName = left.name;
right = prop.value;
checkIfVarNameShouldStartWithDollar(varName, left, right);
});
}
});
}
};
require-dot-notation.js
/**
* Requires member expressions to use dot notation when possible
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `"except_snake_case"` (*deprecated* use `"allExcept": ["snake_case"]`) allow quoted snake cased identifiers
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'keywords'` allow quoted identifiers made of reserved words
* - `'snake_case'` allow quoted snake cased identifiers
*
* N.B.: keywords are always allowed with es3 enabled (http://jscs.info/overview.html#es3)
*
* JSHint: [`sub`](http://www.jshint.com/docs/options/#sub)
*
* #### Example
*
* ```js
* "requireDotNotation": true
* ```
*
* ##### Valid
*
* ```js
* var a = b[c];
* var a = b.c;
* var a = b[c.d];
* var a = b[1];
* var a = b.while; // reserved words can be property names in ES5
* ```
*
* ##### Invalid
*
* ```js
* var a = b['c'];
* var a = b['snake_cased'];
* var a = b['_camelCased'];
* var a = b['camelCased_'];
* ```
*
* #### Example for allExcept snake_case
*
* ```js
* "requireDotNotation": { "allExcept": [ "snake_case" ] }
* ```
*
* ##### Valid
* ```js
* var a = b[c];
* var a = b.c;
* var a = b['snake_cased'];
* var a = b['camelCased_butWithSnakes'];
* ```
*
* #### Example for allExcept keywords
*
* ```js
* "requireDotNotation": { "allExcept": [ "keywords" ] }
* ```
*
* ##### Valid
*
* ```js
* var a = b['await']; // reserved word in ES6
* var a = b['yield']; // reserved word in ES5
* var a = b['let'];
* ```
*
* ##### Invalid
*
* ```js
* var a = b['c'];
* ```
*
* #### Example for `"es3": true`
*
* ```js
* "requireDotNotation": true,
* "es3": true
* ```
*
* ##### Valid
*
* ```js
* var a = b[c];
* var a = b.c;
* var a = b[c.d];
* var a = b[1];
* var a = b['while']; // reserved word in ES3
* ```
*
* ##### Invalid
*
* ```js
* var a = b['c'];
* ```
*/
var assert = require('assert');
var utils = require('../utils');
var reservedWords = require('reserved-words');
Function (anonymous_879)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_880)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true || options === 'except_snake_case',
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {};
if (options === 'except_snake_case') {
_options.allExcept = ['snake_case'];
}

return this.configure(_options);
}

assert(
!options.allExcept || Array.isArray(options.allExcept),
'allExcept value of ' + this.getOptionName() + ' option requires an array with exceptions'
);

if (Array.isArray(options.allExcept)) {
this._exceptSnakeCase = options.allExcept.indexOf('snake_case') > -1;
this._exceptKeywords = options.allExcept.indexOf('keywords') > -1;
}
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true || options === 'except_snake_case',
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {};
if (options === 'except_snake_case') {
_options.allExcept = ['snake_case'];
}

return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
Branch LogicalExpression
✓ Was returned
options === true || options === 'except_snake_case',
✓ Was returned
options === true || options === 'except_snake_case',
options === true || options === 'except_snake_case',
this.getOptionName() + ' option requires either a true value or an object'
);
var _options = {};
Branch IfStatement
✓ Positive was executed (if)
if (options === 'except_snake_case') {···
_options.allExcept = ['snake_case'];
}
✓ Negative was executed (else)
}···

return this.configure(_options);
if (options === 'except_snake_case') {
_options.allExcept = ['snake_case'];
}
return this.configure(_options);
}
assert(
Branch LogicalExpression
✓ Was returned
!options.allExcept || Array.isArray(options.allExcept),
✓ Was returned
!options.allExcept || Array.isArray(options.allExcept),
!options.allExcept || Array.isArray(options.allExcept),
'allExcept value of ' + this.getOptionName() + ' option requires an array with exceptions'
);
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._exceptSnakeCase = options.allExcept.indexOf('snake_case') > -1;
this._exceptKeywords = options.allExcept.indexOf('keywords') > -1;
}
✓ Negative was executed (else)
}···
},
if (Array.isArray(options.allExcept)) {
this._exceptSnakeCase = options.allExcept.indexOf('snake_case') > -1;
this._exceptKeywords = options.allExcept.indexOf('keywords') > -1;
}
},
Function (anonymous_881)
✓ Was called
getOptionName: function() {···
return 'requireDotNotation';
},
getOptionName: function() {
return 'requireDotNotation';
},
Function (anonymous_882)
✓ Was called
check: function(file, errors) {···
var exceptSnakeCase = this._exceptSnakeCase;
var exceptKeywords = this._exceptKeywords;

var dialect = file.getDialect();
file.iterateNodesByType('MemberExpression', function(node) {
if (!node.computed || node.property.type !== 'StringLiteral') {
return;
}

var value = node.property.value;
if (// allow numbers, nulls, and anything else
typeof value !== 'string' ||
// allow invalid identifiers
!utils.isValidIdentifierName(value, file.getDialect()) ||
// allow quoted snake cased identifiers if allExcept: ['snake_case']
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
// allow quoted reserved words if allExcept: ['keywords']
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
) {
return;
}

errors.add('Use dot notation instead of brackets for member expressions', node.property);
});
}
check: function(file, errors) {
var exceptSnakeCase = this._exceptSnakeCase;
var exceptKeywords = this._exceptKeywords;
var dialect = file.getDialect();
Function (anonymous_883)
✓ Was called
file.iterateNodesByType('MemberExpression', function(node) {···
if (!node.computed || node.property.type !== 'StringLiteral') {
return;
}

var value = node.property.value;
if (// allow numbers, nulls, and anything else
typeof value !== 'string' ||
// allow invalid identifiers
!utils.isValidIdentifierName(value, file.getDialect()) ||
// allow quoted snake cased identifiers if allExcept: ['snake_case']
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
// allow quoted reserved words if allExcept: ['keywords']
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
) {
return;
}

errors.add('Use dot notation instead of brackets for member expressions', node.property);
});
file.iterateNodesByType('MemberExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (!node.computed || node.property.type !== 'StringLiteral') {···
return;
}
✓ Negative was executed (else)
}···

var value = node.property.value;
Branch LogicalExpression
✓ Was returned
if (!node.computed || node.property.type !== 'StringLiteral') {
✓ Was returned
if (!node.computed || node.property.type !== 'StringLiteral') {
if (!node.computed || node.property.type !== 'StringLiteral') {
return;
}
var value = node.property.value;
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

errors.add('Use dot notation instead of brackets for member expressions', node.property);
if (// allow numbers, nulls, and anything else
Branch LogicalExpression
✓ Was returned
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
✓ Was returned
typeof value !== 'string' ||···
// allow invalid identifiers
!utils.isValidIdentifierName(value, file.getDialect()) ||
// allow quoted snake cased identifiers if allExcept: ['snake_case']
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
Branch LogicalExpression
✓ Was returned
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
✓ Was returned
typeof value !== 'string' ||···
// allow invalid identifiers
!utils.isValidIdentifierName(value, file.getDialect()) ||
Branch LogicalExpression
✓ Was returned
!utils.isValidIdentifierName(value, file.getDialect()) ||
✗ Was not returned
typeof value !== 'string' ||
typeof value !== 'string' ||
// allow invalid identifiers
!utils.isValidIdentifierName(value, file.getDialect()) ||
// allow quoted snake cased identifiers if allExcept: ['snake_case']
Branch LogicalExpression
✓ Was returned
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
✓ Was returned
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
(exceptSnakeCase && utils.isSnakeCased(utils.trimUnderscores(value))) ||
// allow quoted reserved words if allExcept: ['keywords']
Branch LogicalExpression
✗ Was not returned
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
✓ Was returned
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
Branch LogicalExpression
✓ Was returned
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
✗ Was not returned
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
((dialect === 'es3' || exceptKeywords) && reservedWords.check(value, dialect, true))
) {
return;
}
errors.add('Use dot notation instead of brackets for member expressions', node.property);
});
}
};
require-early-return.js
/**
* Requires to return early in a function.
*
* Types: `Boolean`
*
* Values:
* - `true`: disallow to use of else if the corresponding `if` block contain a return.
*
* #### Example
*
* ```js
* "requireEarlyReturn": true
* ```
*
* ##### Valid
*
* ```js
* function test() {
* if (x) {
* return x;
* }
* return y;
* }
* ```
*
* ##### Invalid
*
* ```js
* function test() {
* if (x) {
* return x;
* } else {
* return y;
* }
* }
* ```
*/
var assert = require('assert');
Function (anonymous_884)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_885)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option allow only the `true` value'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option allow only the `true` value'
);
},
Function (anonymous_886)
✓ Was called
getOptionName: function() {···
return 'requireEarlyReturn';
},
getOptionName: function() {
return 'requireEarlyReturn';
},
Function (anonymous_887)
✓ Was called
check: function(file, errors) {···
function addError(entity) {
errors.add(
'Use of else after return',
entity
);
}

// Check if the IfStatement node contain a ReturnStatement.
// If the node has a block, check all the statements in backward order to see if there is one.
// This is to ensure that code like this will still return true:
//
// if (true) {
// return;
// eval();
// }
function hasNodeReturn(node) {
if (node.type === 'BlockStatement') {
for (var i = node.body.length - 1; i >= 0; i--) {
if (node.body[i].type === 'ReturnStatement') {
return true;
}
}
return false;
}
return node.type === 'ReturnStatement';
}

file.iterateNodesByType('IfStatement', function(node) {
if (!node.alternate) {
return;
}

// Check if all the parents have a return statement, if not continue to the following IfStatement node.
//
// Example:
//
// if (foo) {
// return;
// } else if (bar) { <-- error
// bar();
// } else if (baz) { <-- safe
// return baz();
// } else { <-- safe
// bas();
// }
for (var nodeIf = node; nodeIf && nodeIf.type === 'IfStatement'; nodeIf = nodeIf.parentElement) {
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {
return;
}
}

return addError(file.getPrevToken(file.getFirstNodeToken(node.alternate)));
});
}
check: function(file, errors) {
Function addError
✓ Was called
function addError(entity) {···
errors.add(
'Use of else after return',
entity
);
}
function addError(entity) {
errors.add(
'Use of else after return',
entity
);
}
// Check if the IfStatement node contain a ReturnStatement.
// If the node has a block, check all the statements in backward order to see if there is one.
// This is to ensure that code like this will still return true:
//
// if (true) {
// return;
// eval();
// }
Function hasNodeReturn
✓ Was called
function hasNodeReturn(node) {···
if (node.type === 'BlockStatement') {
for (var i = node.body.length - 1; i >= 0; i--) {
if (node.body[i].type === 'ReturnStatement') {
return true;
}
}
return false;
}
return node.type === 'ReturnStatement';
}
function hasNodeReturn(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'BlockStatement') {···
for (var i = node.body.length - 1; i >= 0; i--) {
if (node.body[i].type === 'ReturnStatement') {
return true;
}
}
return false;
}
✓ Negative was executed (else)
}···
return node.type === 'ReturnStatement';
if (node.type === 'BlockStatement') {
for (var i = node.body.length - 1; i >= 0; i--) {
Branch IfStatement
✓ Positive was executed (if)
if (node.body[i].type === 'ReturnStatement') {···
return true;
}
✓ Negative was executed (else)
}···
}
if (node.body[i].type === 'ReturnStatement') {
return true;
}
}
return false;
}
return node.type === 'ReturnStatement';
}
Function (anonymous_890)
✓ Was called
file.iterateNodesByType('IfStatement', function(node) {···
if (!node.alternate) {
return;
}

// Check if all the parents have a return statement, if not continue to the following IfStatement node.
//
// Example:
//
// if (foo) {
// return;
// } else if (bar) { <-- error
// bar();
// } else if (baz) { <-- safe
// return baz();
// } else { <-- safe
// bas();
// }
for (var nodeIf = node; nodeIf && nodeIf.type === 'IfStatement'; nodeIf = nodeIf.parentElement) {
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {
return;
}
}

return addError(file.getPrevToken(file.getFirstNodeToken(node.alternate)));
});
file.iterateNodesByType('IfStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (!node.alternate) {···
return;
}
✓ Negative was executed (else)
}···

// Check if all the parents have a return statement, if not continue to the following IfStatement node.
if (!node.alternate) {
return;
}
// Check if all the parents have a return statement, if not continue to the following IfStatement node.
//
// Example:
//
// if (foo) {
// return;
// } else if (bar) { <-- error
// bar();
// } else if (baz) { <-- safe
// return baz();
// } else { <-- safe
// bas();
// }
Branch LogicalExpression
✓ Was returned
for (var nodeIf = node; nodeIf && nodeIf.type === 'IfStatement'; nodeIf = nodeIf.parentElement) {
✗ Was not returned
for (var nodeIf = node; nodeIf && nodeIf.type === 'IfStatement'; nodeIf = nodeIf.parentElement) {
for (var nodeIf = node; nodeIf && nodeIf.type === 'IfStatement'; nodeIf = nodeIf.parentElement) {
Branch IfStatement
✓ Positive was executed (if)
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {
✓ Was returned
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {
if (nodeIf.alternate && !hasNodeReturn(nodeIf.consequent)) {
return;
}
}
return addError(file.getPrevToken(file.getFirstNodeToken(node.alternate)));
});
}
};
require-enhanced-object-literals.js
/**
* Requires declaring objects via ES6 enhanced object literals
*
* Type: `Boolean`
*
* Values: true
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireEnhancedObjectLiterals": true
* ```
*
* ##### Valid
*
* ```js
* var bar = true;
* var obj = {
* foo() { },
* bar
* };
* ```
*
* ##### Invalid
*
* ```js
* var bar = true;
* var obj = {
* foo: function() { },
* bar: bar
* };
* ```
*/
var assert = require('assert');
var Parser = require('cst').Parser;
Function (anonymous_891)
✓ Was called
var parse = function(code) {···
var program = new Parser().parse('({' + code + '})');
return program.body[0].expression.properties[0];
};
var parse = function(code) {
var program = new Parser().parse('({' + code + '})');
return program.body[0].expression.properties[0];
};
Function (anonymous_892)
✓ Was called
module.exports = function() { };
module.exports = function() { };
module.exports.prototype = {
Function (anonymous_893)
✓ Was called
configure: function(option) {···
assert(option === true, this.getOptionName() + ' requires a true value');
},
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},
Function (anonymous_894)
✓ Was called
getOptionName: function() {···
return 'requireEnhancedObjectLiterals';
},
getOptionName: function() {
return 'requireEnhancedObjectLiterals';
},
Function (anonymous_895)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectProperty', function(node) {
// node.key.name is used when the property key is an unquoted identifier
// node.key.value is used when the property key is a quoted string
var propertyName = node.key.name || node.key.value;
var valueName = node.value.name;
var shorthand = node.shorthand;
var computed = node.computed;

// check for non-shorthand properties
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ propName: propName }` is not allowed.',
node
);
}

// check for non-method function properties
var valueType = node.value.type;
var valueIsMethod = node.method;
if (valueType === 'FunctionExpression' && !valueIsMethod) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ funcName: function() {} }` is not allowed.',
node
);
}
});
},
check: function(file, errors) {
Function (anonymous_896)
✓ Was called
file.iterateNodesByType('ObjectProperty', function(node) {···
// node.key.name is used when the property key is an unquoted identifier
// node.key.value is used when the property key is a quoted string
var propertyName = node.key.name || node.key.value;
var valueName = node.value.name;
var shorthand = node.shorthand;
var computed = node.computed;

// check for non-shorthand properties
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ propName: propName }` is not allowed.',
node
);
}

// check for non-method function properties
var valueType = node.value.type;
var valueIsMethod = node.method;
if (valueType === 'FunctionExpression' && !valueIsMethod) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ funcName: function() {} }` is not allowed.',
node
);
}
});
file.iterateNodesByType('ObjectProperty', function(node) {
// node.key.name is used when the property key is an unquoted identifier
// node.key.value is used when the property key is a quoted string
Branch LogicalExpression
✗ Was not returned
var propertyName = node.key.name || node.key.value;
✓ Was returned
var propertyName = node.key.name || node.key.value;
var propertyName = node.key.name || node.key.value;
var valueName = node.value.name;
var shorthand = node.shorthand;
var computed = node.computed;
// check for non-shorthand properties
Branch IfStatement
✓ Positive was executed (if)
if (propertyName && propertyName === valueName && !(shorthand || computed)) {···
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ propName: propName }` is not allowed.',
node
);
}
✓ Negative was executed (else)
}···

// check for non-method function properties
Branch LogicalExpression
✓ Was returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
✓ Was returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
Branch LogicalExpression
✓ Was returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
✗ Was not returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
Branch LogicalExpression
✓ Was returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
✓ Was returned
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
if (propertyName && propertyName === valueName && !(shorthand || computed)) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ propName: propName }` is not allowed.',
node
);
}
// check for non-method function properties
var valueType = node.value.type;
var valueIsMethod = node.method;
Branch IfStatement
✓ Positive was executed (if)
if (valueType === 'FunctionExpression' && !valueIsMethod) {···
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ funcName: function() {} }` is not allowed.',
node
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (valueType === 'FunctionExpression' && !valueIsMethod) {
✓ Was returned
if (valueType === 'FunctionExpression' && !valueIsMethod) {
if (valueType === 'FunctionExpression' && !valueIsMethod) {
errors.add(
'Property assignment should use enhanced object literal function.\n' +
' `{ funcName: function() {} }` is not allowed.',
node
);
}
});
},
Function (anonymous_897)
✓ Was called
_fix: function(file, error) {···
var elem = error.element;

// Can't fix it yet
if (elem.value.type === 'FunctionExpression') {
return;
}

var element = parse(elem.key.name);
element.remove();
elem.parentElement.replaceChild(element, elem);
}
_fix: function(file, error) {
var elem = error.element;
// Can't fix it yet
Branch IfStatement
✓ Positive was executed (if)
if (elem.value.type === 'FunctionExpression') {···
return;
}
✓ Negative was executed (else)
}···

var element = parse(elem.key.name);
if (elem.value.type === 'FunctionExpression') {
return;
}
var element = parse(elem.key.name);
element.remove();
elem.parentElement.replaceChild(element, elem);
}
};
require-function-declarations.js
/**
* Requires function declarations by disallowing assignment of functions
* expressions to variables. Function expressions are allowed in all other
* contexts, including when passed as function arguments or immediately invoked.
*
* Assignment of function expressions to object members is also permitted, since
* these can't be declared.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireFunctionDeclarations": true
* ```
*
* ##### Valid
*
* ```js
* function declared() {
*
* };
*
* (function iife() {
* void 0;
* })();
*
* var obj = {
* a: function () {}
* };
*
* obj.b = function () { };
*
* $('#foo').click(function bar() {
*
* };)
* ```
*
* ##### Invalid
*
* ```js
* var expressed = function() {
*
* };
*
* var expressed = function deeply() {
*
* };
* ```
*/
var assert = require('assert');
Function (anonymous_898)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_899)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_900)
✓ Was called
getOptionName: function() {···
return 'requireFunctionDeclarations';
},
getOptionName: function() {
return 'requireFunctionDeclarations';
},
Function (anonymous_901)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(
'VariableDeclarator',
function(node) {
if (node.init && node.init.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
);

file.iterateNodesByType(
'AssignmentExpression',
function(node) {
if (node.left.type !== 'MemberExpression' &&
node.right.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
);
}
check: function(file, errors) {
file.iterateNodesByType(
'VariableDeclarator',
Function (anonymous_902)
✓ Was called
function(node) {···
if (node.init && node.init.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.init && node.init.type === 'FunctionExpression') {···
errors.add('Use a function declaration instead', node);
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (node.init && node.init.type === 'FunctionExpression') {
✓ Was returned
if (node.init && node.init.type === 'FunctionExpression') {
if (node.init && node.init.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
);
file.iterateNodesByType(
'AssignmentExpression',
Function (anonymous_903)
✓ Was called
function(node) {···
if (node.left.type !== 'MemberExpression' &&
node.right.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
function(node) {
Branch IfStatement
✓ Positive was executed (if)
node.right.type === 'FunctionExpression') {···
errors.add('Use a function declaration instead', node);
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
node.right.type === 'FunctionExpression') {
✓ Was returned
if (node.left.type !== 'MemberExpression' &&
if (node.left.type !== 'MemberExpression' &&
node.right.type === 'FunctionExpression') {
errors.add('Use a function declaration instead', node);
}
}
);
}
};
require-imports-alphabetized.js
/**
* Requires imports to be alphabetised
*
* Types: `Boolean`
*
* Values: `true` to require imports to be ordered (A-Z)
*
* #### Example
*
* ```js
* "requireImportAlphabetized": true
* ```
*
* ##### Valid
*
* ```js
* import a from 'a';
* import c from 'c';
* import z from 'z';
* ```
*
* ##### Invalid
*
* ```js
* import a from 'a';
* import z from 'z';
* import c from 'c';
* ```
*/
var assert = require('assert');
Function (anonymous_904)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_905)
✓ Was called
configure: function(option) {···
assert(
option === true,
this.getOptionName() + ' option requires true value'
);
},
configure: function(option) {
assert(
option === true,
this.getOptionName() + ' option requires true value'
);
},
Function (anonymous_906)
✓ Was called
getOptionName: function() {···
return 'requireImportAlphabetized';
},
getOptionName: function() {
return 'requireImportAlphabetized';
},
Function (anonymous_907)
✓ Was called
check: function(file, errors) {···

var previous;
var current;

var createSpecHash = function(specifier) {

var imported = '';
var local = '';

if (specifier.imported && specifier.imported.name) {
imported = specifier.imported.name;
}

if (specifier.local && specifier.local.name) {
local = specifier.local.name;
}

return imported === local ? imported : imported + local;

};

file.iterateNodesByType(
'ImportDeclaration',
function(node) {

current = '';

for (var i = 0; i < node.specifiers.length; i++) {
current += createSpecHash(node.specifiers[i]);
}

if (node.source && node.source.value) {
current += node.source.value;
}

if (previous && previous > current) {
errors.add('imports must be alphabetized', node);
}

previous = current;
}
);
}
check: function(file, errors) {
var previous;
var current;
Function (anonymous_908)
✓ Was called
var createSpecHash = function(specifier) {···

var imported = '';
var local = '';

if (specifier.imported && specifier.imported.name) {
imported = specifier.imported.name;
}

if (specifier.local && specifier.local.name) {
local = specifier.local.name;
}

return imported === local ? imported : imported + local;

};
var createSpecHash = function(specifier) {
var imported = '';
var local = '';
Branch IfStatement
✓ Positive was executed (if)
if (specifier.imported && specifier.imported.name) {···
imported = specifier.imported.name;
}
✓ Negative was executed (else)
}···

if (specifier.local && specifier.local.name) {
Branch LogicalExpression
✓ Was returned
if (specifier.imported && specifier.imported.name) {
✓ Was returned
if (specifier.imported && specifier.imported.name) {
if (specifier.imported && specifier.imported.name) {
imported = specifier.imported.name;
}
Branch IfStatement
✓ Positive was executed (if)
if (specifier.local && specifier.local.name) {···
local = specifier.local.name;
}
✗ Negative was not executed (else)
}···

return imported === local ? imported : imported + local;
Branch LogicalExpression
✓ Was returned
if (specifier.local && specifier.local.name) {
✗ Was not returned
if (specifier.local && specifier.local.name) {
if (specifier.local && specifier.local.name) {
local = specifier.local.name;
}
Branch ConditionalExpression
✓ Positive was returned (? ...)
return imported === local ? imported : imported + local;
✓ Negative was returned (: ...)
return imported === local ? imported : imported + local;
return imported === local ? imported : imported + local;
};
file.iterateNodesByType(
'ImportDeclaration',
Function (anonymous_909)
✓ Was called
function(node) {···

current = '';

for (var i = 0; i < node.specifiers.length; i++) {
current += createSpecHash(node.specifiers[i]);
}

if (node.source && node.source.value) {
current += node.source.value;
}

if (previous && previous > current) {
errors.add('imports must be alphabetized', node);
}

previous = current;
}
function(node) {
current = '';
for (var i = 0; i < node.specifiers.length; i++) {
current += createSpecHash(node.specifiers[i]);
}
Branch IfStatement
✓ Positive was executed (if)
if (node.source && node.source.value) {···
current += node.source.value;
}
✗ Negative was not executed (else)
}···

if (previous && previous > current) {
Branch LogicalExpression
✓ Was returned
if (node.source && node.source.value) {
✗ Was not returned
if (node.source && node.source.value) {
if (node.source && node.source.value) {
current += node.source.value;
}
Branch IfStatement
✓ Positive was executed (if)
if (previous && previous > current) {···
errors.add('imports must be alphabetized', node);
}
✓ Negative was executed (else)
}···

previous = current;
Branch LogicalExpression
✓ Was returned
if (previous && previous > current) {
✓ Was returned
if (previous && previous > current) {
if (previous && previous > current) {
errors.add('imports must be alphabetized', node);
}
previous = current;
}
);
}
};
require-keywords-on-new-line.js
/**
* Requires placing keywords on a new line.
*
* Type: `Array`
*
* Values: Array of quoted keywords
*
* #### Example
*
* ```js
* "requireKeywordsOnNewLine": ["else"]
* ```
*
* ##### Valid
*
* ```js
* if (x < 0) {
* x++;
* }
* else {
* x--;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (x < 0) {
* x++;
* } else {
* x--;
* }
* ```
*/
var assert = require('assert');
Function (anonymous_910)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_911)
✓ Was called
configure: function(keywords) {···
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
configure: function(keywords) {
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
Function (anonymous_912)
✓ Was called
getOptionName: function() {···
return 'requireKeywordsOnNewLine';
},
getOptionName: function() {
return 'requireKeywordsOnNewLine';
},
Function (anonymous_913)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token
});
});
}
check: function(file, errors) {
Function (anonymous_914)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token
});
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
errors.assert.differentLine({
token: token.getPreviousCodeToken(),
nextToken: token
});
});
}
};
require-line-break-after-variable-assignment.js
/**
* Requires placing line feed after assigning a variable.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireLineBreakAfterVariableAssignment": true
* ```
*
* ##### Valid
*
* ```js
* var abc = 8;
* var foo = 5;
*
* var a, b, c,
* foo = 7,
* bar = 8;
*
* var a,
* foo = 7,
* a, b, c,
* bar = 8;
* ```
*
* ##### Invalid
*
* ```js
* var abc = 8; var foo = 5;
*
* var a, b, c,
* foo = 7, bar = 8;
* ```
*/
var assert = require('assert');
Function (anonymous_915)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_916)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_917)
✓ Was called
getOptionName: function() {···
return 'requireLineBreakAfterVariableAssignment';
},
getOptionName: function() {
return 'requireLineBreakAfterVariableAssignment';
},
Function (anonymous_918)
✓ Was called
check: function(file, errors) {···
var lastDeclaration;
file.iterateNodesByType('VariableDeclaration', function(node) {
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}

for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];
if (thisDeclaration.parentElement.kind === 'var' ||
thisDeclaration.parentElement.kind === 'let' ||
thisDeclaration.parentElement.kind === 'const') {
if (lastDeclaration && lastDeclaration.init) {
errors.assert.differentLine({
token: lastDeclaration,
nextToken: thisDeclaration,
message: 'Variable assignments should be followed by new line'
});
}
lastDeclaration = thisDeclaration;
}
}
});
}
check: function(file, errors) {
var lastDeclaration;
Function (anonymous_919)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}

for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];
if (thisDeclaration.parentElement.kind === 'var' ||
thisDeclaration.parentElement.kind === 'let' ||
thisDeclaration.parentElement.kind === 'const') {
if (lastDeclaration && lastDeclaration.init) {
errors.assert.differentLine({
token: lastDeclaration,
nextToken: thisDeclaration,
message: 'Variable assignments should be followed by new line'
});
}
lastDeclaration = thisDeclaration;
}
}
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Branch IfStatement
✓ Positive was executed (if)
node.parentElement.type === 'ForOfStatement') {···
return;
}
✓ Negative was executed (else)
}···

for (var i = 0; i < node.declarations.length; i++) {
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'ForOfStatement') {
✓ Was returned
if (node.parentElement.type === 'ForStatement' ||···
node.parentElement.type === 'ForInStatement' ||
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'ForInStatement' ||
✓ Was returned
if (node.parentElement.type === 'ForStatement' ||
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}
for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];
Branch IfStatement
✓ Positive was executed (if)
thisDeclaration.parentElement.kind === 'const') {···
if (lastDeclaration && lastDeclaration.init) {
errors.assert.differentLine({
token: lastDeclaration,
nextToken: thisDeclaration,
message: 'Variable assignments should be followed by new line'
});
}
lastDeclaration = thisDeclaration;
}
✗ Negative was not executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
thisDeclaration.parentElement.kind === 'const') {
✓ Was returned
if (thisDeclaration.parentElement.kind === 'var' ||···
thisDeclaration.parentElement.kind === 'let' ||
Branch LogicalExpression
✓ Was returned
thisDeclaration.parentElement.kind === 'let' ||
✓ Was returned
if (thisDeclaration.parentElement.kind === 'var' ||
if (thisDeclaration.parentElement.kind === 'var' ||
thisDeclaration.parentElement.kind === 'let' ||
thisDeclaration.parentElement.kind === 'const') {
Branch IfStatement
✓ Positive was executed (if)
if (lastDeclaration && lastDeclaration.init) {···
errors.assert.differentLine({
token: lastDeclaration,
nextToken: thisDeclaration,
message: 'Variable assignments should be followed by new line'
});
}
✓ Negative was executed (else)
}···
lastDeclaration = thisDeclaration;
Branch LogicalExpression
✓ Was returned
if (lastDeclaration && lastDeclaration.init) {
✓ Was returned
if (lastDeclaration && lastDeclaration.init) {
if (lastDeclaration && lastDeclaration.init) {
errors.assert.differentLine({
token: lastDeclaration,
nextToken: thisDeclaration,
message: 'Variable assignments should be followed by new line'
});
}
lastDeclaration = thisDeclaration;
}
}
});
}
};
require-line-feed-at-file-end.js
/**
* Requires placing line feed at file end.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireLineFeedAtFileEnd": true
* ```
*/
var assert = require('assert');
Function (anonymous_920)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_921)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_922)
✓ Was called
getOptionName: function() {···
return 'requireLineFeedAtFileEnd';
},
getOptionName: function() {
return 'requireLineFeedAtFileEnd';
},
Function (anonymous_923)
✓ Was called
check: function(file, errors) {···
var lastToken = file.getLastToken({includeComments: true});
var prevToken = file.getPrevToken(lastToken, {includeComments: true});
errors.assert.differentLine({
token: prevToken,
nextToken: lastToken,
message: 'Missing line feed at file end'
});
}
check: function(file, errors) {
var lastToken = file.getLastToken({includeComments: true});
var prevToken = file.getPrevToken(lastToken, {includeComments: true});
errors.assert.differentLine({
token: prevToken,
nextToken: lastToken,
message: 'Missing line feed at file end'
});
}
};
require-matching-function-name.js
/**
* Requires function names to match member and property names.
*
* It doesn't affect anonymous functions nor functions assigned to members or
* properties named with a reserved word. Assigning to `module.exports` is also
* ignored, unless `includeModuleExports: true` is configured.
*
* Types: `Boolean` or `Object`
*
* Values: `true` or Object with `includeModuleExports: true`
*
* #### Example
*
* ```js
* "requireMatchingFunctionName": true
* ```
*
* ##### Valid
*
* ```js
* var test = {};
* test.foo = function foo() {};
* ```
*
* ```js
* var test = {};
* test['foo'] = function foo() {};
* ```
*
* ```js
* var test = {foo: function foo() {}};
* ```
*
* ```js
* module.exports = function foo() {};
* ```
*
* ```js
* module['exports'] = function foo() {};
* ```
*
* ##### Invalid
*
* ```js
* var test = {};
* test.foo = function bar() {};
* ```
*
* ```js
* var test = {};
* test['foo'] = function bar() {};
* ```
*
* ```js
* var test = {foo: function bar() {}};
* ```
*
* ```js
* var test = {module: {}};
* test.module.exports = function foo() {};
* ```
*
* #### Example
*
* ```js
* "requireMatchingFunctionName": { "includeModuleExports": true }
* ```
*
* ##### Invalid
*
* ```js
* module.exports = function foo() {};
* ```
*
* ```js
* module['exports'] = function foo() {};
* ```
*/
var assert = require('assert');
var reservedWords = require('reserved-words');
Function (anonymous_924)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_925)
✓ Was called
configure: function(requireMatchingFunctionName) {···
if (typeof requireMatchingFunctionName === 'object') {
assert(requireMatchingFunctionName.includeModuleExports === true,
'requireMatchingFunctionName option requires includeModuleExports property to be true for object');
this._includeModuleExports = requireMatchingFunctionName.includeModuleExports;
} else {
assert(
requireMatchingFunctionName === true,
'requireMatchingFunctionName option requires true value or should be removed'
);
}
},
configure: function(requireMatchingFunctionName) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof requireMatchingFunctionName === 'object') {···
assert(requireMatchingFunctionName.includeModuleExports === true,
'requireMatchingFunctionName option requires includeModuleExports property to be true for object');
this._includeModuleExports = requireMatchingFunctionName.includeModuleExports;
} else {
✓ Negative was executed (else)
} else {···
assert(
requireMatchingFunctionName === true,
'requireMatchingFunctionName option requires true value or should be removed'
);
}
if (typeof requireMatchingFunctionName === 'object') {
assert(requireMatchingFunctionName.includeModuleExports === true,
'requireMatchingFunctionName option requires includeModuleExports property to be true for object');
this._includeModuleExports = requireMatchingFunctionName.includeModuleExports;
} else {
assert(
requireMatchingFunctionName === true,
'requireMatchingFunctionName option requires true value or should be removed'
);
}
},
Function (anonymous_926)
✓ Was called
getOptionName: function() {···
return 'requireMatchingFunctionName';
},
getOptionName: function() {
return 'requireMatchingFunctionName';
},
Function (anonymous_927)
✓ Was called
check: function(file, errors) {···
var _includeModuleExports = this._includeModuleExports;
file.iterateNodesByType(['FunctionExpression'], function(node) {
switch (node.parentElement.type) {
// var foo = function bar() {}
// object.foo = function bar() {}
// object['foo'] = function bar() {}
case 'AssignmentExpression':
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
checkForMember(node.parentElement, skip, errors);
}
break;

// object = {foo: function bar() {}}
case 'ObjectProperty':
checkForProperty(node.parentElement, skip, errors);
break;
}
});

function skip(key, value) {
// We don't care about anonymous functions as
// those should be enforced by separate rule
if (!value.id) {
return true;
}

// Relax a bit when reserved word is detected
if (reservedWords.check(key, file.getDialect(), true)) {
return true;
}
}
}
check: function(file, errors) {
var _includeModuleExports = this._includeModuleExports;
Function (anonymous_928)
✓ Was called
file.iterateNodesByType(['FunctionExpression'], function(node) {···
switch (node.parentElement.type) {
// var foo = function bar() {}
// object.foo = function bar() {}
// object['foo'] = function bar() {}
case 'AssignmentExpression':
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
checkForMember(node.parentElement, skip, errors);
}
break;

// object = {foo: function bar() {}}
case 'ObjectProperty':
checkForProperty(node.parentElement, skip, errors);
break;
}
});
file.iterateNodesByType(['FunctionExpression'], function(node) {
Branch SwitchStatement
✓ Was evaluated
case 'AssignmentExpression':···
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
checkForMember(node.parentElement, skip, errors);
}
break;
✓ Was evaluated
case 'ObjectProperty':···
checkForProperty(node.parentElement, skip, errors);
break;
switch (node.parentElement.type) {
// var foo = function bar() {}
// object.foo = function bar() {}
// object['foo'] = function bar() {}
case 'AssignmentExpression':
Branch IfStatement
✓ Positive was executed (if)
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {···
checkForMember(node.parentElement, skip, errors);
}
✓ Negative was executed (else)
}···
break;
Branch LogicalExpression
✓ Was returned
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
✓ Was returned
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
if (_includeModuleExports || !_isModuleExports(node.parentElement.left)) {
checkForMember(node.parentElement, skip, errors);
}
break;
// object = {foo: function bar() {}}
case 'ObjectProperty':
checkForProperty(node.parentElement, skip, errors);
break;
}
});
Function skip
✓ Was called
function skip(key, value) {···
// We don't care about anonymous functions as
// those should be enforced by separate rule
if (!value.id) {
return true;
}

// Relax a bit when reserved word is detected
if (reservedWords.check(key, file.getDialect(), true)) {
return true;
}
}
function skip(key, value) {
// We don't care about anonymous functions as
// those should be enforced by separate rule
Branch IfStatement
✓ Positive was executed (if)
if (!value.id) {···
return true;
}
✓ Negative was executed (else)
}···

// Relax a bit when reserved word is detected
if (!value.id) {
return true;
}
// Relax a bit when reserved word is detected
Branch IfStatement
✓ Positive was executed (if)
if (reservedWords.check(key, file.getDialect(), true)) {···
return true;
}
✓ Negative was executed (else)
}···
}
if (reservedWords.check(key, file.getDialect(), true)) {
return true;
}
}
}
};
Function _isModuleExports
✓ Was called
function _isModuleExports(pattern) {···
if (pattern.type === 'MemberExpression') {
// must be module.sth
if (pattern.object.type === 'Identifier' &&
pattern.object.name === 'module') {

if (pattern.property.type === 'Identifier' &&
pattern.property.name === 'exports') {
// sth.exports
return true;
} else if (pattern.property.type === 'StringLiteral' &&
pattern.property.value === 'exports') {
// sth["exports"]
return true;
}
}
}
return false;
}
function _isModuleExports(pattern) {
Branch IfStatement
✓ Positive was executed (if)
if (pattern.type === 'MemberExpression') {···
// must be module.sth
if (pattern.object.type === 'Identifier' &&
pattern.object.name === 'module') {

if (pattern.property.type === 'Identifier' &&
pattern.property.name === 'exports') {
// sth.exports
return true;
} else if (pattern.property.type === 'StringLiteral' &&
pattern.property.value === 'exports') {
// sth["exports"]
return true;
}
}
}
✓ Negative was executed (else)
}···
return false;
if (pattern.type === 'MemberExpression') {
// must be module.sth
Branch IfStatement
✓ Positive was executed (if)
pattern.object.name === 'module') {···

if (pattern.property.type === 'Identifier' &&
pattern.property.name === 'exports') {
// sth.exports
return true;
} else if (pattern.property.type === 'StringLiteral' &&
pattern.property.value === 'exports') {
// sth["exports"]
return true;
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
pattern.object.name === 'module') {
✓ Was returned
if (pattern.object.type === 'Identifier' &&
if (pattern.object.type === 'Identifier' &&
pattern.object.name === 'module') {
Branch IfStatement
✓ Positive was executed (if)
pattern.property.name === 'exports') {···
// sth.exports
return true;
} else if (pattern.property.type === 'StringLiteral' &&
✓ Negative was executed (else)
} else if (pattern.property.type === 'StringLiteral' &&···
pattern.property.value === 'exports') {
// sth["exports"]
return true;
}
Branch LogicalExpression
✓ Was returned
pattern.property.name === 'exports') {
✓ Was returned
if (pattern.property.type === 'Identifier' &&
if (pattern.property.type === 'Identifier' &&
pattern.property.name === 'exports') {
// sth.exports
return true;
Branch IfStatement
✓ Positive was executed (if)
pattern.property.value === 'exports') {···
// sth["exports"]
return true;
}
✗ Negative was not executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
pattern.property.value === 'exports') {
✗ Was not returned
} else if (pattern.property.type === 'StringLiteral' &&
} else if (pattern.property.type === 'StringLiteral' &&
pattern.property.value === 'exports') {
// sth["exports"]
return true;
}
}
}
return false;
}
/**
* Fetching name from a Pattern
*
* @param {Pattern} pattern - E.g. left side of AssignmentExpression
* @returns {String|Boolean} - Resolved name or false (if there is an Expression)
*/
Function _resolvePatternName
✓ Was called
function _resolvePatternName(pattern) {···
switch (pattern.type) {
case 'Identifier':
// prop = ...;
return pattern.name;
case 'StringLiteral':
// obj['prop'] = ...;
return pattern.value;
case 'MemberExpression':
// obj.prop = ...;
return _resolvePatternName(pattern.property);
default:
// Something unhandy like obj['x' + 2] = ...;
return false;
}
}
function _resolvePatternName(pattern) {
Branch SwitchStatement
✓ Was evaluated
case 'Identifier':···
// prop = ...;
return pattern.name;
✓ Was evaluated
case 'StringLiteral':···
// obj['prop'] = ...;
return pattern.value;
✓ Was evaluated
case 'MemberExpression':···
// obj.prop = ...;
return _resolvePatternName(pattern.property);
✓ Was evaluated
default:···
// Something unhandy like obj['x' + 2] = ...;
return false;
switch (pattern.type) {
case 'Identifier':
// prop = ...;
return pattern.name;
case 'StringLiteral':
// obj['prop'] = ...;
return pattern.value;
case 'MemberExpression':
// obj.prop = ...;
return _resolvePatternName(pattern.property);
default:
// Something unhandy like obj['x' + 2] = ...;
return false;
}
}
Function checkForMember
✓ Was called
function checkForMember(assignment, skip, errors) {···
var _name = _resolvePatternName(assignment.left);
if (_name === false || skip(_name, assignment.right)) {
return;
}

if (_name !== assignment.right.id.name) {
errors.add(
'Function name does not match member name',
assignment
);
}
}
function checkForMember(assignment, skip, errors) {
var _name = _resolvePatternName(assignment.left);
Branch IfStatement
✓ Positive was executed (if)
if (_name === false || skip(_name, assignment.right)) {···
return;
}
✓ Negative was executed (else)
}···

if (_name !== assignment.right.id.name) {
Branch LogicalExpression
✓ Was returned
if (_name === false || skip(_name, assignment.right)) {
✓ Was returned
if (_name === false || skip(_name, assignment.right)) {
if (_name === false || skip(_name, assignment.right)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_name !== assignment.right.id.name) {···
errors.add(
'Function name does not match member name',
assignment
);
}
✓ Negative was executed (else)
}···
}
if (_name !== assignment.right.id.name) {
errors.add(
'Function name does not match member name',
assignment
);
}
}
Function checkForProperty
✓ Was called
function checkForProperty(property, skip, errors) {···
var _name = _resolvePatternName(property.key);
if (_name === false || skip(_name, property.value)) {
return;
}

if (_name !== property.value.id.name) {
errors.add(
'Function name does not match property name',
property
);
}
}
function checkForProperty(property, skip, errors) {
var _name = _resolvePatternName(property.key);
Branch IfStatement
✓ Positive was executed (if)
if (_name === false || skip(_name, property.value)) {···
return;
}
✓ Negative was executed (else)
}···

if (_name !== property.value.id.name) {
Branch LogicalExpression
✓ Was returned
if (_name === false || skip(_name, property.value)) {
✓ Was returned
if (_name === false || skip(_name, property.value)) {
if (_name === false || skip(_name, property.value)) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_name !== property.value.id.name) {···
errors.add(
'Function name does not match property name',
property
);
}
✓ Negative was executed (else)
}···
}
if (_name !== property.value.id.name) {
errors.add(
'Function name does not match property name',
property
);
}
}
require-multi-line-ternary.js
/**
* Requires the test, consequent and alternate to be on separate lines when using the ternary operator.
*
* Types: `Boolean`
*
* #### Example
*
* ```js
* "requireMultiLineTernary": true
* ```
*
* ##### Valid
*
* ```js
* var foo = (a === b)
* ? 1
* : 2;
* ```
*
* ##### Invalid
*
* ```js
* var foo = (a === b) ? 1 : 2;
* ```
*/
var assert = require('assert');
Function (anonymous_934)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_935)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_936)
✓ Was called
getOptionName: function() {···
return 'requireMultiLineTernary';
},
getOptionName: function() {
return 'requireMultiLineTernary';
},
Function (anonymous_937)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ConditionalExpression', function(node) {

errors.assert.differentLine({
token: node.test,
nextToken: node.consequent,
message: 'Missing new line after test'
});

errors.assert.differentLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Missing new line after consequent'
});

});
}
check: function(file, errors) {
Function (anonymous_938)
✓ Was called
file.iterateNodesByType('ConditionalExpression', function(node) {···

errors.assert.differentLine({
token: node.test,
nextToken: node.consequent,
message: 'Missing new line after test'
});

errors.assert.differentLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Missing new line after consequent'
});

});
file.iterateNodesByType('ConditionalExpression', function(node) {
errors.assert.differentLine({
token: node.test,
nextToken: node.consequent,
message: 'Missing new line after test'
});
errors.assert.differentLine({
token: node.consequent,
nextToken: node.alternate,
message: 'Missing new line after consequent'
});
});
}
};
require-multiple-var-decl.js
/**
* Requires multiple `var` declaration.
*
* Types: `Boolean` or `String` or `Object`
*
* Values: `true` or `"onevar"` or `allExcept: ['require']`
*
* If `requireMultipleVarDecl` defined as a `true` value, it will report only consecutive vars, if, on the other hand,
* value equals to `"onevar"` string, `requireMultipleVarDecl` will allow only one `var` per function scope.
*
* If the value is `allExcept: ['require']`, then require statements are allowed to have a var declaration per variable.
*
* JSHint: [`onevar`](http://jshint.com/docs/options/#onevar)
*
* #### Example
*
* ```js
* "requireMultipleVarDecl": true
* ```
*
* ##### Valid
*
* ```js
* var x = 1,
* y = 2;
* ```
*
* ##### Valid for `allExcept: ['require']`
*
* ```js
* var a = require("a");
* var b = require("b");
* var c = 1,
* d = 2;
* ```
*
* ##### Invalid
*
* ```js
* var x = 1;
* var y = 2;
* ```
*/
var assert = require('assert');
Function consecutive
✓ Was called
function consecutive(file, errors) {···
var isExceptRequire = this._isExceptRequire;

file.iterateNodesByType('VariableDeclaration', function(node) {
if (isExceptRequire && hasRequireStatements(node)) {
return;
}

var sibling = node.nextSibling;

if (!sibling) {
return;
}

while (sibling.nextSibling) {
sibling = sibling.nextSibling;

if (sibling.type !== node.type) {
break;
}

if (isExceptRequire && hasRequireStatements(sibling)) {
break;
}

if (sibling.kind === node.kind) {
errors.add(
node.kind[0].toUpperCase() + node.kind.slice(1) + ' declarations should be joined',
sibling
);
}
}
});
}
function consecutive(file, errors) {
var isExceptRequire = this._isExceptRequire;
Function (anonymous_940)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···
if (isExceptRequire && hasRequireStatements(node)) {
return;
}

var sibling = node.nextSibling;

if (!sibling) {
return;
}

while (sibling.nextSibling) {
sibling = sibling.nextSibling;

if (sibling.type !== node.type) {
break;
}

if (isExceptRequire && hasRequireStatements(sibling)) {
break;
}

if (sibling.kind === node.kind) {
errors.add(
node.kind[0].toUpperCase() + node.kind.slice(1) + ' declarations should be joined',
sibling
);
}
}
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (isExceptRequire && hasRequireStatements(node)) {···
return;
}
✓ Negative was executed (else)
}···

var sibling = node.nextSibling;
Branch LogicalExpression
✓ Was returned
if (isExceptRequire && hasRequireStatements(node)) {
✓ Was returned
if (isExceptRequire && hasRequireStatements(node)) {
if (isExceptRequire && hasRequireStatements(node)) {
return;
}
var sibling = node.nextSibling;
Branch IfStatement
✓ Positive was executed (if)
if (!sibling) {···
return;
}
✓ Negative was executed (else)
}···

while (sibling.nextSibling) {
if (!sibling) {
return;
}
while (sibling.nextSibling) {
sibling = sibling.nextSibling;
Branch IfStatement
✓ Positive was executed (if)
if (sibling.type !== node.type) {···
break;
}
✓ Negative was executed (else)
}···

if (isExceptRequire && hasRequireStatements(sibling)) {
if (sibling.type !== node.type) {
break;
}
Branch IfStatement
✓ Positive was executed (if)
if (isExceptRequire && hasRequireStatements(sibling)) {···
break;
}
✓ Negative was executed (else)
}···

if (sibling.kind === node.kind) {
Branch LogicalExpression
✓ Was returned
if (isExceptRequire && hasRequireStatements(sibling)) {
✓ Was returned
if (isExceptRequire && hasRequireStatements(sibling)) {
if (isExceptRequire && hasRequireStatements(sibling)) {
break;
}
Branch IfStatement
✓ Positive was executed (if)
if (sibling.kind === node.kind) {···
errors.add(
node.kind[0].toUpperCase() + node.kind.slice(1) + ' declarations should be joined',
sibling
);
}
✓ Negative was executed (else)
}···
}
if (sibling.kind === node.kind) {
errors.add(
node.kind[0].toUpperCase() + node.kind.slice(1) + ' declarations should be joined',
sibling
);
}
}
});
}
Function _onevar
✓ Was called
function _onevar(file, errors, node) {···
var firstVar = true;
var firstConst = true;
var firstParent = true;

file.iterate(function(node) {
var type = node.type;
var kind = node.kind;

// Don't go in nested scopes
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {
return false;
}

if (firstParent) {
firstParent = false;
}

if (type === 'VariableDeclaration') {
if (kind === 'var') {
if (!firstVar) {
errors.add('Var declarations should be joined', node);

} else {
firstVar = false;
}
}

if (kind === 'const') {
if (!firstConst) {
errors.add('Const declarations should be joined', node);

} else {
firstConst = false;
}
}
}
}, node);
}
function _onevar(file, errors, node) {
var firstVar = true;
var firstConst = true;
var firstParent = true;
Function (anonymous_942)
✓ Was called
file.iterate(function(node) {···
var type = node.type;
var kind = node.kind;

// Don't go in nested scopes
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {
return false;
}

if (firstParent) {
firstParent = false;
}

if (type === 'VariableDeclaration') {
if (kind === 'var') {
if (!firstVar) {
errors.add('Var declarations should be joined', node);

} else {
firstVar = false;
}
}

if (kind === 'const') {
if (!firstConst) {
errors.add('Const declarations should be joined', node);

} else {
firstConst = false;
}
}
}
}, node);
file.iterate(function(node) {
var type = node.type;
var kind = node.kind;
// Don't go in nested scopes
Branch IfStatement
✓ Positive was executed (if)
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {···
return false;
}
✓ Negative was executed (else)
}···

if (firstParent) {
Branch LogicalExpression
✓ Was returned
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {
✓ Was returned
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {
if (!firstParent && ['FunctionDeclaration', 'FunctionExpression'].indexOf(type) > -1) {
return false;
}
Branch IfStatement
✓ Positive was executed (if)
if (firstParent) {···
firstParent = false;
}
✓ Negative was executed (else)
}···

if (type === 'VariableDeclaration') {
if (firstParent) {
firstParent = false;
}
Branch IfStatement
✓ Positive was executed (if)
if (type === 'VariableDeclaration') {···
if (kind === 'var') {
if (!firstVar) {
errors.add('Var declarations should be joined', node);

} else {
firstVar = false;
}
}

if (kind === 'const') {
if (!firstConst) {
errors.add('Const declarations should be joined', node);

} else {
firstConst = false;
}
}
}
✓ Negative was executed (else)
}···
}, node);
if (type === 'VariableDeclaration') {
Branch IfStatement
✓ Positive was executed (if)
if (kind === 'var') {···
if (!firstVar) {
errors.add('Var declarations should be joined', node);

} else {
firstVar = false;
}
}
✓ Negative was executed (else)
}···

if (kind === 'const') {
if (kind === 'var') {
Branch IfStatement
✓ Positive was executed (if)
if (!firstVar) {···
errors.add('Var declarations should be joined', node);

} else {
✓ Negative was executed (else)
} else {···
firstVar = false;
}
if (!firstVar) {
errors.add('Var declarations should be joined', node);
} else {
firstVar = false;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (kind === 'const') {···
if (!firstConst) {
errors.add('Const declarations should be joined', node);

} else {
firstConst = false;
}
}
✓ Negative was executed (else)
}···
}
if (kind === 'const') {
Branch IfStatement
✓ Positive was executed (if)
if (!firstConst) {···
errors.add('Const declarations should be joined', node);

} else {
✓ Negative was executed (else)
} else {···
firstConst = false;
}
if (!firstConst) {
errors.add('Const declarations should be joined', node);
} else {
firstConst = false;
}
}
}
}, node);
}
Function onevar
✓ Was called
function onevar(file, errors) {···
_onevar(file, errors, file.getProgram());
file.iterateNodesByType(
['FunctionDeclaration', 'FunctionExpression'],
_onevar.bind(this, file, errors)
);
}
function onevar(file, errors) {
_onevar(file, errors, file.getProgram());
file.iterateNodesByType(
['FunctionDeclaration', 'FunctionExpression'],
_onevar.bind(this, file, errors)
);
}
Function hasRequireStatements
✓ Was called
function hasRequireStatements(node) {···
if (!Array.isArray(node.declarations)) {
return false;
}

return node.declarations.some(function(declaration) {
var init = declaration.init;

return init &&
init.callee &&
init.callee.name === 'require';
});
}
function hasRequireStatements(node) {
Branch IfStatement
✗ Positive was not executed (if)
if (!Array.isArray(node.declarations)) {···
return false;
}
✓ Negative was executed (else)
}···

return node.declarations.some(function(declaration) {
if (!Array.isArray(node.declarations)) {
return false;
}
Function (anonymous_945)
✓ Was called
return node.declarations.some(function(declaration) {···
var init = declaration.init;

return init &&
init.callee &&
init.callee.name === 'require';
});
return node.declarations.some(function(declaration) {
var init = declaration.init;
Branch LogicalExpression
✓ Was returned
init.callee.name === 'require';
✓ Was returned
return init &&···
init.callee &&
Branch LogicalExpression
✓ Was returned
init.callee &&
✓ Was returned
return init &&
return init &&
init.callee &&
init.callee.name === 'require';
});
}
Function (anonymous_946)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_947)
✓ Was called
configure: function(options) {···
var isExceptRequire = typeof options === 'object' &&
options.allExcept.length &&
options.allExcept.indexOf('require') !== -1;

assert(
options === true ||
options === 'onevar' ||
isExceptRequire,
this.getOptionName() + ' option requires a true value, `onevar` or {allExcept: [\'require\']}'
);

var checkers = {
'true': consecutive,
onevar: onevar
};

this._isExceptRequire = isExceptRequire;
this._check = isExceptRequire ? consecutive : checkers[options];
},
configure: function(options) {
Branch LogicalExpression
✓ Was returned
options.allExcept.indexOf('require') !== -1;
✓ Was returned
var isExceptRequire = typeof options === 'object' &&···
options.allExcept.length &&
Branch LogicalExpression
✓ Was returned
options.allExcept.length &&
✓ Was returned
var isExceptRequire = typeof options === 'object' &&
var isExceptRequire = typeof options === 'object' &&
options.allExcept.length &&
options.allExcept.indexOf('require') !== -1;
assert(
Branch LogicalExpression
✓ Was returned
isExceptRequire,
✓ Was returned
options === true ||···
options === 'onevar' ||
Branch LogicalExpression
✓ Was returned
options === 'onevar' ||
✓ Was returned
options === true ||
options === true ||
options === 'onevar' ||
isExceptRequire,
this.getOptionName() + ' option requires a true value, `onevar` or {allExcept: [\'require\']}'
);
var checkers = {
'true': consecutive,
onevar: onevar
};
this._isExceptRequire = isExceptRequire;
Branch ConditionalExpression
✓ Positive was returned (? ...)
this._check = isExceptRequire ? consecutive : checkers[options];
✓ Negative was returned (: ...)
this._check = isExceptRequire ? consecutive : checkers[options];
this._check = isExceptRequire ? consecutive : checkers[options];
},
Function (anonymous_948)
✓ Was called
getOptionName: function() {···
return 'requireMultipleVarDecl';
},
getOptionName: function() {
return 'requireMultipleVarDecl';
},
Function (anonymous_949)
✓ Was called
check: function() {···
return this._check.apply(this, arguments);
}
check: function() {
return this._check.apply(this, arguments);
}
};
require-named-unassigned-functions.js
/**
* Require unassigned functions to be named inline
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `Object`:
* - `allExcept`: array of quoted identifiers
*
* #### Example
*
* ```js
* "requireNamedUnassignedFunctions": { "allExcept": ["describe", "it"] }
* ```
*
* ##### Valid
*
* ```js
* [].forEach(function x() {});
* var y = function() {};
* function z() {}
* it(function () {});
* ```
*
* ##### Invalid
*
* ```js
* [].forEach(function () {});
* before(function () {});
* ```
*/
var assert = require('assert');
var pathval = require('pathval');
Function getNodeName
✓ Was called
function getNodeName(node) {···
if (node.type === 'Identifier') {
return node.name;
} else {
return node.value;
}
}
function getNodeName(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'Identifier') {···
return node.name;
} else {
✓ Negative was executed (else)
} else {···
return node.value;
}
if (node.type === 'Identifier') {
return node.name;
} else {
return node.value;
}
}
Function (anonymous_951)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_952)
✓ Was called
configure: function(options) {···
assert(
options === true ||
typeof options === 'object',
this.getOptionName() + ' option requires true value ' +
'or an object with String[] `allExcept` property'
);

// verify first item in `allExcept` property in object (if it's an object)
assert(
typeof options !== 'object' ||
Array.isArray(options.allExcept) &&
typeof options.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);

if (options.allExcept) {
this._allExceptItems = options.allExcept.map(function(item) {
var parts = pathval.parse(item).map(function extractPart(part) {
return part.i !== undefined ? part.i : part.p;
});
return JSON.stringify(parts);
});
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'object',
✓ Was returned
options === true ||
options === true ||
typeof options === 'object',
this.getOptionName() + ' option requires true value ' +
'or an object with String[] `allExcept` property'
);
// verify first item in `allExcept` property in object (if it's an object)
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(options.allExcept) &&···
typeof options.allExcept[0] === 'string',
✓ Was returned
typeof options !== 'object' ||
typeof options !== 'object' ||
Branch LogicalExpression
✓ Was returned
typeof options.allExcept[0] === 'string',
✓ Was returned
Array.isArray(options.allExcept) &&
Array.isArray(options.allExcept) &&
typeof options.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
Branch IfStatement
✓ Positive was executed (if)
if (options.allExcept) {···
this._allExceptItems = options.allExcept.map(function(item) {
var parts = pathval.parse(item).map(function extractPart(part) {
return part.i !== undefined ? part.i : part.p;
});
return JSON.stringify(parts);
});
}
✓ Negative was executed (else)
}···
},
if (options.allExcept) {
Function (anonymous_953)
✓ Was called
this._allExceptItems = options.allExcept.map(function(item) {···
var parts = pathval.parse(item).map(function extractPart(part) {
return part.i !== undefined ? part.i : part.p;
});
return JSON.stringify(parts);
});
this._allExceptItems = options.allExcept.map(function(item) {
Function extractPart
✓ Was called
var parts = pathval.parse(item).map(function extractPart(part) {···
return part.i !== undefined ? part.i : part.p;
});
var parts = pathval.parse(item).map(function extractPart(part) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
return part.i !== undefined ? part.i : part.p;
✓ Negative was returned (: ...)
return part.i !== undefined ? part.i : part.p;
return part.i !== undefined ? part.i : part.p;
});
return JSON.stringify(parts);
});
}
},
Function (anonymous_955)
✓ Was called
getOptionName: function() {···
return 'requireNamedUnassignedFunctions';
},
getOptionName: function() {
return 'requireNamedUnassignedFunctions';
},
Function (anonymous_956)
✓ Was called
check: function(file, errors) {···
var _this = this;
file.iterateNodesByType('FunctionExpression', function(node) {
var parentElement = node.parentElement;
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}

// If the function has been named, skip it
// e.g. `[].forEach(function hello() {`
if (node.id !== null) {
return;
}

// If we have exceptions and the function is being invoked, detect whether we excepted it
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
// Determine the path that resolves to our call expression
// We must cover both direct calls (e.g. `it(function() {`) and
// member expressions (e.g. `foo.bar(function() {`)
var memberNode = parentElement.callee;
var canBeRepresented = true;
var fullpathParts = [];
while (memberNode) {
if (memberNode.type.match(/Identifier|Literal/)) {
fullpathParts.unshift(getNodeName(memberNode));
} else if (memberNode.type === 'MemberExpression') {
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
memberNode = memberNode.object;
}

// If the path is not-dynamic (i.e. can be represented by static parts),
// then check it against our exceptions
if (canBeRepresented) {
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
}

// Complain that this function must be named
errors.add('Inline functions need to be named', node);
});
}
check: function(file, errors) {
var _this = this;
Function (anonymous_957)
✓ Was called
file.iterateNodesByType('FunctionExpression', function(node) {···
var parentElement = node.parentElement;
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}

// If the function has been named, skip it
// e.g. `[].forEach(function hello() {`
if (node.id !== null) {
return;
}

// If we have exceptions and the function is being invoked, detect whether we excepted it
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
// Determine the path that resolves to our call expression
// We must cover both direct calls (e.g. `it(function() {`) and
// member expressions (e.g. `foo.bar(function() {`)
var memberNode = parentElement.callee;
var canBeRepresented = true;
var fullpathParts = [];
while (memberNode) {
if (memberNode.type.match(/Identifier|Literal/)) {
fullpathParts.unshift(getNodeName(memberNode));
} else if (memberNode.type === 'MemberExpression') {
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
memberNode = memberNode.object;
}

// If the path is not-dynamic (i.e. can be represented by static parts),
// then check it against our exceptions
if (canBeRepresented) {
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
}

// Complain that this function must be named
errors.add('Inline functions need to be named', node);
});
file.iterateNodesByType('FunctionExpression', function(node) {
var parentElement = node.parentElement;
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {···
return;
}
✓ Negative was executed (else)
}···

// If the function has been named, skip it
if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}
// If the function has been named, skip it
// e.g. `[].forEach(function hello() {`
Branch IfStatement
✓ Positive was executed (if)
if (node.id !== null) {···
return;
}
✓ Negative was executed (else)
}···

// If we have exceptions and the function is being invoked, detect whether we excepted it
if (node.id !== null) {
return;
}
// If we have exceptions and the function is being invoked, detect whether we excepted it
Branch IfStatement
✓ Positive was executed (if)
if (_this._allExceptItems && parentElement.type === 'CallExpression') {···
// Determine the path that resolves to our call expression
// We must cover both direct calls (e.g. `it(function() {`) and
// member expressions (e.g. `foo.bar(function() {`)
var memberNode = parentElement.callee;
var canBeRepresented = true;
var fullpathParts = [];
while (memberNode) {
if (memberNode.type.match(/Identifier|Literal/)) {
fullpathParts.unshift(getNodeName(memberNode));
} else if (memberNode.type === 'MemberExpression') {
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
memberNode = memberNode.object;
}

// If the path is not-dynamic (i.e. can be represented by static parts),
// then check it against our exceptions
if (canBeRepresented) {
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
}
✓ Negative was executed (else)
}···

// Complain that this function must be named
Branch LogicalExpression
✓ Was returned
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
✓ Was returned
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
// Determine the path that resolves to our call expression
// We must cover both direct calls (e.g. `it(function() {`) and
// member expressions (e.g. `foo.bar(function() {`)
var memberNode = parentElement.callee;
var canBeRepresented = true;
var fullpathParts = [];
while (memberNode) {
Branch IfStatement
✓ Positive was executed (if)
if (memberNode.type.match(/Identifier|Literal/)) {···
fullpathParts.unshift(getNodeName(memberNode));
} else if (memberNode.type === 'MemberExpression') {
✓ Negative was executed (else)
} else if (memberNode.type === 'MemberExpression') {···
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
if (memberNode.type.match(/Identifier|Literal/)) {
fullpathParts.unshift(getNodeName(memberNode));
Branch IfStatement
✓ Positive was executed (if)
} else if (memberNode.type === 'MemberExpression') {···
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
✓ Negative was executed (else)
} else {···
canBeRepresented = false;
break;
}
} else if (memberNode.type === 'MemberExpression') {
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
memberNode = memberNode.object;
}
// If the path is not-dynamic (i.e. can be represented by static parts),
// then check it against our exceptions
Branch IfStatement
✓ Positive was executed (if)
if (canBeRepresented) {···
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
✓ Negative was executed (else)
}···
}
if (canBeRepresented) {
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
Branch IfStatement
✓ Positive was executed (if)
if (fullpath === _this._allExceptItems[i]) {···
return;
}
✓ Negative was executed (else)
}···
}
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
}
// Complain that this function must be named
errors.add('Inline functions need to be named', node);
});
}
};
require-newline-before-block-statements.js
/**
* Requires newline before opening curly brace of all block statements.
*
* Type: `Boolean` or `Array`
*
* Values:
*
* - `true` always requires newline before curly brace of block statements
* - `Array` specifies block-type keywords after which newlines are required before curly brace
* - Valid types include: `['if', 'else', 'try', 'catch', 'finally', 'do', 'while', 'for', 'function', 'switch']`
*
* #### Example
*
* ```js
* "requireNewlineBeforeBlockStatements": true
* ```
*
* ##### Valid
*
* ```js
* function good()
* {
* var obj =
* {
* val: true
* };
*
* return {
* data: obj
* };
* }
*
* if (cond)
* {
* foo();
* }
*
* for (var e in elements)
* {
* bar(e);
* }
*
* while (cond)
* {
* foo();
* }
* ```
*
* ##### Invalid
*
* ```js
* function bad(){
* var obj = {
* val: true
* };
*
* return {
* data: obj
* };
* }
*
* if (cond){
* foo();
* }
*
* for (var e in elements){
* bar(e);
* }
*
* while (cond){
* foo();
* }
* ```
*
* #### Example
*
* ```js
* "requireNewlineBeforeBlockStatements": ["if", "else", "for"]
* ```
*
* ##### Valid
*
* ```js
* if (i > 0)
* {
* positive = true;
* }
*
* if (i < 0)
* {
* negative = true;
* }
* else
* {
* negative = false;
* }
*
* for (var i = 0, len = myList.length; i < len; ++i)
* {
* newList.push(myList[i]);
* }
*
* // this is fine, since "function" wasn't configured
* function myFunc(x) {
* return x + 1;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (i < 0) {
* negative = true;
* }
*
* if (i < 0) {
* negative = true;
* } else {
* negative = false;
* }
*
* for (var i = 0, len = myList.length; i < len; ++i) {
* newList.push(myList[i]);
* }
* ```
*
* #### Example
*
* ```js
* "requireNewlineBeforeBlockStatements": ["function", "while"]
* ```
*
* ##### Valid
*
* ```js
* function myFunc(x)
* {
* return x + 1;
* }
*
* var z = function(x)
* {
* return x - 1;
* }
*
* // this is fine, since "for" wasn't configured
* for (var i = 0, len = myList.length; i < len; ++i) {
* newList.push(myList[i]);
* }
* ```
*
* ##### Invalid
*
* ```js
* function myFunc(x) {
* return x + 1;
* }
*
* var z = function(x) {
* return x - 1;
* }
* ```
*/
var assert = require('assert');
Function (anonymous_958)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_959)
✓ Was called
configure: function(settingValue) {···
assert(
Array.isArray(settingValue) && settingValue.length || settingValue === true,
'requireNewlineBeforeBlockStatements option requires non-empty array value or true value'
);

this._setting = settingValue;
},
configure: function(settingValue) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
Branch LogicalExpression
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
✓ Was returned
Array.isArray(settingValue) && settingValue.length || settingValue === true,
Array.isArray(settingValue) && settingValue.length || settingValue === true,
'requireNewlineBeforeBlockStatements option requires non-empty array value or true value'
);
this._setting = settingValue;
},
Function (anonymous_960)
✓ Was called
getOptionName: function() {···
return 'requireNewlineBeforeBlockStatements';
},
getOptionName: function() {
return 'requireNewlineBeforeBlockStatements';
},
Function (anonymous_961)
✓ Was called
check: function(file, errors) {···
var setting = this._setting;

function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}

file.iterateNodesByType('BlockStatement', function(node) {
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

assertDifferentLine(prevToken, openingBrace);
}
});
if (setting === true || setting.indexOf('switch') !== -1) {
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

assertDifferentLine(prevToken, openingBrace);
});
}
}
check: function(file, errors) {
var setting = this._setting;
Function assertDifferentLine
✓ Was called
function assertDifferentLine(token, nextToken) {···
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}
function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before curly brace for block statement is required'
});
}
Function (anonymous_963)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

assertDifferentLine(prevToken, openingBrace);
}
});
file.iterateNodesByType('BlockStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {···
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();

assertDifferentLine(prevToken, openingBrace);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
✓ Was returned
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
if (setting === true || setting.indexOf(getBlockType(node)) !== -1) {
var openingBrace = node.getFirstToken();
var prevToken = openingBrace.getPreviousCodeToken();
assertDifferentLine(prevToken, openingBrace);
}
});
Branch IfStatement
✓ Positive was executed (if)
if (setting === true || setting.indexOf('switch') !== -1) {···
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

assertDifferentLine(prevToken, openingBrace);
});
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (setting === true || setting.indexOf('switch') !== -1) {
✓ Was returned
if (setting === true || setting.indexOf('switch') !== -1) {
if (setting === true || setting.indexOf('switch') !== -1) {
Function (anonymous_964)
✓ Was called
file.iterateNodesByType(['SwitchStatement'], function(node) {···
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);

assertDifferentLine(prevToken, openingBrace);
});
file.iterateNodesByType(['SwitchStatement'], function(node) {
var openingBrace = file.findNextToken(file.getLastNodeToken(node.discriminant), 'Punctuator', '{');
var prevToken = file.getPrevToken(openingBrace);
assertDifferentLine(prevToken, openingBrace);
});
}
}
};
Function getBlockType
✓ Was called
function getBlockType(node) {···
var parentElement = node.parentElement;
switch (parentElement.type) {
case 'IfStatement':
return (parentElement.alternate === node) ? 'else' : 'if';
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
return 'function';
case 'ForStatement':
case 'ForInStatement':
case 'ForOfStatement':
return 'for';
case 'WhileStatement':
return 'while';
case 'DoWhileStatement':
return 'do';
case 'TryStatement':
return (parentElement.finalizer === node) ? 'finally' : 'try';
case 'CatchClause':
return 'catch';
}
}
function getBlockType(node) {
var parentElement = node.parentElement;
Branch SwitchStatement
✓ Was evaluated
case 'IfStatement':···
return (parentElement.alternate === node) ? 'else' : 'if';
✓ Was evaluated
case 'FunctionDeclaration':
✓ Was evaluated
case 'FunctionExpression':
✓ Was evaluated
case 'ArrowFunctionExpression':···
return 'function';
✓ Was evaluated
case 'ForStatement':
✓ Was evaluated
case 'ForInStatement':
✓ Was evaluated
case 'ForOfStatement':···
return 'for';
✓ Was evaluated
case 'WhileStatement':···
return 'while';
✓ Was evaluated
case 'DoWhileStatement':···
return 'do';
✓ Was evaluated
case 'TryStatement':···
return (parentElement.finalizer === node) ? 'finally' : 'try';
✓ Was evaluated
case 'CatchClause':···
return 'catch';
switch (parentElement.type) {
case 'IfStatement':
Branch ConditionalExpression
✓ Positive was returned (? ...)
return (parentElement.alternate === node) ? 'else' : 'if';
✓ Negative was returned (: ...)
return (parentElement.alternate === node) ? 'else' : 'if';
return (parentElement.alternate === node) ? 'else' : 'if';
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
return 'function';
case 'ForStatement':
case 'ForInStatement':
case 'ForOfStatement':
return 'for';
case 'WhileStatement':
return 'while';
case 'DoWhileStatement':
return 'do';
case 'TryStatement':
Branch ConditionalExpression
✓ Positive was returned (? ...)
return (parentElement.finalizer === node) ? 'finally' : 'try';
✓ Negative was returned (: ...)
return (parentElement.finalizer === node) ? 'finally' : 'try';
return (parentElement.finalizer === node) ? 'finally' : 'try';
case 'CatchClause':
return 'catch';
}
}
require-newline-before-single-statements-in-if.js
/**
* Requires newline before single if statements
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireNewlineBeforeSingleStatementsInIf": true
* ```
*
* ##### Valid
*
* ```js
* if (x)
* doX();
*
* if (x)
* doX();
* else
* doY();
*
* if (x)
* doX();
* else if (v)
* doV();
* else
* doY();
* ```
*
* ##### Invalid
*
* ```js
* if (x) doX();
*
* if (x) doX();
* else doY();
*
* if (x) doX();
* else if (v) doV();
* else doY();
* ```
*/
var assert = require('assert');
Function (anonymous_966)
✓ Was called
module.exports = function() {};
module.exports = function() {};
Function getFirstStatement
✓ Was called
function getFirstStatement(node) {···
if (node && node.type === 'BlockStatement') {
return node.body[0];
}
return node;
}
function getFirstStatement(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node && node.type === 'BlockStatement') {···
return node.body[0];
}
✓ Negative was executed (else)
}···
return node;
Branch LogicalExpression
✓ Was returned
if (node && node.type === 'BlockStatement') {
✓ Was returned
if (node && node.type === 'BlockStatement') {
if (node && node.type === 'BlockStatement') {
return node.body[0];
}
return node;
}
module.exports.prototype = {
Function (anonymous_968)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_969)
✓ Was called
getOptionName: function() {···
return 'requireNewlineBeforeSingleStatementsInIf';
},
getOptionName: function() {
return 'requireNewlineBeforeSingleStatementsInIf';
},
Function (anonymous_970)
✓ Was called
check: function(file, errors) {···
function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before single statement in if is required'
});
}

// Recursively locate a token based on it's type.
function getToken(entity, tokenType, tokenProperty) {
if (entity.type === tokenType || !entity[tokenProperty]) {
return entity;
} else {
return getToken(entity[tokenProperty], tokenType, tokenProperty);
}
}

file.iterateNodesByType('IfStatement', function(node) {
var consequentNode = getFirstStatement(node.consequent);
var alternateNode = getFirstStatement(node.alternate);

if (consequentNode) {
assertDifferentLine(
getToken(consequentNode, 'Keyword', 'previousSibling'),
consequentNode
);
}

if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
assertDifferentLine(
getToken(alternateNode, 'Keyword', 'previousSibling'),
alternateNode
);
}
});
}
check: function(file, errors) {
Function assertDifferentLine
✓ Was called
function assertDifferentLine(token, nextToken) {···
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before single statement in if is required'
});
}
function assertDifferentLine(token, nextToken) {
errors.assert.differentLine({
token: token,
nextToken: nextToken,
message: 'Newline before single statement in if is required'
});
}
// Recursively locate a token based on it's type.
Function getToken
✓ Was called
function getToken(entity, tokenType, tokenProperty) {···
if (entity.type === tokenType || !entity[tokenProperty]) {
return entity;
} else {
return getToken(entity[tokenProperty], tokenType, tokenProperty);
}
}
function getToken(entity, tokenType, tokenProperty) {
Branch IfStatement
✓ Positive was executed (if)
if (entity.type === tokenType || !entity[tokenProperty]) {···
return entity;
} else {
✓ Negative was executed (else)
} else {···
return getToken(entity[tokenProperty], tokenType, tokenProperty);
}
Branch LogicalExpression
✓ Was returned
if (entity.type === tokenType || !entity[tokenProperty]) {
✓ Was returned
if (entity.type === tokenType || !entity[tokenProperty]) {
if (entity.type === tokenType || !entity[tokenProperty]) {
return entity;
} else {
return getToken(entity[tokenProperty], tokenType, tokenProperty);
}
}
Function (anonymous_973)
✓ Was called
file.iterateNodesByType('IfStatement', function(node) {···
var consequentNode = getFirstStatement(node.consequent);
var alternateNode = getFirstStatement(node.alternate);

if (consequentNode) {
assertDifferentLine(
getToken(consequentNode, 'Keyword', 'previousSibling'),
consequentNode
);
}

if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
assertDifferentLine(
getToken(alternateNode, 'Keyword', 'previousSibling'),
alternateNode
);
}
});
file.iterateNodesByType('IfStatement', function(node) {
var consequentNode = getFirstStatement(node.consequent);
var alternateNode = getFirstStatement(node.alternate);
Branch IfStatement
✓ Positive was executed (if)
if (consequentNode) {···
assertDifferentLine(
getToken(consequentNode, 'Keyword', 'previousSibling'),
consequentNode
);
}
✗ Negative was not executed (else)
}···

if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
if (consequentNode) {
assertDifferentLine(
getToken(consequentNode, 'Keyword', 'previousSibling'),
consequentNode
);
}
Branch IfStatement
✓ Positive was executed (if)
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {···
assertDifferentLine(
getToken(alternateNode, 'Keyword', 'previousSibling'),
alternateNode
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
✓ Was returned
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
Branch LogicalExpression
✓ Was returned
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
✓ Was returned
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
if (alternateNode && alternateNode.type !== 'IfStatement' && alternateNode.type !== 'BlockStatement') {
assertDifferentLine(
getToken(alternateNode, 'Keyword', 'previousSibling'),
alternateNode
);
}
});
}
};
require-numeric-literals.js
/**
* Requires use of binary, hexadecimal, and octal literals instead of parseInt.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireNumericLiterals": true
* ```
*
* ##### Valid
*
* ```js
* 0b111110111 === 503;
* 0o767 === 503;
* 0x1F7 === 503;
* ```
*
* ##### Invalid
*
* ```js
* parseInt("111110111", 2) === 503;
* parseInt("767", 8) === 503;
* parseInt("1F7", 16) === 255;
* ```
*/
var assert = require('assert');
Function (anonymous_974)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_975)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);

this._radixMap = {
2: 'binary',
8: 'octal',
16: 'hexadecimal'
};
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
this._radixMap = {
2: 'binary',
8: 'octal',
16: 'hexadecimal'
};
},
Function (anonymous_976)
✓ Was called
getOptionName: function() {···
return 'requireNumericLiterals';
},
getOptionName: function() {
return 'requireNumericLiterals';
},
Function (anonymous_977)
✓ Was called
check: function(file, errors) {···
var radixMap = this._radixMap;
file.iterateNodesByType(['CallExpression'], function(node) {
// don't check for parseInt(1)
if (node.arguments.length !== 2) {
return;
}

// only error if the radix is 2, 8, or 16
var radixName = radixMap[node.arguments[1].value];

if (node.callee.type === 'Identifier' &&
node.callee.name === 'parseInt' &&
radixName &&
node.arguments[0].type.indexOf('Literal') > -1
) {
errors.add('Use ' + radixName + ' literals instead of parseInt', node);
}
});
}
check: function(file, errors) {
var radixMap = this._radixMap;
Function (anonymous_978)
✓ Was called
file.iterateNodesByType(['CallExpression'], function(node) {···
// don't check for parseInt(1)
if (node.arguments.length !== 2) {
return;
}

// only error if the radix is 2, 8, or 16
var radixName = radixMap[node.arguments[1].value];

if (node.callee.type === 'Identifier' &&
node.callee.name === 'parseInt' &&
radixName &&
node.arguments[0].type.indexOf('Literal') > -1
) {
errors.add('Use ' + radixName + ' literals instead of parseInt', node);
}
});
file.iterateNodesByType(['CallExpression'], function(node) {
// don't check for parseInt(1)
Branch IfStatement
✓ Positive was executed (if)
if (node.arguments.length !== 2) {···
return;
}
✓ Negative was executed (else)
}···

// only error if the radix is 2, 8, or 16
if (node.arguments.length !== 2) {
return;
}
// only error if the radix is 2, 8, or 16
var radixName = radixMap[node.arguments[1].value];
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add('Use ' + radixName + ' literals instead of parseInt', node);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
node.arguments[0].type.indexOf('Literal') > -1
✓ Was returned
if (node.callee.type === 'Identifier' &&···
node.callee.name === 'parseInt' &&
radixName &&
Branch LogicalExpression
✓ Was returned
radixName &&
✓ Was returned
if (node.callee.type === 'Identifier' &&···
node.callee.name === 'parseInt' &&
Branch LogicalExpression
✓ Was returned
node.callee.name === 'parseInt' &&
✓ Was returned
if (node.callee.type === 'Identifier' &&
if (node.callee.type === 'Identifier' &&
node.callee.name === 'parseInt' &&
radixName &&
node.arguments[0].type.indexOf('Literal') > -1
) {
errors.add('Use ' + radixName + ' literals instead of parseInt', node);
}
});
}
};
require-object-destructuring.js
/**
* Requires variable declarations from objects via destructuring
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireObjectDestructuring": true
* ```
*
* ##### Valid
*
* ```js
* var { foo } = SomeThing;
* var { bar } = SomeThing.foo;
* var { val } = SomeThing['some.key'];
* ```
*
* ##### Invalid
*
* ```js
* var foo = SomeThing.foo;
* var bar = SomeThing.foo.bar;
* var val = SomeThing['some.key'].val;
* ```
*/
var assert = require('assert');
Function (anonymous_979)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_980)
✓ Was called
configure: function(option) {···
var isTrue = option === true;

assert(
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
this.getOptionName() + ' requires the value `true` ' +
'or an object with an `allExcept` array property'
);

this._propertyExceptions = !isTrue && option.allExcept || [];
},
configure: function(option) {
var isTrue = option === true;
assert(
Branch LogicalExpression
✗ Was not returned
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
✓ Was returned
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
Branch LogicalExpression
✗ Was not returned
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
✗ Was not returned
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
this.getOptionName() + ' requires the value `true` ' +
'or an object with an `allExcept` array property'
);
Branch LogicalExpression
✓ Was returned
this._propertyExceptions = !isTrue && option.allExcept || [];
✗ Was not returned
this._propertyExceptions = !isTrue && option.allExcept || [];
Branch LogicalExpression
✗ Was not returned
this._propertyExceptions = !isTrue && option.allExcept || [];
✓ Was returned
this._propertyExceptions = !isTrue && option.allExcept || [];
this._propertyExceptions = !isTrue && option.allExcept || [];
},
Function (anonymous_981)
✓ Was called
getOptionName: function() {···
return 'requireObjectDestructuring';
},
getOptionName: function() {
return 'requireObjectDestructuring';
},
Function (anonymous_982)
✓ Was called
check: function(file, errors) {···
var propertyExceptions = this._propertyExceptions;

file.iterateNodesByType('VariableDeclaration', function(node) {

node.declarations.forEach(function(declaration) {
var declarationId = declaration.id || {};
var declarationInit = declaration.init || {};

if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
return;
}

var propertyName = declarationInit.property && declarationInit.property.name;

if (declarationId.name === propertyName &&
propertyExceptions.indexOf(propertyName) < 0) {

errors.add('Property assignments should use destructuring', node);
}
});
});
}
check: function(file, errors) {
var propertyExceptions = this._propertyExceptions;
Function (anonymous_983)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···

node.declarations.forEach(function(declaration) {
var declarationId = declaration.id || {};
var declarationInit = declaration.init || {};

if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
return;
}

var propertyName = declarationInit.property && declarationInit.property.name;

if (declarationId.name === propertyName &&
propertyExceptions.indexOf(propertyName) < 0) {

errors.add('Property assignments should use destructuring', node);
}
});
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Function (anonymous_984)
✓ Was called
node.declarations.forEach(function(declaration) {···
var declarationId = declaration.id || {};
var declarationInit = declaration.init || {};

if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
return;
}

var propertyName = declarationInit.property && declarationInit.property.name;

if (declarationId.name === propertyName &&
propertyExceptions.indexOf(propertyName) < 0) {

errors.add('Property assignments should use destructuring', node);
}
});
node.declarations.forEach(function(declaration) {
Branch LogicalExpression
✗ Was not returned
var declarationId = declaration.id || {};
✓ Was returned
var declarationId = declaration.id || {};
var declarationId = declaration.id || {};
Branch LogicalExpression
✗ Was not returned
var declarationInit = declaration.init || {};
✓ Was returned
var declarationInit = declaration.init || {};
var declarationInit = declaration.init || {};
Branch IfStatement
✓ Positive was executed (if)
if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {···
return;
}
✓ Negative was executed (else)
}···

var propertyName = declarationInit.property && declarationInit.property.name;
Branch LogicalExpression
✓ Was returned
if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
✓ Was returned
if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
return;
}
Branch LogicalExpression
✓ Was returned
var propertyName = declarationInit.property && declarationInit.property.name;
✗ Was not returned
var propertyName = declarationInit.property && declarationInit.property.name;
var propertyName = declarationInit.property && declarationInit.property.name;
Branch IfStatement
✓ Positive was executed (if)
propertyExceptions.indexOf(propertyName) < 0) {···

errors.add('Property assignments should use destructuring', node);
}
✗ Negative was not executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
propertyExceptions.indexOf(propertyName) < 0) {
✗ Was not returned
if (declarationId.name === propertyName &&
if (declarationId.name === propertyName &&
propertyExceptions.indexOf(propertyName) < 0) {
errors.add('Property assignments should use destructuring', node);
}
});
});
}
};
require-object-keys-on-new-line.js
/**
* Requires placing object keys on new line
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'sameLine'` ignores the rule if all the keys and values are on the same line
*
* #### Example
*
* ```js
* "requireObjectKeysOnNewLine": true
* "requireObjectKeysOnNewLine": {
* "allExcept": ["sameLine"]
* }
* ```
*
* ##### Valid
*
* ```js
* var a = {
* b: 'b',
* c: 'c'
* };
* ```
*
* ##### Invalid
*
* ```js
* var a = {
* b: 'b', c: 'c'
* };
* ```
*
* ##### Valid for `{ "allExcept": ["sameLine"] }`
*
* ```js
* var a = {
* b: 'b', c: 'c'
* };
* ```
*
* ##### Invalid for `{ "allExcept": ["sameLine"] }`
*
* ```js
* var a = {
* b: 'b', c: 'c',
* d: 'd'
* };
* ```
*/
var assert = require('assert');
Function (anonymous_985)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_986)
✓ Was called
configure: function(options) {···
assert(
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);

this._isSameLine = false;
if (Array.isArray(options.allExcept)) {
this._isSameLine = options.allExcept[0] === 'sameLine';
}
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || Array.isArray(options.allExcept),
✓ Was returned
options === true || Array.isArray(options.allExcept),
options === true || Array.isArray(options.allExcept),
this.getOptionName() + ' option requires a true value or an object of exceptions'
);
this._isSameLine = false;
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._isSameLine = options.allExcept[0] === 'sameLine';
}
✓ Negative was executed (else)
}···
},
if (Array.isArray(options.allExcept)) {
this._isSameLine = options.allExcept[0] === 'sameLine';
}
},
Function (anonymous_987)
✓ Was called
getOptionName: function() {···
return 'requireObjectKeysOnNewLine';
},
getOptionName: function() {
return 'requireObjectKeysOnNewLine';
},
Function (anonymous_988)
✓ Was called
check: function(file, errors) {···
var message = 'Object keys must go on a new line';
var isSameLine = this._isSameLine;

if (isSameLine) {
message = 'Object keys must go on a new line if they aren\'t all on the same line';
}

file.iterateNodesByType('ObjectExpression', function(node) {
var firstKeyToken;
var lastValueToken;
var lastProp;

if (isSameLine) {
if (node.properties.length > 1) {
firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
lastProp = node.properties[node.properties.length - 1];
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);

if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
// It's ok, all keys and values are on the same line.
return;
}
}
}

for (var i = 1; i < node.properties.length; i++) {
var prop = node.properties[i - 1];
lastValueToken = file.getLastNodeToken(prop.value || prop.body);
var comma = file.findNextToken(lastValueToken, 'Punctuator', ',');

firstKeyToken = file.getFirstNodeToken(node.properties[i].key);

errors.assert.differentLine({
token: comma,
nextToken: firstKeyToken,
message: message
});
}
});
}
check: function(file, errors) {
var message = 'Object keys must go on a new line';
var isSameLine = this._isSameLine;
Branch IfStatement
✓ Positive was executed (if)
if (isSameLine) {···
message = 'Object keys must go on a new line if they aren\'t all on the same line';
}
✓ Negative was executed (else)
}···

file.iterateNodesByType('ObjectExpression', function(node) {
if (isSameLine) {
message = 'Object keys must go on a new line if they aren\'t all on the same line';
}
Function (anonymous_989)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var firstKeyToken;
var lastValueToken;
var lastProp;

if (isSameLine) {
if (node.properties.length > 1) {
firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
lastProp = node.properties[node.properties.length - 1];
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);

if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
// It's ok, all keys and values are on the same line.
return;
}
}
}

for (var i = 1; i < node.properties.length; i++) {
var prop = node.properties[i - 1];
lastValueToken = file.getLastNodeToken(prop.value || prop.body);
var comma = file.findNextToken(lastValueToken, 'Punctuator', ',');

firstKeyToken = file.getFirstNodeToken(node.properties[i].key);

errors.assert.differentLine({
token: comma,
nextToken: firstKeyToken,
message: message
});
}
});
file.iterateNodesByType('ObjectExpression', function(node) {
var firstKeyToken;
var lastValueToken;
var lastProp;
Branch IfStatement
✓ Positive was executed (if)
if (isSameLine) {···
if (node.properties.length > 1) {
firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
lastProp = node.properties[node.properties.length - 1];
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);

if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
// It's ok, all keys and values are on the same line.
return;
}
}
}
✓ Negative was executed (else)
}···

for (var i = 1; i < node.properties.length; i++) {
if (isSameLine) {
Branch IfStatement
✓ Positive was executed (if)
if (node.properties.length > 1) {···
firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
lastProp = node.properties[node.properties.length - 1];
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);

if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
// It's ok, all keys and values are on the same line.
return;
}
}
✓ Negative was executed (else)
}···
}
if (node.properties.length > 1) {
firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
lastProp = node.properties[node.properties.length - 1];
Branch LogicalExpression
✓ Was returned
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);
✓ Was returned
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);
lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);
Branch IfStatement
✓ Positive was executed (if)
if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {···
// It's ok, all keys and values are on the same line.
return;
}
✓ Negative was executed (else)
}···
}
if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
// It's ok, all keys and values are on the same line.
return;
}
}
}
for (var i = 1; i < node.properties.length; i++) {
var prop = node.properties[i - 1];
Branch LogicalExpression
✓ Was returned
lastValueToken = file.getLastNodeToken(prop.value || prop.body);
✓ Was returned
lastValueToken = file.getLastNodeToken(prop.value || prop.body);
lastValueToken = file.getLastNodeToken(prop.value || prop.body);
var comma = file.findNextToken(lastValueToken, 'Punctuator', ',');
firstKeyToken = file.getFirstNodeToken(node.properties[i].key);
errors.assert.differentLine({
token: comma,
nextToken: firstKeyToken,
message: message
});
}
});
}
};
require-operator-before-line-break.js
/**
* Requires operators to appear before line breaks and not after.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to require all possible binary operators to appear before line breaks
*
* JSHint: [`laxbreak`](http://www.jshint.com/docs/options/#laxbreak)
*
* #### Example
*
* ```js
* "requireOperatorBeforeLineBreak": [
* "?",
* "=",
* "+",
* "-",
* "/",
* "*",
* "==",
* "===",
* "!=",
* "!==",
* ">",
* ">=",
* "<",
* "<="
* ]
* ```
*
* ##### Valid
*
* ```js
* x = y ? 1 : 2;
* x = y ?
* 1 : 2;
* ```
*
* ##### Invalid
*
* ```js
* x = y
* ? 1 : 2;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').binaryOperators.slice();
defaultOperators.push('?');
Function (anonymous_990)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_991)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array value or true value'
);

if (isTrue) {
operators = defaultOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array value or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = defaultOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_992)
✓ Was called
getOptionName: function() {···
return 'requireOperatorBeforeLineBreak';
},
getOptionName: function() {
return 'requireOperatorBeforeLineBreak';
},
Function (anonymous_993)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;
var throughTokens = ['?', ','];

function errorIfApplicable(operatorToken) {
errors.assert.sameLine({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + operatorToken.value + ' should not be on a new line',
stickToPreviousToken: true
});
}

throughTokens = throughTokens.filter(function(operator) {
return operators[operator];
});

if (throughTokens.length) {
file.iterateTokensByType('Punctuator', function(token) {
var operator = token.value;

if (throughTokens.every(function() {
return throughTokens.indexOf(operator) >= 0;
})) {
errorIfApplicable(token);
}
});
}

file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'LogicalExpression'],
function(node) {
var operator = node.operator;

if (!operators[operator]) {
return;
}

var nextToken = file.getFirstNodeToken(node.argument || node.right);
var token = file.findPrevOperatorToken(nextToken, operator);

errorIfApplicable(token);
}
);
}
check: function(file, errors) {
var operators = this._operatorIndex;
var throughTokens = ['?', ','];
Function errorIfApplicable
✓ Was called
function errorIfApplicable(operatorToken) {···
errors.assert.sameLine({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + operatorToken.value + ' should not be on a new line',
stickToPreviousToken: true
});
}
function errorIfApplicable(operatorToken) {
errors.assert.sameLine({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + operatorToken.value + ' should not be on a new line',
stickToPreviousToken: true
});
}
Function (anonymous_995)
✓ Was called
throughTokens = throughTokens.filter(function(operator) {···
return operators[operator];
});
throughTokens = throughTokens.filter(function(operator) {
return operators[operator];
});
Branch IfStatement
✓ Positive was executed (if)
if (throughTokens.length) {···
file.iterateTokensByType('Punctuator', function(token) {
var operator = token.value;

if (throughTokens.every(function() {
return throughTokens.indexOf(operator) >= 0;
})) {
errorIfApplicable(token);
}
});
}
✓ Negative was executed (else)
}···

file.iterateNodesByType(
if (throughTokens.length) {
Function (anonymous_996)
✓ Was called
file.iterateTokensByType('Punctuator', function(token) {···
var operator = token.value;

if (throughTokens.every(function() {
return throughTokens.indexOf(operator) >= 0;
})) {
errorIfApplicable(token);
}
});
file.iterateTokensByType('Punctuator', function(token) {
var operator = token.value;
Function (anonymous_997)
✓ Was called
if (throughTokens.every(function() {···
return throughTokens.indexOf(operator) >= 0;
})) {
Branch IfStatement
✓ Positive was executed (if)
})) {···
errorIfApplicable(token);
}
✓ Negative was executed (else)
}···
});
if (throughTokens.every(function() {
return throughTokens.indexOf(operator) >= 0;
})) {
errorIfApplicable(token);
}
});
}
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'LogicalExpression'],
Function (anonymous_998)
✓ Was called
function(node) {···
var operator = node.operator;

if (!operators[operator]) {
return;
}

var nextToken = file.getFirstNodeToken(node.argument || node.right);
var token = file.findPrevOperatorToken(nextToken, operator);

errorIfApplicable(token);
}
function(node) {
var operator = node.operator;
Branch IfStatement
✓ Positive was executed (if)
if (!operators[operator]) {···
return;
}
✓ Negative was executed (else)
}···

var nextToken = file.getFirstNodeToken(node.argument || node.right);
if (!operators[operator]) {
return;
}
Branch LogicalExpression
✓ Was returned
var nextToken = file.getFirstNodeToken(node.argument || node.right);
✗ Was not returned
var nextToken = file.getFirstNodeToken(node.argument || node.right);
var nextToken = file.getFirstNodeToken(node.argument || node.right);
var token = file.findPrevOperatorToken(nextToken, operator);
errorIfApplicable(token);
}
);
}
};
require-padding-newline-after-variable-declaration.js
/**
* Requires an extra blank newline after var declarations, as long
* as it is not the last expression in the current block.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requirePaddingNewLineAfterVariableDeclaration": true
* ```
*
* ##### Valid
*
* ```js
* var x = {
* a: 1
* };
*
* foo({
* a: {
* b: 1
* }
* });
* ```
*
* ##### Invalid
*
* ```js
* var x = { a: 1 };
* foo({a:{b:1}});
* ```
*/
var assert = require('assert');
Function (anonymous_999)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1000)
✓ Was called
configure: function(requirePaddingNewLineAfterVariableDeclaration) {···
assert(
requirePaddingNewLineAfterVariableDeclaration === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(requirePaddingNewLineAfterVariableDeclaration) {
assert(
requirePaddingNewLineAfterVariableDeclaration === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1001)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLineAfterVariableDeclaration';
},
getOptionName: function() {
return 'requirePaddingNewLineAfterVariableDeclaration';
},
Function (anonymous_1002)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('VariableDeclaration', function(node) {
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}

var endOfDeclaration = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfDeclaration);

// check export declaration
if (nextToken.value === 'export') {
nextToken = file.getNextToken(nextToken);
}

if (nextToken.value in {'var': true, 'let': true, 'const': true}) {
return;
}

if (nextToken.value === '}') {
return;
}

if (nextToken.type === 'EOF') {
return;
}

errors.assert.linesBetween({
atLeast: 2,
token: endOfDeclaration,
nextToken: nextToken
});
});
}
check: function(file, errors) {
Function (anonymous_1003)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}

var endOfDeclaration = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfDeclaration);

// check export declaration
if (nextToken.value === 'export') {
nextToken = file.getNextToken(nextToken);
}

if (nextToken.value in {'var': true, 'let': true, 'const': true}) {
return;
}

if (nextToken.value === '}') {
return;
}

if (nextToken.type === 'EOF') {
return;
}

errors.assert.linesBetween({
atLeast: 2,
token: endOfDeclaration,
nextToken: nextToken
});
});
file.iterateNodesByType('VariableDeclaration', function(node) {
Branch IfStatement
✓ Positive was executed (if)
node.parentElement.type === 'ForOfStatement') {···
return;
}
✓ Negative was executed (else)
}···

var endOfDeclaration = file.getLastNodeToken(node);
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'ForOfStatement') {
✓ Was returned
if (node.parentElement.type === 'ForStatement' ||···
node.parentElement.type === 'ForInStatement' ||
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'ForInStatement' ||
✓ Was returned
if (node.parentElement.type === 'ForStatement' ||
if (node.parentElement.type === 'ForStatement' ||
node.parentElement.type === 'ForInStatement' ||
node.parentElement.type === 'ForOfStatement') {
return;
}
var endOfDeclaration = file.getLastNodeToken(node);
var nextToken = file.getNextToken(endOfDeclaration);
// check export declaration
Branch IfStatement
✗ Positive was not executed (if)
if (nextToken.value === 'export') {···
nextToken = file.getNextToken(nextToken);
}
✓ Negative was executed (else)
}···

if (nextToken.value in {'var': true, 'let': true, 'const': true}) {
if (nextToken.value === 'export') {
nextToken = file.getNextToken(nextToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value in {'var': true, 'let': true, 'const': true}) {···
return;
}
✓ Negative was executed (else)
}···

if (nextToken.value === '}') {
if (nextToken.value in {'var': true, 'let': true, 'const': true}) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value === '}') {···
return;
}
✓ Negative was executed (else)
}···

if (nextToken.type === 'EOF') {
if (nextToken.value === '}') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'EOF') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.linesBetween({
if (nextToken.type === 'EOF') {
return;
}
errors.assert.linesBetween({
atLeast: 2,
token: endOfDeclaration,
nextToken: nextToken
});
});
}
};
require-padding-newlines-after-blocks.js
/**
* Requires newline after blocks
*
* Type: `Boolean` or `Object`
*
* Values:
* - `true`: always require a newline after blocks
* - `Object`:
* - `"allExcept"`: `Array`
* - `"inCallExpressions"` Blocks don't need a line of padding in function argument lists
* - `"inNewExpressions"` Blocks don't need a line of padding in constructor argument lists
* - `"inArrayExpressions"` Blocks don't need a line of padding in arrays
* - `"inProperties"` Blocks don't need a line of padding as object properties
* - `"singleLine"` Blocks don't need a line of padding if they are on a single line
*
* #### Example
*
* ```js
* "requirePaddingNewLinesAfterBlocks": true
* "requirePaddingNewLinesAfterBlocks": {
* "allExcept": ["inCallExpressions", "inNewExpressions", "inArrayExpressions", "inProperties", "singleLine"]
* }
* ```
*
* ##### Valid
*
* ```js
* function () {
* for (var i = 0; i < 2; i++) {
* if (true) {
* return false;
* }
*
* continue;
* }
*
* var obj = {
* foo: function() {
* return 1;
* },
*
* bar: function() {
* return 2;
* }
* };
*
* func(
* function() {
* }
* );
*
* var a = [
* function() {
* },
*
* function() {
* }
* ]
*
* }
* ```
*
* ##### Valid for `{ "allExcept": ["inCallExpressions"] }`
*
* ```js
* func(
* 2,
* 3,
* function() {
* }
* );
* ```
*
* ##### Valid for `{ "allExcept": ["inNewExpressions"] }`
*
* ```js
* new SomeClass(
* 2,
* 3,
* function() {
* }
* );
* ```
*
* ##### Valid for `{ "allExcept": ["inArrayExpressions"] }`
*
* ```js
* var foo = [
* 2,
* 3,
* function() {
* }
* ];
* ```
* ##### Valid for `{ "allExcept": ["inProperties"] }`
*
* ```js
* var foo = {
* a: 2,
* b: function() {
* },
* c: 3
* ];
* ```
* ##### Valid for `{ "allExcept": ["singleLine"] }`
* ```js
* for (var i = 0; i < 10; ++i) {
* if (i % 2 === 0) { continue; }
* console.log('Its getting odd in here...');
* }
* ```
*
* ##### Invalid
*
* ```js
* function () {
* for (var i = 0; i < 2; i++) {
* if (true) {
* return false;
* }
* continue;
* }
* }
* ```
*/
var assert = require('assert');
var excludes = {
'IfStatement': ['else'],
'DoWhileStatement': ['while'],
'TryStatement': ['catch', 'finally'],
'CatchClause': ['finally'],
'FunctionExpression': ['.'],
'ArrowFunctionExpression': [')']
};
Function (anonymous_1004)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1005)
✓ Was called
configure: function(value) {···
this.exceptions = {
'CallExpression': false,
'NewExpression': false,
'ArrayExpression': false,
'ObjectProperty': false,
'SingleLine': false
};

var optionName = this.getOptionName();

if (typeof value === 'object') {
assert(Array.isArray(value.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(value.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');

value.allExcept.forEach(function(except) {
if (except === 'inCallExpressions') {
this.exceptions.CallExpression = true;
} else if (except === 'inNewExpressions') {
this.exceptions.NewExpression = true;
} else if (except === 'inArrayExpressions') {
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
}, this);
} else {
assert(value === true,
optionName + ' option requires true value or object'
);
}
},
configure: function(value) {
this.exceptions = {
'CallExpression': false,
'NewExpression': false,
'ArrayExpression': false,
'ObjectProperty': false,
'SingleLine': false
};
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'object') {···
assert(Array.isArray(value.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(value.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');

value.allExcept.forEach(function(except) {
if (except === 'inCallExpressions') {
this.exceptions.CallExpression = true;
} else if (except === 'inNewExpressions') {
this.exceptions.NewExpression = true;
} else if (except === 'inArrayExpressions') {
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
}, this);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true,
optionName + ' option requires true value or object'
);
}
if (typeof value === 'object') {
assert(Array.isArray(value.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(value.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');
Function (anonymous_1006)
✓ Was called
value.allExcept.forEach(function(except) {···
if (except === 'inCallExpressions') {
this.exceptions.CallExpression = true;
} else if (except === 'inNewExpressions') {
this.exceptions.NewExpression = true;
} else if (except === 'inArrayExpressions') {
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
}, this);
value.allExcept.forEach(function(except) {
Branch IfStatement
✓ Positive was executed (if)
if (except === 'inCallExpressions') {···
this.exceptions.CallExpression = true;
} else if (except === 'inNewExpressions') {
✓ Negative was executed (else)
} else if (except === 'inNewExpressions') {···
this.exceptions.NewExpression = true;
} else if (except === 'inArrayExpressions') {
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
if (except === 'inCallExpressions') {
this.exceptions.CallExpression = true;
Branch IfStatement
✓ Positive was executed (if)
} else if (except === 'inNewExpressions') {···
this.exceptions.NewExpression = true;
} else if (except === 'inArrayExpressions') {
✓ Negative was executed (else)
} else if (except === 'inArrayExpressions') {···
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
} else if (except === 'inNewExpressions') {
this.exceptions.NewExpression = true;
Branch IfStatement
✓ Positive was executed (if)
} else if (except === 'inArrayExpressions') {···
this.exceptions.ArrayExpression = true;
} else if (except === 'inProperties') {
✓ Negative was executed (else)
} else if (except === 'inProperties') {···
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
} else if (except === 'inArrayExpressions') {
this.exceptions.ArrayExpression = true;
Branch IfStatement
✓ Positive was executed (if)
} else if (except === 'inProperties') {···
this.exceptions.ObjectProperty = true;
} else if (except === 'singleLine') {
✓ Negative was executed (else)
} else if (except === 'singleLine') {···
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
} else if (except === 'inProperties') {
this.exceptions.ObjectProperty = true;
Branch IfStatement
✓ Positive was executed (if)
} else if (except === 'singleLine') {···
this.exceptions.SingleLine = true;
} else {
✓ Negative was executed (else)
} else {···
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
} else if (except === 'singleLine') {
this.exceptions.SingleLine = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'one of "inCallExpressions", "inNewExpressions",' +
'"inArrayExpressions", "inProperties" or "singleLine"');
}
}, this);
} else {
assert(value === true,
optionName + ' option requires true value or object'
);
}
},
Function (anonymous_1007)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLinesAfterBlocks';
},
getOptionName: function() {
return 'requirePaddingNewLinesAfterBlocks';
},
Function (anonymous_1008)
✓ Was called
check: function(file, errors) {···
function isException(node, parent, exceptions) {
var grandpa = parent.parentElement;

// Check if this block is used in call or array expression
if (grandpa && exceptions[grandpa.type]) {
return true;
}

var first = node.getFirstToken();
var last = node.getLastToken();

if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {
return true;
}

return false;
}

file.iterateNodesByType('BlockStatement', (function(node) {

var endToken = file.getLastNodeToken(node);
var parentElement = node.parentElement;
var tokens = {
next: endToken.getNextCodeToken(),
token: endToken
};

if (isException(node, parentElement, this.exceptions)) {
return;
}

while (tokens.next.type !== 'EOF') {
var excludeValues = excludes[parentElement.type];
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {
return;
}

if (file.isOnTheSameLine(tokens.token, tokens.next)) {
endToken = tokens.next;
tokens.next = tokens.next.getNextCodeToken();
continue;
}

if (tokens.next.type === 'Punctuator' && (
tokens.next.value === '}' ||
tokens.next.value === ']' ||
tokens.next.value === '>' ||
tokens.next.value === ')')
) {
return;
}

errors.assert.linesBetween({
token: tokens.token,
nextToken: tokens.next,
atLeast: 2,
message: 'Missing newline after block'
});

return;
}
}).bind(this));
}
check: function(file, errors) {
Function isException
✓ Was called
function isException(node, parent, exceptions) {···
var grandpa = parent.parentElement;

// Check if this block is used in call or array expression
if (grandpa && exceptions[grandpa.type]) {
return true;
}

var first = node.getFirstToken();
var last = node.getLastToken();

if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {
return true;
}

return false;
}
function isException(node, parent, exceptions) {
var grandpa = parent.parentElement;
// Check if this block is used in call or array expression
Branch IfStatement
✓ Positive was executed (if)
if (grandpa && exceptions[grandpa.type]) {···
return true;
}
✓ Negative was executed (else)
}···

var first = node.getFirstToken();
Branch LogicalExpression
✓ Was returned
if (grandpa && exceptions[grandpa.type]) {
✓ Was returned
if (grandpa && exceptions[grandpa.type]) {
if (grandpa && exceptions[grandpa.type]) {
return true;
}
var first = node.getFirstToken();
var last = node.getLastToken();
Branch IfStatement
✓ Positive was executed (if)
if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {···
return true;
}
✓ Negative was executed (else)
}···

return false;
Branch LogicalExpression
✓ Was returned
if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {
✓ Was returned
if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {
if (exceptions.SingleLine && file.isOnTheSameLine(first, last)) {
return true;
}
return false;
}
Function (anonymous_1010)
✓ Was called
file.iterateNodesByType('BlockStatement', (function(node) {···

var endToken = file.getLastNodeToken(node);
var parentElement = node.parentElement;
var tokens = {
next: endToken.getNextCodeToken(),
token: endToken
};

if (isException(node, parentElement, this.exceptions)) {
return;
}

while (tokens.next.type !== 'EOF') {
var excludeValues = excludes[parentElement.type];
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {
return;
}

if (file.isOnTheSameLine(tokens.token, tokens.next)) {
endToken = tokens.next;
tokens.next = tokens.next.getNextCodeToken();
continue;
}

if (tokens.next.type === 'Punctuator' && (
tokens.next.value === '}' ||
tokens.next.value === ']' ||
tokens.next.value === '>' ||
tokens.next.value === ')')
) {
return;
}

errors.assert.linesBetween({
token: tokens.token,
nextToken: tokens.next,
atLeast: 2,
message: 'Missing newline after block'
});

return;
}
}).bind(this));
file.iterateNodesByType('BlockStatement', (function(node) {
var endToken = file.getLastNodeToken(node);
var parentElement = node.parentElement;
var tokens = {
next: endToken.getNextCodeToken(),
token: endToken
};
Branch IfStatement
✓ Positive was executed (if)
if (isException(node, parentElement, this.exceptions)) {···
return;
}
✓ Negative was executed (else)
}···

while (tokens.next.type !== 'EOF') {
if (isException(node, parentElement, this.exceptions)) {
return;
}
while (tokens.next.type !== 'EOF') {
var excludeValues = excludes[parentElement.type];
Branch IfStatement
✓ Positive was executed (if)
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {···
return;
}
✓ Negative was executed (else)
}···

if (file.isOnTheSameLine(tokens.token, tokens.next)) {
Branch LogicalExpression
✓ Was returned
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {
✗ Was not returned
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {
if (excludeValues && excludeValues.indexOf(tokens.next.value) !== -1) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (file.isOnTheSameLine(tokens.token, tokens.next)) {···
endToken = tokens.next;
tokens.next = tokens.next.getNextCodeToken();
continue;
}
✓ Negative was executed (else)
}···

if (tokens.next.type === 'Punctuator' && (
if (file.isOnTheSameLine(tokens.token, tokens.next)) {
endToken = tokens.next;
tokens.next = tokens.next.getNextCodeToken();
continue;
}
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.linesBetween({
Branch LogicalExpression
✓ Was returned
tokens.next.value === '}' ||···
tokens.next.value === ']' ||
tokens.next.value === '>' ||
tokens.next.value === ')')
✓ Was returned
if (tokens.next.type === 'Punctuator' && (
if (tokens.next.type === 'Punctuator' && (
Branch LogicalExpression
✓ Was returned
tokens.next.value === ')')
✓ Was returned
tokens.next.value === '}' ||···
tokens.next.value === ']' ||
tokens.next.value === '>' ||
Branch LogicalExpression
✓ Was returned
tokens.next.value === '>' ||
✓ Was returned
tokens.next.value === '}' ||···
tokens.next.value === ']' ||
Branch LogicalExpression
✓ Was returned
tokens.next.value === ']' ||
✓ Was returned
tokens.next.value === '}' ||
tokens.next.value === '}' ||
tokens.next.value === ']' ||
tokens.next.value === '>' ||
tokens.next.value === ')')
) {
return;
}
errors.assert.linesBetween({
token: tokens.token,
nextToken: tokens.next,
atLeast: 2,
message: 'Missing newline after block'
});
return;
}
}).bind(this));
}
};
require-padding-newlines-after-use-strict.js
/**
* Requires a blank line after `'use strict';` statements
*
* Values:
* - `true` for default behavior (require blank line after 'use strict' statements)
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'require'` allows 'require' statements to occur immediately after 'use strict'
*
* #### Example
*
* ```js
* "requirePaddingNewLinesAfterUseStrict": true
* ```
*
* ##### Valid
*
* ```js
* 'use strict';
*
* // code
* ```
*
* ##### Invalid
*
* ```js
* 'use strict';
* // code
* ```
*/
var assert = require('assert');
Function (anonymous_1011)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1012)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {allExcept: []};
return this.configure(_options);
}

if (Array.isArray(options.allExcept)) {
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {allExcept: []};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

if (Array.isArray(options.allExcept)) {
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}
✗ Negative was not executed (else)
}···
},
if (Array.isArray(options.allExcept)) {
this._exceptRequire = options.allExcept.indexOf('require') > -1;
}
},
Function (anonymous_1013)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLinesAfterUseStrict';
},
getOptionName: function() {
return 'requirePaddingNewLinesAfterUseStrict';
},
Function (anonymous_1014)
✓ Was called
check: function(file, errors) {···
var exceptRequire = this._exceptRequire;
file.iterateNodesByType('Directive', function(node) {
var literal = node.value;

if (literal.value !== 'use strict') {
return;
}

var endOfNode = file.getLastNodeToken(node);
if (exceptRequire) {
var requireToken = file.findNextToken(endOfNode, 'Identifier', 'require');
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {

// Ensure the detected require is the first declaration of this line
var keywordToken = file.getNextToken(endOfNode, {
includeComments: true
});
var identifierToken = file.getNextToken(file.getLastNodeToken(keywordToken), {
includeComments: true
});
var punctuatorToken = file.getNextToken(file.getLastNodeToken(identifierToken), {
includeComments: true
});
requireToken = file.getNextToken(file.getLastNodeToken(punctuatorToken), {
includeComments: true
});

if (
keywordToken.type === 'Keyword' &&
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
requireToken.value === 'require'
) {
return;
}
}
}

var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});

errors.assert.linesBetween({
atLeast: 2,
token: endOfNode,
nextToken: nextToken
});
});
}
check: function(file, errors) {
var exceptRequire = this._exceptRequire;
Function (anonymous_1015)
✓ Was called
file.iterateNodesByType('Directive', function(node) {···
var literal = node.value;

if (literal.value !== 'use strict') {
return;
}

var endOfNode = file.getLastNodeToken(node);
if (exceptRequire) {
var requireToken = file.findNextToken(endOfNode, 'Identifier', 'require');
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {

// Ensure the detected require is the first declaration of this line
var keywordToken = file.getNextToken(endOfNode, {
includeComments: true
});
var identifierToken = file.getNextToken(file.getLastNodeToken(keywordToken), {
includeComments: true
});
var punctuatorToken = file.getNextToken(file.getLastNodeToken(identifierToken), {
includeComments: true
});
requireToken = file.getNextToken(file.getLastNodeToken(punctuatorToken), {
includeComments: true
});

if (
keywordToken.type === 'Keyword' &&
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
requireToken.value === 'require'
) {
return;
}
}
}

var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});

errors.assert.linesBetween({
atLeast: 2,
token: endOfNode,
nextToken: nextToken
});
});
file.iterateNodesByType('Directive', function(node) {
var literal = node.value;
Branch IfStatement
✓ Positive was executed (if)
if (literal.value !== 'use strict') {···
return;
}
✓ Negative was executed (else)
}···

var endOfNode = file.getLastNodeToken(node);
if (literal.value !== 'use strict') {
return;
}
var endOfNode = file.getLastNodeToken(node);
Branch IfStatement
✓ Positive was executed (if)
if (exceptRequire) {···
var requireToken = file.findNextToken(endOfNode, 'Identifier', 'require');
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {

// Ensure the detected require is the first declaration of this line
var keywordToken = file.getNextToken(endOfNode, {
includeComments: true
});
var identifierToken = file.getNextToken(file.getLastNodeToken(keywordToken), {
includeComments: true
});
var punctuatorToken = file.getNextToken(file.getLastNodeToken(identifierToken), {
includeComments: true
});
requireToken = file.getNextToken(file.getLastNodeToken(punctuatorToken), {
includeComments: true
});

if (
keywordToken.type === 'Keyword' &&
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
requireToken.value === 'require'
) {
return;
}
}
}
✓ Negative was executed (else)
}···

var nextToken = file.getNextToken(endOfNode, {
if (exceptRequire) {
var requireToken = file.findNextToken(endOfNode, 'Identifier', 'require');
Branch IfStatement
✓ Positive was executed (if)
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {···

// Ensure the detected require is the first declaration of this line
var keywordToken = file.getNextToken(endOfNode, {
includeComments: true
});
var identifierToken = file.getNextToken(file.getLastNodeToken(keywordToken), {
includeComments: true
});
var punctuatorToken = file.getNextToken(file.getLastNodeToken(identifierToken), {
includeComments: true
});
requireToken = file.getNextToken(file.getLastNodeToken(punctuatorToken), {
includeComments: true
});

if (
keywordToken.type === 'Keyword' &&
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
requireToken.value === 'require'
) {
return;
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {
✓ Was returned
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {
if (requireToken && node.getLoc().start.line + 1 === requireToken.getLoc().start.line) {
// Ensure the detected require is the first declaration of this line
var keywordToken = file.getNextToken(endOfNode, {
includeComments: true
});
var identifierToken = file.getNextToken(file.getLastNodeToken(keywordToken), {
includeComments: true
});
var punctuatorToken = file.getNextToken(file.getLastNodeToken(identifierToken), {
includeComments: true
});
requireToken = file.getNextToken(file.getLastNodeToken(punctuatorToken), {
includeComments: true
});
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···
}
if (
Branch LogicalExpression
✓ Was returned
requireToken.value === 'require'
✓ Was returned
keywordToken.type === 'Keyword' &&···
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
requireToken.type === 'Identifier' &&
✗ Was not returned
keywordToken.type === 'Keyword' &&···
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
Branch LogicalExpression
✓ Was returned
punctuatorToken.type === 'Punctuator' &&
✗ Was not returned
keywordToken.type === 'Keyword' &&···
identifierToken.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
identifierToken.type === 'Identifier' &&
✗ Was not returned
keywordToken.type === 'Keyword' &&
keywordToken.type === 'Keyword' &&
identifierToken.type === 'Identifier' &&
punctuatorToken.type === 'Punctuator' &&
requireToken.type === 'Identifier' &&
requireToken.value === 'require'
) {
return;
}
}
}
var nextToken = file.getNextToken(endOfNode, {
includeComments: true
});
errors.assert.linesBetween({
atLeast: 2,
token: endOfNode,
nextToken: nextToken
});
});
}
};
require-padding-newlines-before-export.js
/**
* Requires newline before module.exports
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requirePaddingNewLinesBeforeExport": true
* ```
*
* ##### Valid
*
* ```js
* var a = 2;
*
* module.exports = a;
*
* if (cond) {
* module.exports = a;
* }
* ```
*
* ##### Invalid
*
* ```js
* var a = 2;
* module.exports = a;
*
* if (cond) {
* foo();
* module.exports = a;
* }
* ```
*/
var assert = require('assert');
Function (anonymous_1016)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1017)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1018)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLinesBeforeExport';
},
getOptionName: function() {
return 'requirePaddingNewLinesBeforeExport';
},
Function (anonymous_1019)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('AssignmentExpression', function(node) {
var left = node.left;
var greatGrandpa = node.parentElement.parentElement;
if (!(
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}

// module.exports is in a block and is the only statement.
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {
return;
}

var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken);

errors.assert.linesBetween({
atLeast: 2,
token: prevToken,
nextToken: firstToken,
message: 'Missing newline before export'
});
});

}
check: function(file, errors) {
Function (anonymous_1020)
✓ Was called
file.iterateNodesByType('AssignmentExpression', function(node) {···
var left = node.left;
var greatGrandpa = node.parentElement.parentElement;
if (!(
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}

// module.exports is in a block and is the only statement.
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {
return;
}

var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken);

errors.assert.linesBetween({
atLeast: 2,
token: prevToken,
nextToken: firstToken,
message: 'Missing newline before export'
});
});
file.iterateNodesByType('AssignmentExpression', function(node) {
var left = node.left;
var greatGrandpa = node.parentElement.parentElement;
Branch IfStatement
✓ Positive was executed (if)
left.property.name === 'exports')) {···
return;
}
✓ Negative was executed (else)
}···

// module.exports is in a block and is the only statement.
if (!(
Branch LogicalExpression
✓ Was returned
left.property.name === 'exports')) {
✓ Was returned
left.object &&···
left.object.name === 'module' &&
left.property &&
Branch LogicalExpression
✓ Was returned
left.property &&
✓ Was returned
left.object &&···
left.object.name === 'module' &&
Branch LogicalExpression
✓ Was returned
left.object.name === 'module' &&
✗ Was not returned
left.object &&
left.object &&
left.object.name === 'module' &&
left.property &&
left.property.name === 'exports')) {
return;
}
// module.exports is in a block and is the only statement.
Branch IfStatement
✓ Positive was executed (if)
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {···
return;
}
✓ Negative was executed (else)
}···

var firstToken = node.getFirstToken();
Branch LogicalExpression
✓ Was returned
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {
✓ Was returned
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {
if (greatGrandpa.type === 'BlockStatement' && greatGrandpa.body.length === 1) {
return;
}
var firstToken = node.getFirstToken();
var prevToken = file.getPrevToken(firstToken);
errors.assert.linesBetween({
atLeast: 2,
token: prevToken,
nextToken: firstToken,
message: 'Missing newline before export'
});
});
}
};
require-padding-newlines-before-keywords.js
/**
* Requires an empty line above the specified keywords unless the keyword is the first expression in a block.
*
* Types: `Boolean` or `Array`
*
* Values:
*
* - `true` specifies that the spacedKeywords found in the utils module require an empty line above it
* - `Array` specifies quoted keywords which require an empty line above it
*
* #### Example
*
* ```js
* "requirePaddingNewlinesBeforeKeywords": [
* "do",
* "for",
* "if",
* "else"
* // etc
* ]
* ```
*
* ##### Valid for mode `true`
*
* ```js
* function(a) {
* if (!a) {
* return false;
* }
*
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
* return false;
* }
* }
*
* while (a) {
* a = false;
* }
* return true;
* }
* ```
*
* ##### Invalid
*
* ```js
* function(a) {
* if (!a) {
* return false;
* }
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
* return false;
* }
* }
* while (a) {
* a = false;
* }
* return true;
* }
* ```
*
* ##### Valid for mode `['if', for']`
*
* ```js
* function(a) {
* if (!a) {
* return false;
* }
*
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
* return false;
* }
* }
* while (a) {
* a = false;
* }
* return true;
* }
* ```
*
* ##### Invalid
*
* ```js
* function(a) {
* if (!a) {
* return false;
* }
* for (var i = 0; i < b; i++) {
* if (!a[i]) {
* return false;
* }
* }
* while (a) {
* a = false;
* }
* return true;
* }
* ```
*
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
Function (anonymous_1021)
✓ Was called
module.exports = function() { };
module.exports = function() { };
module.exports.prototype = {
Function (anonymous_1022)
✓ Was called
configure: function(keywords) {···
assert(Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');

if (keywords === true) {
keywords = defaultKeywords;
}

this._keywords = keywords;
},
configure: function(keywords) {
Branch LogicalExpression
✓ Was returned
assert(Array.isArray(keywords) || keywords === true,
✓ Was returned
assert(Array.isArray(keywords) || keywords === true,
assert(Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');
Branch IfStatement
✓ Positive was executed (if)
if (keywords === true) {···
keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
Function (anonymous_1023)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewlinesBeforeKeywords';
},
getOptionName: function() {
return 'requirePaddingNewlinesBeforeKeywords';
},
Function (anonymous_1024)
✓ Was called
check: function(file, errors) {···
var excludedTokens = [':', ',', '(', '='];
var specialCases = { 'if': 'else' };
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = token.getPreviousCodeToken();

if (!prevToken) {
return;
}

// Handle special cases listed in specialCasesToken array
if (prevToken.value === specialCases[token.value]) {
return;
}

// allow returning a function
if (prevToken.value === 'return' && token.value === 'function') {
return;
}

// Do not report `do...while` statements
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {
return;
}

// Handle excludedTokens
if (excludedTokens.indexOf(prevToken.value) > -1) {
return;
}

// Handle all other cases
// The { character is there to handle the case of a matching token which happens to be the first
// statement in a block
// The ) character is there to handle the case of `if (...) matchingKeyword` in which case
// requiring padding would break the statement
if (prevToken.value !== '{' && prevToken.value !== ')') {
errors.assert.linesBetween({
token: prevToken,
nextToken: token,
atLeast: 2,
message: 'Keyword `' + token.value + '` should have an empty line above it'
});
}
});
}
check: function(file, errors) {
var excludedTokens = [':', ',', '(', '='];
var specialCases = { 'if': 'else' };
Function (anonymous_1025)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var prevToken = token.getPreviousCodeToken();

if (!prevToken) {
return;
}

// Handle special cases listed in specialCasesToken array
if (prevToken.value === specialCases[token.value]) {
return;
}

// allow returning a function
if (prevToken.value === 'return' && token.value === 'function') {
return;
}

// Do not report `do...while` statements
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {
return;
}

// Handle excludedTokens
if (excludedTokens.indexOf(prevToken.value) > -1) {
return;
}

// Handle all other cases
// The { character is there to handle the case of a matching token which happens to be the first
// statement in a block
// The ) character is there to handle the case of `if (...) matchingKeyword` in which case
// requiring padding would break the statement
if (prevToken.value !== '{' && prevToken.value !== ')') {
errors.assert.linesBetween({
token: prevToken,
nextToken: token,
atLeast: 2,
message: 'Keyword `' + token.value + '` should have an empty line above it'
});
}
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = token.getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken) {···
return;
}
✓ Negative was executed (else)
}···

// Handle special cases listed in specialCasesToken array
if (!prevToken) {
return;
}
// Handle special cases listed in specialCasesToken array
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value === specialCases[token.value]) {···
return;
}
✓ Negative was executed (else)
}···

// allow returning a function
if (prevToken.value === specialCases[token.value]) {
return;
}
// allow returning a function
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value === 'return' && token.value === 'function') {···
return;
}
✓ Negative was executed (else)
}···

// Do not report `do...while` statements
Branch LogicalExpression
✓ Was returned
if (prevToken.value === 'return' && token.value === 'function') {
✓ Was returned
if (prevToken.value === 'return' && token.value === 'function') {
if (prevToken.value === 'return' && token.value === 'function') {
return;
}
// Do not report `do...while` statements
Branch IfStatement
✓ Positive was executed (if)
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {···
return;
}
✓ Negative was executed (else)
}···

// Handle excludedTokens
Branch LogicalExpression
✓ Was returned
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {
✓ Was returned
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {
if (token.value === 'while' && token.parentElement.type === 'DoWhileStatement') {
return;
}
// Handle excludedTokens
Branch IfStatement
✓ Positive was executed (if)
if (excludedTokens.indexOf(prevToken.value) > -1) {···
return;
}
✓ Negative was executed (else)
}···

// Handle all other cases
if (excludedTokens.indexOf(prevToken.value) > -1) {
return;
}
// Handle all other cases
// The { character is there to handle the case of a matching token which happens to be the first
// statement in a block
// The ) character is there to handle the case of `if (...) matchingKeyword` in which case
// requiring padding would break the statement
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value !== '{' && prevToken.value !== ')') {···
errors.assert.linesBetween({
token: prevToken,
nextToken: token,
atLeast: 2,
message: 'Keyword `' + token.value + '` should have an empty line above it'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (prevToken.value !== '{' && prevToken.value !== ')') {
✓ Was returned
if (prevToken.value !== '{' && prevToken.value !== ')') {
if (prevToken.value !== '{' && prevToken.value !== ')') {
errors.assert.linesBetween({
token: prevToken,
nextToken: token,
atLeast: 2,
message: 'Keyword `' + token.value + '` should have an empty line above it'
});
}
});
}
};
require-padding-newlines-before-line-comments.js
/**
* Requires newline before line comments
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`: always require a newline before line comments
* - `Object`:
* - `"allExcept"`: `"firstAfterCurly"` Comments may be first line of block without extra padding
*
* #### Examples
* ```js
* "requirePaddingNewLinesBeforeLineComments": true
* "requirePaddingNewLinesBeforeLineComments": { "allExcept": "firstAfterCurly" }
* ```
*
* ##### Valid for `true`
*
* ```js
* var a = 2;
* var b = 3; // comment
*
* // comment
* return a;
*
* function() {
*
* // comment
* }
* ```
*
* ##### Valid for `{ "allExcept": "firstAfterCurly" }`
*
* ```js
* var a = 2;
*
* // comment
* return a;
*
* function() {
* // comment
* }
* ```
*
* ##### Invalid
*
* ```js
* var a = 2;
* //comment
* return a;
*
* function() {
* // comment
* }
* ```
*/
var assert = require('assert');
Function (anonymous_1026)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1027)
✓ Was called
configure: function(value) {···
this._allowFirstAfterCurly = false;

if (typeof value === 'object') {
assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
this.getOptionName() + ' option requires the "allExcept" ' +
'property to equal "firstAfterCurly"');
this._allowFirstAfterCurly = true;
} else {
assert(value === true,
this.getOptionName() + ' option requires true value or object'
);
}
},
configure: function(value) {
this._allowFirstAfterCurly = false;
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'object') {···
assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
this.getOptionName() + ' option requires the "allExcept" ' +
'property to equal "firstAfterCurly"');
this._allowFirstAfterCurly = true;
} else {
✓ Negative was executed (else)
} else {···
assert(value === true,
this.getOptionName() + ' option requires true value or object'
);
}
if (typeof value === 'object') {
Branch LogicalExpression
✓ Was returned
assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
✓ Was returned
assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
this.getOptionName() + ' option requires the "allExcept" ' +
'property to equal "firstAfterCurly"');
this._allowFirstAfterCurly = true;
} else {
assert(value === true,
this.getOptionName() + ' option requires true value or object'
);
}
},
Function (anonymous_1028)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLinesBeforeLineComments';
},
getOptionName: function() {
return 'requirePaddingNewLinesBeforeLineComments';
},
Function (anonymous_1029)
✓ Was called
check: function(file, errors) {···
var allowFirstAfterCurly = this._allowFirstAfterCurly;

file.iterateTokensByType('CommentLine', function(comment) {
if (comment.getLoc().start.line === 1) {
return;
}

var firstToken = file.getFirstTokenOnLineWith(comment);

// Should not consider code and comment on the same line (#1194)
if (firstToken !== null && firstToken.type !== 'EOF') {
return;
}

var prevToken = file.getPrevToken(comment, {includeComments: true});

if (!prevToken || prevToken.type === 'CommentLine') {
return;
}

if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
return;
}

errors.assert.linesBetween({
token: prevToken,
nextToken: comment,
atLeast: 2,
message: 'Line comments must be preceded with a blank line'
});
});
}
check: function(file, errors) {
var allowFirstAfterCurly = this._allowFirstAfterCurly;
Function (anonymous_1030)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
if (comment.getLoc().start.line === 1) {
return;
}

var firstToken = file.getFirstTokenOnLineWith(comment);

// Should not consider code and comment on the same line (#1194)
if (firstToken !== null && firstToken.type !== 'EOF') {
return;
}

var prevToken = file.getPrevToken(comment, {includeComments: true});

if (!prevToken || prevToken.type === 'CommentLine') {
return;
}

if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
return;
}

errors.assert.linesBetween({
token: prevToken,
nextToken: comment,
atLeast: 2,
message: 'Line comments must be preceded with a blank line'
});
});
file.iterateTokensByType('CommentLine', function(comment) {
Branch IfStatement
✓ Positive was executed (if)
if (comment.getLoc().start.line === 1) {···
return;
}
✓ Negative was executed (else)
}···

var firstToken = file.getFirstTokenOnLineWith(comment);
if (comment.getLoc().start.line === 1) {
return;
}
var firstToken = file.getFirstTokenOnLineWith(comment);
// Should not consider code and comment on the same line (#1194)
Branch IfStatement
✓ Positive was executed (if)
if (firstToken !== null && firstToken.type !== 'EOF') {···
return;
}
✓ Negative was executed (else)
}···

var prevToken = file.getPrevToken(comment, {includeComments: true});
Branch LogicalExpression
✓ Was returned
if (firstToken !== null && firstToken.type !== 'EOF') {
✓ Was returned
if (firstToken !== null && firstToken.type !== 'EOF') {
if (firstToken !== null && firstToken.type !== 'EOF') {
return;
}
var prevToken = file.getPrevToken(comment, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken || prevToken.type === 'CommentLine') {···
return;
}
✓ Negative was executed (else)
}···

if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
Branch LogicalExpression
✓ Was returned
if (!prevToken || prevToken.type === 'CommentLine') {
✓ Was returned
if (!prevToken || prevToken.type === 'CommentLine') {
if (!prevToken || prevToken.type === 'CommentLine') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.linesBetween({
Branch LogicalExpression
✓ Was returned
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
✓ Was returned
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
Branch LogicalExpression
✓ Was returned
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
✓ Was returned
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
return;
}
errors.assert.linesBetween({
token: prevToken,
nextToken: comment,
atLeast: 2,
message: 'Line comments must be preceded with a blank line'
});
});
}
};
require-padding-newlines-in-blocks.js
/**
* Requires blocks to begin and end with 2 newlines
*
* Types: `Boolean`, `Integer`, `Object`
*
* Values:
* - `true` validates all non-empty blocks
* - `Integer` specifies a minimum number of lines containing elements in the block before validating
* - `Object` (at least one of properties must be true):
* - `'open'`
* - `true` validates that there is a newline after the opening brace in a block
* - `false` ignores the newline validation after the opening brace in a block
* - `'close'`
* - `true` validates that there is a newline before the closing brace in a block
* - `false` ignores the newline validation before the closing brace in a block
* - `'allExcept'` array of exceptions:
* - `'conditionals'` ignores conditional (if, else if, else) blocks
* - `'functions'` ignores function blocks
*
* #### Example
*
* ```js
* "requirePaddingNewlinesInBlocks": true
* "requirePaddingNewlinesInBlocks": 1
* "requirePaddingNewlinesInBlocks": { "open": true, "close": false }
* "requirePaddingNewlinesInBlocks": { "allExcept": [ "conditionals" ] }
* "requirePaddingNewlinesInBlocks": { "open": true, "close": false, allExcept: ['conditionals'] }
* ```
*
* ##### Valid for mode `true` or `{ "open": true, "close": true }`
*
* ```js
* if (true) {
*
* doSomething();
*
* }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) {doSomething();}
* if (true) {
* doSomething();
* }
* ```
*
* ##### Valid for mode `1`
*
* ```js
* if (true) {
*
* doSomething();
* doSomethingElse();
*
* }
* if (true) {
* doSomething();
* }
* if (true) { doSomething(); }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) { doSomething(); doSomethingElse(); }
* if (true) {
* doSomething();
* doSomethingElse();
* }
* ```
*
* ##### Valid for mode `{ "open": true, "close": false }`
*
* ```js
* if (true) {
*
* doSomething();
* }
* var abc = function() {};
* ```
*
* ##### Invalid
*
* ```js
* if (true) {doSomething();}
* if (true) {
* doSomething();
* }
* if (true) {
* doSomething();
*
* }
* ```
*
* ##### Valid for `{ allExcept: ['conditionals'] }`
*
* ```js
* if (true) {
* doSomething();
* }
*
* function (foo) {
*
* return bar;
*
* }
* ```
*
* ##### Invalid
*
* ```js
* function (foo) {
* return bar;
* }
* ```
*
* ##### Valid for `{ "open": true, "close": false, allExcept: ['conditionals'] }`
*
* ```js
* function (foo) {
*
* return bar;
* }
*
* if (true) {
* doSomething();
* }
* ```
*
* ##### Invalid
*
* ```js
* function (foo) {
* return bar;
*
* }
* ```
*/
var assert = require('assert');
Function (anonymous_1031)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1032)
✓ Was called
configure: function(options) {···
var optionName = this.getOptionName();

assert(
options === true || typeof options === 'number' || typeof options === 'object',
optionName + ' option requires the value true, an Integer or an object'
);

this._checkOpen = true;
this._checkClose = true;
this._minLines = 0;

if (typeof options === 'object') {
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');

if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}

if (options.open || options.close) {
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
} else if (typeof options === 'number') {
this._minLines = options;
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
},
configure: function(options) {
var optionName = this.getOptionName();
assert(
Branch LogicalExpression
✓ Was returned
options === true || typeof options === 'number' || typeof options === 'object',
✓ Was returned
options === true || typeof options === 'number' || typeof options === 'object',
Branch LogicalExpression
✓ Was returned
options === true || typeof options === 'number' || typeof options === 'object',
✓ Was returned
options === true || typeof options === 'number' || typeof options === 'object',
options === true || typeof options === 'number' || typeof options === 'object',
optionName + ' option requires the value true, an Integer or an object'
);
this._checkOpen = true;
this._checkClose = true;
this._minLines = 0;
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');

if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}

if (options.open || options.close) {
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
} else if (typeof options === 'number') {
✓ Negative was executed (else)
} else if (typeof options === 'number') {···
this._minLines = options;
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
if (typeof options === 'object') {
Branch LogicalExpression
✓ Was returned
assert(options.allExcept || options.open || options.close,
✓ Was returned
assert(options.allExcept || options.open || options.close,
Branch LogicalExpression
✓ Was returned
assert(options.allExcept || options.open || options.close,
✓ Was returned
assert(options.allExcept || options.open || options.close,
assert(options.allExcept || options.open || options.close,
optionName + 'option requires either "open", "close", "allExcept"');
Branch IfStatement
✓ Positive was executed (if)
if (options.allExcept) {···
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}
✓ Negative was executed (else)
}···

if (options.open || options.close) {
if (options.allExcept) {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" to have at least one ' +
'item or be set to `true`');
this._exceptConditionals = options.allExcept.indexOf('conditionals') > -1;
this._exceptFunctions = options.allExcept.indexOf('functions') > -1;
}
Branch IfStatement
✓ Positive was executed (if)
if (options.open || options.close) {···
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');

this._checkOpen = options.open;
this._checkClose = options.close;
}
✓ Negative was executed (else)
}···
} else if (typeof options === 'number') {
Branch LogicalExpression
✓ Was returned
if (options.open || options.close) {
✓ Was returned
if (options.open || options.close) {
if (options.open || options.close) {
Branch LogicalExpression
✓ Was returned
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
✓ Was returned
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
assert(typeof options.open === 'boolean' && typeof options.close === 'boolean',
this.getOptionName() + ' option requires the "open" and "close" ' +
'properties to be booleans');
this._checkOpen = options.open;
this._checkClose = options.close;
}
Branch IfStatement
✓ Positive was executed (if)
} else if (typeof options === 'number') {···
this._minLines = options;
} else {
✓ Negative was executed (else)
} else {···
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
} else if (typeof options === 'number') {
this._minLines = options;
} else {
assert(options === true, this.getOptionName() + ' option requires either a true value, or an object');
}
},
Function (anonymous_1033)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewlinesInBlocks';
},
getOptionName: function() {
return 'requirePaddingNewlinesInBlocks';
},
Function (anonymous_1034)
✓ Was called
check: function(file, errors) {···
var minLines = this._minLines;
var exceptConditionals = this._exceptConditionals;
var exceptFunctions = this._exceptFunctions;
var checkOpen = this._checkOpen;
var checkClose = this._checkClose;

file.iterateNodesByType('BlockStatement', function(node) {
var openingBracket;
var closingBracket;

if (node.body.length <= minLines) {
return;
}

if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}

if (checkOpen === true) {
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atLeast: 2,
message: 'Expected a padding newline after opening curly brace'
});
}

if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atLeast: 2,
message: 'Expected a padding newline before closing curly brace'
});
}
});
}
check: function(file, errors) {
var minLines = this._minLines;
var exceptConditionals = this._exceptConditionals;
var exceptFunctions = this._exceptFunctions;
var checkOpen = this._checkOpen;
var checkClose = this._checkClose;
Function (anonymous_1035)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
var openingBracket;
var closingBracket;

if (node.body.length <= minLines) {
return;
}

if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}

if (checkOpen === true) {
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atLeast: 2,
message: 'Expected a padding newline after opening curly brace'
});
}

if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atLeast: 2,
message: 'Expected a padding newline before closing curly brace'
});
}
});
file.iterateNodesByType('BlockStatement', function(node) {
var openingBracket;
var closingBracket;
Branch IfStatement
✓ Positive was executed (if)
if (node.body.length <= minLines) {···
return;
}
✓ Negative was executed (else)
}···

if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
if (node.body.length <= minLines) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
node.parentElement.type === 'FunctionDeclaration')) {···
return;
}
✓ Negative was executed (else)
}···

if (checkOpen === true) {
Branch LogicalExpression
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||···
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
Branch LogicalExpression
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
✓ Was returned
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
if (exceptConditionals && node.parentElement.type === 'IfStatement' ||
Branch LogicalExpression
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||···
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
Branch LogicalExpression
✓ Was returned
node.parentElement.type === 'FunctionDeclaration')) {
✓ Was returned
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
exceptFunctions && (node.parentElement.type === 'FunctionExpression' ||
node.parentElement.type === 'FunctionDeclaration')) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (checkOpen === true) {···
openingBracket = node.getFirstToken();

errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atLeast: 2,
message: 'Expected a padding newline after opening curly brace'
});
}
✓ Negative was executed (else)
}···

if (checkClose === true) {
if (checkOpen === true) {
openingBracket = node.getFirstToken();
errors.assert.linesBetween({
token: openingBracket,
nextToken: file.getNextToken(openingBracket, {includeComments: true}),
atLeast: 2,
message: 'Expected a padding newline after opening curly brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (checkClose === true) {···
closingBracket = file.getLastNodeToken(node);

errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atLeast: 2,
message: 'Expected a padding newline before closing curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (checkClose === true) {
closingBracket = file.getLastNodeToken(node);
errors.assert.linesBetween({
token: file.getPrevToken(closingBracket, {includeComments: true}),
nextToken: closingBracket,
atLeast: 2,
message: 'Expected a padding newline before closing curly brace'
});
}
});
}
};
require-padding-newlines-in-objects.js
/**
* Requires newline inside curly braces of all objects.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requirePaddingNewLinesInObjects": true
* ```
*
* ##### Valid
*
* ```js
* var x = {
* a: 1
* };
* foo({
* a: {
* b: 1
* }
* });
* ```
*
* ##### Invalid
*
* ```js
* var x = { a: 1 };
* foo({a:{b:1}});
* ```
*/
var assert = require('assert');
Function (anonymous_1036)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1037)
✓ Was called
configure: function(value) {···
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(value) {
assert(
value === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1038)
✓ Was called
getOptionName: function() {···
return 'requirePaddingNewLinesInObjects';
},
getOptionName: function() {
return 'requirePaddingNewLinesInObjects';
},
Function (anonymous_1039)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}

errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);

errors.assert.differentLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
}
check: function(file, errors) {
Function (anonymous_1040)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}

errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);

errors.assert.differentLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.differentLine({
Branch LogicalExpression
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
if (nextToken.type === 'Punctuator' && nextToken.value === '}') {
return;
}
errors.assert.differentLine({
token: openingBracket,
nextToken: nextToken,
message: 'Missing newline after opening curly brace'
});
var closingBracket = file.getLastNodeToken(node);
errors.assert.differentLine({
token: file.getPrevToken(closingBracket),
nextToken: closingBracket,
message: 'Missing newline before closing curly brace'
});
});
}
};
require-parentheses-around-arrow-param.js
/**
* Requires parentheses around arrow function expressions with a single parameter.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireParenthesesAroundArrowParam": true
* ```
*
* ##### Valid
*
* ```js
* [1, 2, 3].map((x) => x * x);
* // params are always required for multiple parameters
* [1, 2, 3].map((x, y, z) => x * x);
* ```
*
* ##### Invalid
*
* ```js
* [1, 2, 3].map(x => x * x);
* ```
*/
var assert = require('assert');
Function (anonymous_1041)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1042)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1043)
✓ Was called
getOptionName: function() {···
return 'requireParenthesesAroundArrowParam';
},
getOptionName: function() {
return 'requireParenthesesAroundArrowParam';
},
Function (anonymous_1044)
✓ Was called
check: function(file, errors) {···
function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}

file.iterateNodesByType('ArrowFunctionExpression', function(node) {
var params = node.params;
var firstParam = params[0];

if (params.length === 1 && !isWrapped(firstParam)) {
errors.add(
'Wrap arrow function expressions in parentheses',
firstParam
);
}
});
}
check: function(file, errors) {
Function isWrapped
✓ Was called
function isWrapped(node) {···
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}
function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
Branch ConditionalExpression
✓ Positive was returned (? ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
✗ Negative was not returned (: ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
return openParensToken.value + closingTokenValue === '()';
}
Function (anonymous_1046)
✓ Was called
file.iterateNodesByType('ArrowFunctionExpression', function(node) {···
var params = node.params;
var firstParam = params[0];

if (params.length === 1 && !isWrapped(firstParam)) {
errors.add(
'Wrap arrow function expressions in parentheses',
firstParam
);
}
});
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
var params = node.params;
var firstParam = params[0];
Branch IfStatement
✓ Positive was executed (if)
if (params.length === 1 && !isWrapped(firstParam)) {···
errors.add(
'Wrap arrow function expressions in parentheses',
firstParam
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (params.length === 1 && !isWrapped(firstParam)) {
✓ Was returned
if (params.length === 1 && !isWrapped(firstParam)) {
if (params.length === 1 && !isWrapped(firstParam)) {
errors.add(
'Wrap arrow function expressions in parentheses',
firstParam
);
}
});
}
};
require-parentheses-around-iife.js
/**
* Requires parentheses around immediately invoked function expressions.
*
* Type: `Boolean`
*
* Value: `true`
*
* JSHint: [`immed`](http://www.jshint.com/docs/options/#immed)
*
* #### Example
*
* ```js
* "requireParenthesesAroundIIFE": true
* ```
*
* ##### Valid
*
* ```js
* var a = (function(){ return 1; })();
* var b = (function(){ return 2; }());
* var c = (function(){ return 3; }).call(this, arg1);
* var d = (function(){ return 3; }.call(this, arg1));
* var e = (function(){ return d; }).apply(this, args);
* var f = (function(){ return d; }.apply(this, args));
* ```
*
* ##### Invalid
*
* ```js
* var a = function(){ return 1; }();
* var c = function(){ return 3; }.call(this, arg1);
* var d = function(){ return d; }.apply(this, args);
* ```
*/
var assert = require('assert');
var utils = require('../utils');
Function (anonymous_1047)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1048)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1049)
✓ Was called
getOptionName: function() {···
return 'requireParenthesesAroundIIFE';
},
getOptionName: function() {
return 'requireParenthesesAroundIIFE';
},
Function (anonymous_1050)
✓ Was called
check: function(file, errors) {···

function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));

var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}

file.iterateNodesByType('CallExpression', function(node) {
var inner = utils.getFunctionNodeFromIIFE(node);

if (inner && !isWrapped(inner) && !isWrapped(node)) {
errors.add(
'Wrap immediately invoked function expressions in parentheses',
node
);

}
});
}
check: function(file, errors) {
Function isWrapped
✓ Was called
function isWrapped(node) {···
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));

var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
var closingTokenValue = closingParensToken ? closingParensToken.value : '';

return openParensToken.value + closingTokenValue === '()';
}
function isWrapped(node) {
var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
Branch ConditionalExpression
✓ Positive was returned (? ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
✗ Negative was not returned (: ...)
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
var closingTokenValue = closingParensToken ? closingParensToken.value : '';
return openParensToken.value + closingTokenValue === '()';
}
Function (anonymous_1052)
✓ Was called
file.iterateNodesByType('CallExpression', function(node) {···
var inner = utils.getFunctionNodeFromIIFE(node);

if (inner && !isWrapped(inner) && !isWrapped(node)) {
errors.add(
'Wrap immediately invoked function expressions in parentheses',
node
);

}
});
file.iterateNodesByType('CallExpression', function(node) {
var inner = utils.getFunctionNodeFromIIFE(node);
Branch IfStatement
✓ Positive was executed (if)
if (inner && !isWrapped(inner) && !isWrapped(node)) {···
errors.add(
'Wrap immediately invoked function expressions in parentheses',
node
);

}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (inner && !isWrapped(inner) && !isWrapped(node)) {
✓ Was returned
if (inner && !isWrapped(inner) && !isWrapped(node)) {
Branch LogicalExpression
✓ Was returned
if (inner && !isWrapped(inner) && !isWrapped(node)) {
✓ Was returned
if (inner && !isWrapped(inner) && !isWrapped(node)) {
if (inner && !isWrapped(inner) && !isWrapped(node)) {
errors.add(
'Wrap immediately invoked function expressions in parentheses',
node
);
}
});
}
};
require-quoted-keys-in-objects.js
/**
* Requires quoted keys in objects.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireQuotedKeysInObjects": true
* ```
*
* ##### Valid
*
* ```js
* var x = { 'a': { "default": 1 } };
* ```
*
* ##### Invalid
*
* ```js
* var x = { a: 1 };
* ```
*/
var assert = require('assert');
var cst = require('cst');
Function (anonymous_1053)
✓ Was called
module.exports = function() { };
module.exports = function() { };
module.exports.prototype = {
Function (anonymous_1054)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1055)
✓ Was called
getOptionName: function() {···
return 'requireQuotedKeysInObjects';
},
getOptionName: function() {
return 'requireQuotedKeysInObjects';
},
Function (anonymous_1056)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
node.type === 'SpreadProperty') {
return;
}

var key = property.key;
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
errors.cast({
message: 'Object key without surrounding quotes',
element: property.firstChild
});
}
});
});
},
check: function(file, errors) {
Function (anonymous_1057)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
node.type === 'SpreadProperty') {
return;
}

var key = property.key;
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
errors.cast({
message: 'Object key without surrounding quotes',
element: property.firstChild
});
}
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_1058)
✓ Was called
node.properties.forEach(function(property) {···
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
node.type === 'SpreadProperty') {
return;
}

var key = property.key;
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
errors.cast({
message: 'Object key without surrounding quotes',
element: property.firstChild
});
}
});
node.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

if (property.shorthand || property.method ||
if (
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
property.type === 'ObjectMethod' &&
property.type === 'ObjectMethod' &&
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
(property.kind === 'get' || property.kind === 'set')
) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
node.type === 'SpreadProperty') {···
return;
}
✓ Negative was executed (else)
}···

var key = property.key;
Branch LogicalExpression
✓ Was returned
node.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand || property.method ||
Branch LogicalExpression
✓ Was returned
if (property.shorthand || property.method ||
✓ Was returned
if (property.shorthand || property.method ||
if (property.shorthand || property.method ||
node.type === 'SpreadProperty') {
return;
}
var key = property.key;
Branch IfStatement
✓ Positive was executed (if)
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {···
errors.cast({
message: 'Object key without surrounding quotes',
element: property.firstChild
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
✓ Was returned
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
Branch LogicalExpression
✓ Was returned
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
✓ Was returned
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
errors.cast({
message: 'Object key without surrounding quotes',
element: property.firstChild
});
}
});
});
},
Function (anonymous_1059)
✓ Was called
_fix: function(file, error) {···
var element = error.element.firstChild;
var newElem = new cst.Token(element.type, '"' + element.getSourceCode() + '"');

element.parentElement.replaceChild(
newElem,
element
);
}
_fix: function(file, error) {
var element = error.element.firstChild;
var newElem = new cst.Token(element.type, '"' + element.getSourceCode() + '"');
element.parentElement.replaceChild(
newElem,
element
);
}
};
require-semicolons.js
/**
* Requires semicolon after:
*
* * var declaration
* * expression statement
* * return
* * throw
* * break
* * continue
* * do-while
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSemicolons": true
* ```
*
* ##### Valid
*
* ```js
* var a = 1;
* ```
*
* ##### Invalid
*
* ```js
* var a = 1
* ```
*/
var assert = require('assert');
var cst = require('cst');
Function (anonymous_1060)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1061)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1062)
✓ Was called
getOptionName: function() {···
return 'requireSemicolons';
},
getOptionName: function() {
return 'requireSemicolons';
},
Function (anonymous_1063)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType([
'VariableDeclaration',
'ImportDeclaration',
'ExportDeclaration',
'ExportDefaultDeclaration',
'ExportNamedDeclaration',
'ExpressionStatement',
'DoWhileStatement',
'ReturnStatement',
'ThrowStatement',
'BreakStatement',
'ContinueStatement',
'DebuggerStatement',
'ClassProperty'
], function(node) {
// ignore variable declaration inside for and for-in
if (node.type === 'VariableDeclaration') {
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
return;
}
}

// don't require semicolon for class and function exports
if (node.type === 'ExportDefaultDeclaration' ||
node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
if (node.declaration.type === 'ClassDeclaration' ||
node.declaration.type === 'FunctionDeclaration') {
return;
}
}
}

// get last token inside node
var lastToken = file.getLastNodeToken(node);
var checkToken = lastToken;

// if last token is not a semicolon punctuator, try to get next token in file
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
checkToken = file.getNextToken(checkToken);
}

// check token is semicolon
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
var entity = lastToken || node;

errors.cast({
message: 'Missing semicolon after statement',
element: entity
});
}
});
},
check: function(file, errors) {
file.iterateNodesByType([
'VariableDeclaration',
'ImportDeclaration',
'ExportDeclaration',
'ExportDefaultDeclaration',
'ExportNamedDeclaration',
'ExpressionStatement',
'DoWhileStatement',
'ReturnStatement',
'ThrowStatement',
'BreakStatement',
'ContinueStatement',
'DebuggerStatement',
'ClassProperty'
Function (anonymous_1064)
✓ Was called
], function(node) {···
// ignore variable declaration inside for and for-in
if (node.type === 'VariableDeclaration') {
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
return;
}
}

// don't require semicolon for class and function exports
if (node.type === 'ExportDefaultDeclaration' ||
node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
if (node.declaration.type === 'ClassDeclaration' ||
node.declaration.type === 'FunctionDeclaration') {
return;
}
}
}

// get last token inside node
var lastToken = file.getLastNodeToken(node);
var checkToken = lastToken;

// if last token is not a semicolon punctuator, try to get next token in file
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
checkToken = file.getNextToken(checkToken);
}

// check token is semicolon
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
var entity = lastToken || node;

errors.cast({
message: 'Missing semicolon after statement',
element: entity
});
}
});
], function(node) {
// ignore variable declaration inside for and for-in
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclaration') {···
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
return;
}
}
✓ Negative was executed (else)
}···

// don't require semicolon for class and function exports
if (node.type === 'VariableDeclaration') {
Branch IfStatement
✓ Positive was executed (if)
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
✓ Was returned
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||···
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
Branch LogicalExpression
✓ Was returned
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
✓ Was returned
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
Branch LogicalExpression
✓ Was returned
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
✓ Was returned
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
if ((node.parentElement.type === 'ForInStatement' && node.parentElement.left === node) ||
Branch LogicalExpression
✓ Was returned
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
✓ Was returned
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
(node.parentElement.type === 'ForOfStatement' && node.parentElement.left === node) ||
Branch LogicalExpression
✓ Was returned
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
✓ Was returned
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
(node.parentElement.type === 'ForStatement' && node.parentElement.init === node)) {
return;
}
}
// don't require semicolon for class and function exports
Branch IfStatement
✓ Positive was executed (if)
node.type === 'ExportNamedDeclaration') {···
if (node.declaration) {
if (node.declaration.type === 'ClassDeclaration' ||
node.declaration.type === 'FunctionDeclaration') {
return;
}
}
}
✓ Negative was executed (else)
}···

// get last token inside node
Branch LogicalExpression
✓ Was returned
node.type === 'ExportNamedDeclaration') {
✓ Was returned
if (node.type === 'ExportDefaultDeclaration' ||
if (node.type === 'ExportDefaultDeclaration' ||
node.type === 'ExportNamedDeclaration') {
Branch IfStatement
✓ Positive was executed (if)
if (node.declaration) {···
if (node.declaration.type === 'ClassDeclaration' ||
node.declaration.type === 'FunctionDeclaration') {
return;
}
}
✓ Negative was executed (else)
}···
}
if (node.declaration) {
Branch IfStatement
✓ Positive was executed (if)
node.declaration.type === 'FunctionDeclaration') {···
return;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
node.declaration.type === 'FunctionDeclaration') {
✓ Was returned
if (node.declaration.type === 'ClassDeclaration' ||
if (node.declaration.type === 'ClassDeclaration' ||
node.declaration.type === 'FunctionDeclaration') {
return;
}
}
}
// get last token inside node
var lastToken = file.getLastNodeToken(node);
var checkToken = lastToken;
// if last token is not a semicolon punctuator, try to get next token in file
Branch IfStatement
✓ Positive was executed (if)
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {···
checkToken = file.getNextToken(checkToken);
}
✓ Negative was executed (else)
}···

// check token is semicolon
Branch LogicalExpression
✓ Was returned
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
✗ Was not returned
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
Branch LogicalExpression
✓ Was returned
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
✓ Was returned
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
if (checkToken && (checkToken.type !== 'Punctuator' || checkToken.value !== ';')) {
checkToken = file.getNextToken(checkToken);
}
// check token is semicolon
Branch IfStatement
✓ Positive was executed (if)
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {···
var entity = lastToken || node;

errors.cast({
message: 'Missing semicolon after statement',
element: entity
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
✓ Was returned
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
Branch LogicalExpression
✓ Was returned
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
✗ Was not returned
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
if (!checkToken || checkToken.type !== 'Punctuator' || checkToken.value !== ';') {
Branch LogicalExpression
✗ Was not returned
var entity = lastToken || node;
✓ Was returned
var entity = lastToken || node;
var entity = lastToken || node;
errors.cast({
message: 'Missing semicolon after statement',
element: entity
});
}
});
},
Function (anonymous_1065)
✓ Was called
_fix: function(file, error) {···
var element = error.element;
var semicolon = new cst.Token('Punctuator', ';');

while (element) {
try {
element.appendChild(semicolon);
break;
} catch (e) {}

element = element.parentElement;
}
}
_fix: function(file, error) {
var element = error.element;
var semicolon = new cst.Token('Punctuator', ';');
while (element) {
try {
element.appendChild(semicolon);
break;
} catch (e) {}
element = element.parentElement;
}
}
};
require-shorthand-arrow-functions.js
/**
* Require arrow functions to use an expression body when returning a single statement
* (no block statement, implicit return).
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireShorthandArrowFunctions": true
* ```
*
* ##### Valid
*
* ```js
* // single expression
* evens.map(v => v + 1);
* // multiple statments require a block
* evens.map(v => {
* v = v + 1;
* return v;
* });
* ```
*
* ##### Invalid
*
* ```js
* evens.map(v => { return v + 1; });
* ```
*/
var assert = require('assert');
Function (anonymous_1066)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1067)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1068)
✓ Was called
getOptionName: function() {···
return 'requireShorthandArrowFunctions';
},
getOptionName: function() {
return 'requireShorthandArrowFunctions';
},
Function (anonymous_1069)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
var body = node.body;
if (body.type === 'BlockStatement' &&
body.body.length === 1 &&
body.body[0].type === 'ReturnStatement') {
errors.add(
'Use the shorthand arrow function form',
node.body
);
}
});
}
check: function(file, errors) {
Function (anonymous_1070)
✓ Was called
file.iterateNodesByType('ArrowFunctionExpression', function(node) {···
var body = node.body;
if (body.type === 'BlockStatement' &&
body.body.length === 1 &&
body.body[0].type === 'ReturnStatement') {
errors.add(
'Use the shorthand arrow function form',
node.body
);
}
});
file.iterateNodesByType('ArrowFunctionExpression', function(node) {
var body = node.body;
Branch IfStatement
✓ Positive was executed (if)
body.body[0].type === 'ReturnStatement') {···
errors.add(
'Use the shorthand arrow function form',
node.body
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
body.body[0].type === 'ReturnStatement') {
✓ Was returned
if (body.type === 'BlockStatement' &&···
body.body.length === 1 &&
Branch LogicalExpression
✓ Was returned
body.body.length === 1 &&
✓ Was returned
if (body.type === 'BlockStatement' &&
if (body.type === 'BlockStatement' &&
body.body.length === 1 &&
body.body[0].type === 'ReturnStatement') {
errors.add(
'Use the shorthand arrow function form',
node.body
);
}
});
}
};
require-space-after-binary-operators.js
/**
* Disallows sticking binary operators to the right.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to require space after all possible binary operators
*
* #### Example
*
* ```js
* "requireSpaceAfterBinaryOperators": [
* "=",
* ",",
* "+",
* "-",
* "/",
* "*",
* "==",
* "===",
* "!=",
* "!=="
* // etc
* ]
* ```
*
* ##### Valid
*
* ```js
* x + y;
* ```
*
* ##### Invalid
*
* ```js
* x +y;
* ```
*/
var assert = require('assert');
var allOperators = require('../utils').binaryOperators;
Function (anonymous_1071)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1072)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = allOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = allOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = allOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_1073)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterBinaryOperators';
},
getOptionName: function() {
return 'requireSpaceAfterBinaryOperators';
},
Function (anonymous_1074)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;

// Comma
if (operators[',']) {
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should not stick to following expression'
});
});
}

// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
function(node) {
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var nextToken = file.getNextToken(operatorToken);

if (operators[operator]) {
errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should not stick to following expression'
});
}
}
);
}
check: function(file, errors) {
var operators = this._operatorIndex;
// Comma
Branch IfStatement
✓ Positive was executed (if)
if (operators[',']) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should not stick to following expression'
});
});
}
✓ Negative was executed (else)
}···

// For everything else
if (operators[',']) {
Function (anonymous_1075)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should not stick to following expression'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Operator , should not stick to following expression'
});
});
}
// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
Function (anonymous_1076)
✓ Was called
function(node) {···
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var nextToken = file.getNextToken(operatorToken);

if (operators[operator]) {
errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should not stick to following expression'
});
}
}
function(node) {
var operator;
var expression;
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclarator') {···
expression = node.init;
operator = '=';
} else {
✓ Negative was executed (else)
} else {···
operator = node.operator;
expression = node.right;
}
if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}
Branch IfStatement
✓ Positive was executed (if)
if (expression === null) {···
return;
}
✓ Negative was executed (else)
}···

var operatorToken = file.findPrevOperatorToken(
if (expression === null) {
return;
}
var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);
var nextToken = file.getNextToken(operatorToken);
Branch IfStatement
✓ Positive was executed (if)
if (operators[operator]) {···
errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should not stick to following expression'
});
}
✓ Negative was executed (else)
}···
}
if (operators[operator]) {
errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + operator + ' should not stick to following expression'
});
}
}
);
}
};
require-space-after-comma.js
/**
* Requires space after comma
*
* Types: `Boolean`, or `Object`
*
* Values:
* - `Boolean`: `true` to require a space after any comma
* - `Object`:
* - `"allExcept"` array of exceptions:
* - `"trailing"` ignore trailing commas
*
* #### Example
*
* ```js
* "requireSpaceAfterComma": true
* ```
* ```
* "requireSpaceAfterComma": {"allExcept": ["trailing"]}
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var a, b;
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* var a,b;
* ```
*
*##### Valid for mode `{"allExcept": ["trailing"]}`
*
* ```js
* var a = [1, 2,];
* ```
*
* ##### Invalid for mode `{"allExcept": ["trailing"]}`
*
* ```js
* var a = [a,b,];
* ```
*
*/
var assert = require('assert');
Function (anonymous_1077)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_1078)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}

assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptTrailingCommas = options.allExcept.indexOf('trailing') >= 0;
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

assert(
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires true value or an object'
);
var _options = {allExcept: []};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
' property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
this._exceptTrailingCommas = options.allExcept.indexOf('trailing') >= 0;
},
Function (anonymous_1079)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterComma';
},
getOptionName: function() {
return 'requireSpaceAfterComma';
},
Function (anonymous_1080)
✓ Was called
check: function(file, errors) {···
var exceptTrailingCommas = this._exceptTrailingCommas;
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {
return;
}
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Space required after comma'
});
});
}
check: function(file, errors) {
var exceptTrailingCommas = this._exceptTrailingCommas;
Function (anonymous_1081)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {
return;
}
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Space required after comma'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
Branch IfStatement
✓ Positive was executed (if)
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {···
return;
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {
✓ Was returned
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {
if (exceptTrailingCommas && [']', '}'].indexOf(file.getNextToken(token).value) >= 0) {
return;
}
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Space required after comma'
});
});
}
};
require-space-after-keywords.js
/**
* Requires space after keyword.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to require all of the keywords below to have a space afterward.
*
* #### Example
*
* ```js
* "requireSpaceAfterKeywords": [
* "do",
* "for",
* "if",
* "else",
* "switch",
* "case",
* "try",
* "catch",
* "void",
* "while",
* "with",
* "return",
* "typeof",
* "function"
* ]
* ```
*
* ##### Valid
*
* ```js
* if (x) {
* x++;
* }
* ```
*
* ##### Invalid
*
* ```js
* if(x) {
* x++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
Function (anonymous_1082)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1083)
✓ Was called
configure: function(keywords) {···
assert(
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');

if (keywords === true) {
keywords = defaultKeywords;
}

this._keywords = keywords;
},
configure: function(keywords) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || keywords === true,
✓ Was returned
Array.isArray(keywords) || keywords === true,
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value');
Branch IfStatement
✓ Positive was executed (if)
if (keywords === true) {···
keywords = defaultKeywords;
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
Function (anonymous_1084)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterKeywords';
},
getOptionName: function() {
return 'requireSpaceAfterKeywords';
},
Function (anonymous_1085)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});

if (nextToken.type === 'Punctuator' && nextToken.value === ';') {
return;
}

errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after "' + token.value + '" keyword'
});
});
}
check: function(file, errors) {
Function (anonymous_1086)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var nextToken = file.getNextToken(token, {includeComments: true});

if (nextToken.type === 'Punctuator' && nextToken.value === ';') {
return;
}

errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after "' + token.value + '" keyword'
});
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.type === 'Punctuator' && nextToken.value === ';') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.spacesBetween({
Branch LogicalExpression
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === ';') {
✓ Was returned
if (nextToken.type === 'Punctuator' && nextToken.value === ';') {
if (nextToken.type === 'Punctuator' && nextToken.value === ';') {
return;
}
errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after "' + token.value + '" keyword'
});
});
}
};
require-space-after-line-comment.js
/**
* Requires that a line comment (`//`) be followed by a space.
*
* Types: `Boolean`, `Object` or `String`
*
* Values:
* - `true`
* - `"allowSlash"` (*deprecated* use `"allExcept": ["/"]`) allows `/// ` format
* - `Object`:
* - `allExcept`: array of allowed strings before space `//(here) `
*
* #### Example
*
* ```js
* "requireSpaceAfterLineComment": { "allExcept": ["#", "="] }
* ```
*
* ##### Valid
*
* ```js
* // A comment
* /*A comment*\/
* //# sourceURL=filename.js
* //= require something
* ```
*
* ##### Invalid
*
* ```js
* //A comment
* ```
*/
var assert = require('assert');
Function (anonymous_1087)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1088)
✓ Was called
configure: function(options) {···
assert(
options === true ||
options === 'allowSlash' ||
typeof options === 'object',
this.getOptionName() + ' option requires a true value ' +
'or an object with String[] `allExcept` property'
);

// verify first item in `allExcept` property in object (if it's an object)
assert(
typeof options !== 'object' ||
Array.isArray(options.allExcept) &&
typeof options.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);

// don't check triple slashed comments, microsoft js doc convention. see #593
// exceptions. see #592
// need to drop allowSlash support in 2.0. Fixes #697
this._allExcept = options === 'allowSlash' ? ['/'] :
options.allExcept || [];
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'object',
✓ Was returned
options === true ||···
options === 'allowSlash' ||
Branch LogicalExpression
✓ Was returned
options === 'allowSlash' ||
✓ Was returned
options === true ||
options === true ||
options === 'allowSlash' ||
typeof options === 'object',
this.getOptionName() + ' option requires a true value ' +
'or an object with String[] `allExcept` property'
);
// verify first item in `allExcept` property in object (if it's an object)
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(options.allExcept) &&···
typeof options.allExcept[0] === 'string',
✓ Was returned
typeof options !== 'object' ||
typeof options !== 'object' ||
Branch LogicalExpression
✓ Was returned
typeof options.allExcept[0] === 'string',
✗ Was not returned
Array.isArray(options.allExcept) &&
Array.isArray(options.allExcept) &&
typeof options.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
// don't check triple slashed comments, microsoft js doc convention. see #593
// exceptions. see #592
// need to drop allowSlash support in 2.0. Fixes #697
Branch ConditionalExpression
✓ Positive was returned (? ...)
this._allExcept = options === 'allowSlash' ? ['/'] :
✓ Negative was returned (: ...)
options.allExcept || [];
this._allExcept = options === 'allowSlash' ? ['/'] :
Branch LogicalExpression
✓ Was returned
options.allExcept || [];
✓ Was returned
options.allExcept || [];
options.allExcept || [];
},
Function (anonymous_1089)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterLineComment';
},
getOptionName: function() {
return 'requireSpaceAfterLineComment';
},
Function (anonymous_1090)
✓ Was called
check: function(file, errors) {···
var allExcept = this._allExcept;

file.iterateTokensByType('CommentLine', function(comment) {
var value = comment.value;

// cutout exceptions
allExcept.forEach(function(el) {
if (value.indexOf(el) === 0) {
value = value.substr(el.length);
}
});

if (value.length === 0) {
return;
}

if (value[0] !== ' ') {
errors.add('Missing space after line comment', comment);
}
});
}
check: function(file, errors) {
var allExcept = this._allExcept;
Function (anonymous_1091)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
var value = comment.value;

// cutout exceptions
allExcept.forEach(function(el) {
if (value.indexOf(el) === 0) {
value = value.substr(el.length);
}
});

if (value.length === 0) {
return;
}

if (value[0] !== ' ') {
errors.add('Missing space after line comment', comment);
}
});
file.iterateTokensByType('CommentLine', function(comment) {
var value = comment.value;
// cutout exceptions
Function (anonymous_1092)
✓ Was called
allExcept.forEach(function(el) {···
if (value.indexOf(el) === 0) {
value = value.substr(el.length);
}
});
allExcept.forEach(function(el) {
Branch IfStatement
✓ Positive was executed (if)
if (value.indexOf(el) === 0) {···
value = value.substr(el.length);
}
✓ Negative was executed (else)
}···
});
if (value.indexOf(el) === 0) {
value = value.substr(el.length);
}
});
Branch IfStatement
✓ Positive was executed (if)
if (value.length === 0) {···
return;
}
✓ Negative was executed (else)
}···

if (value[0] !== ' ') {
if (value.length === 0) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (value[0] !== ' ') {···
errors.add('Missing space after line comment', comment);
}
✓ Negative was executed (else)
}···
});
if (value[0] !== ' ') {
errors.add('Missing space after line comment', comment);
}
});
}
};
require-space-after-object-keys.js
/**
* Requires space after object keys.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSpaceAfterObjectKeys": true
* ```
*
* ##### Valid
* ```js
* var x = {a : 1};
* ```
* ##### Invalid
* ```js
* var x = {a: 1};
* ```
*/
var assert = require('assert');
Function (anonymous_1093)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1094)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1095)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterObjectKeys';
},
getOptionName: function() {
return 'requireSpaceAfterObjectKeys';
},
Function (anonymous_1096)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand ||
property.type === 'SpreadProperty') {
return;
}

var token = file.getLastNodeToken(property.key);

if (property.computed === true) {
token = file.getNextToken(token);
}

errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Missing space after key'
});
});
});
}
check: function(file, errors) {
Function (anonymous_1097)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand ||
property.type === 'SpreadProperty') {
return;
}

var token = file.getLastNodeToken(property.key);

if (property.computed === true) {
token = file.getNextToken(token);
}

errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Missing space after key'
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_1098)
✓ Was called
node.properties.forEach(function(property) {···
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand ||
property.type === 'SpreadProperty') {
return;
}

var token = file.getLastNodeToken(property.key);

if (property.computed === true) {
token = file.getNextToken(token);
}

errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Missing space after key'
});
});
node.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

if (property.shorthand ||
if (
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
property.type === 'ObjectMethod' &&
property.type === 'ObjectMethod' &&
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
(property.kind === 'get' || property.kind === 'set')
) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
property.type === 'SpreadProperty') {···
return;
}
✓ Negative was executed (else)
}···

var token = file.getLastNodeToken(property.key);
Branch LogicalExpression
✓ Was returned
property.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand ||
if (property.shorthand ||
property.type === 'SpreadProperty') {
return;
}
var token = file.getLastNodeToken(property.key);
Branch IfStatement
✓ Positive was executed (if)
if (property.computed === true) {···
token = file.getNextToken(token);
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (property.computed === true) {
token = file.getNextToken(token);
}
errors.assert.whitespaceBetween({
token: token,
nextToken: file.getNextToken(token),
message: 'Missing space after key'
});
});
});
}
};
require-space-after-prefix-unary-operators.js
/**
* Disallows sticking unary operators to the right.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to require space after prefix for all unary operators
*
* #### Example
*
* ```js
* "requireSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"]
* ```
*
* ##### Valid
*
* ```js
* x = ! y; y = ++ z;
* ```
*
* ##### Invalid
*
* ```js
* x = !y; y = ++z;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').unaryOperators;
Function (anonymous_1099)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1100)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = defaultOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = defaultOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_1101)
✓ Was called
getOptionName: function() {···
return 'requireSpaceAfterPrefixUnaryOperators';
},
getOptionName: function() {
return 'requireSpaceAfterPrefixUnaryOperators';
},
Function (anonymous_1102)
✓ Was called
check: function(file, errors) {···
var operatorIndex = this._operatorIndex;

file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {
// Check "node.prefix" for prefix type of (inc|dec)rement
if (node.prefix && operatorIndex[node.operator]) {
var argument = node.argument.type;
var operatorToken = node.getFirstToken();
var nextToken = file.getNextToken(operatorToken);

// Do not report consecutive operators (#405)
if (
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
nextToken.value !== '('
) {
return;
}

errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
}
check: function(file, errors) {
var operatorIndex = this._operatorIndex;
Function (anonymous_1103)
✓ Was called
file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {···
// Check "node.prefix" for prefix type of (inc|dec)rement
if (node.prefix && operatorIndex[node.operator]) {
var argument = node.argument.type;
var operatorToken = node.getFirstToken();
var nextToken = file.getNextToken(operatorToken);

// Do not report consecutive operators (#405)
if (
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
nextToken.value !== '('
) {
return;
}

errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {
// Check "node.prefix" for prefix type of (inc|dec)rement
Branch IfStatement
✓ Positive was executed (if)
if (node.prefix && operatorIndex[node.operator]) {···
var argument = node.argument.type;
var operatorToken = node.getFirstToken();
var nextToken = file.getNextToken(operatorToken);

// Do not report consecutive operators (#405)
if (
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
nextToken.value !== '('
) {
return;
}

errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (node.prefix && operatorIndex[node.operator]) {
✗ Was not returned
if (node.prefix && operatorIndex[node.operator]) {
if (node.prefix && operatorIndex[node.operator]) {
var argument = node.argument.type;
var operatorToken = node.getFirstToken();
var nextToken = file.getNextToken(operatorToken);
// Do not report consecutive operators (#405)
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (
Branch LogicalExpression
✓ Was returned
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&···
nextToken.value !== '('
✓ Was returned
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
Branch LogicalExpression
✓ Was returned
nextToken.value !== '('
✓ Was returned
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
nextToken.value !== '('
) {
return;
}
errors.assert.whitespaceBetween({
token: operatorToken,
nextToken: nextToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
}
};
require-space-before-binary-operators.js
/**
* Disallows sticking binary operators to the left.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to require space before all possible binary operators
* without comma operator, since it's rarely used with this rule
*
*
* #### Example
*
* ```js
* "requireSpaceBeforeBinaryOperators": [
* "=",
* ",",
* "+",
* "-",
* "/",
* "*",
* "==",
* "===",
* "!=",
* "!=="
* // etc
* ]
* ```
*
* ##### Valid
*
* ```js
* x !== y;
* ```
*
* ##### Invalid
*
* ```js
* x!== y;
* ```
*/
var assert = require('assert');
var allOperators = require('../../lib/utils').binaryOperators.filter(function(operator) {
return operator !== ',';
});
Function (anonymous_1105)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1106)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = allOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = allOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = allOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_1107)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeBinaryOperators';
},
getOptionName: function() {
return 'requireSpaceBeforeBinaryOperators';
},
Function (anonymous_1108)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;

// Comma
if (operators[',']) {
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: file.getPrevToken(token),
nextToken: token,
message: 'Operator , should not stick to preceding expression'
});
});
}

// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
function(node) {
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var prevToken = file.getPrevToken(operatorToken);

if (operators[operator]) {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + operator + ' should not stick to preceding expression'
});
}
}
);
}
check: function(file, errors) {
var operators = this._operatorIndex;
// Comma
Branch IfStatement
✓ Positive was executed (if)
if (operators[',']) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: file.getPrevToken(token),
nextToken: token,
message: 'Operator , should not stick to preceding expression'
});
});
}
✓ Negative was executed (else)
}···

// For everything else
if (operators[',']) {
Function (anonymous_1109)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
errors.assert.whitespaceBetween({
token: file.getPrevToken(token),
nextToken: token,
message: 'Operator , should not stick to preceding expression'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
errors.assert.whitespaceBetween({
token: file.getPrevToken(token),
nextToken: token,
message: 'Operator , should not stick to preceding expression'
});
});
}
// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'VariableDeclarator', 'LogicalExpression'],
Function (anonymous_1110)
✓ Was called
function(node) {···
var operator;
var expression;

if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}

if (expression === null) {
return;
}

var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);

var prevToken = file.getPrevToken(operatorToken);

if (operators[operator]) {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + operator + ' should not stick to preceding expression'
});
}
}
function(node) {
var operator;
var expression;
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclarator') {···
expression = node.init;
operator = '=';
} else {
✓ Negative was executed (else)
} else {···
operator = node.operator;
expression = node.right;
}
if (node.type === 'VariableDeclarator') {
expression = node.init;
operator = '=';
} else {
operator = node.operator;
expression = node.right;
}
Branch IfStatement
✓ Positive was executed (if)
if (expression === null) {···
return;
}
✓ Negative was executed (else)
}···

var operatorToken = file.findPrevOperatorToken(
if (expression === null) {
return;
}
var operatorToken = file.findPrevOperatorToken(
file.getFirstNodeToken(expression),
operator
);
var prevToken = file.getPrevToken(operatorToken);
Branch IfStatement
✓ Positive was executed (if)
if (operators[operator]) {···
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + operator + ' should not stick to preceding expression'
});
}
✓ Negative was executed (else)
}···
}
if (operators[operator]) {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: operatorToken,
message: 'Operator ' + operator + ' should not stick to preceding expression'
});
}
}
);
}
};
require-space-before-block-statements.js
/**
* Requires space(s) before block statements (for loops, control structures).
*
* Type: `Boolean` or `Integer`
*
* Values:
*
* - `true` require *at least* a single space
* - `Integer` require *at least* specified number of spaces
*
* #### Example
*
* ```js
* "requireSpaceBeforeBlockStatements": 1
* ```
*
* ##### Valid
*
* ```js
* if (cond) {
* foo();
* } else {
* bar();
* }
*
* for (var e in elements) {
* bar(e);
* }
*
* while (cond) {
* foo();
* }
* ```
*
* ##### Invalid
*
* ```js
* if (cond){
* foo();
* } else{
* bar();
* }
*
* for (var e in elements){
* bar(e);
* }
*
* while (cond){
* foo();
* }
* ```
*/
var assert = require('assert');
Function (anonymous_1111)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1112)
✓ Was called
configure: function(requireSpaceBeforeBlockStatements) {···
assert(
typeof requireSpaceBeforeBlockStatements === 'boolean' ||
typeof requireSpaceBeforeBlockStatements === 'number',
this.getOptionName() + ' option requires number or bolean'
);
assert(
requireSpaceBeforeBlockStatements >= 1,
this.getOptionName() +
' option requires true value or a number greater than equal to 1 or should be removed'
);
this._count = +requireSpaceBeforeBlockStatements;
},
configure: function(requireSpaceBeforeBlockStatements) {
assert(
Branch LogicalExpression
✓ Was returned
typeof requireSpaceBeforeBlockStatements === 'number',
✓ Was returned
typeof requireSpaceBeforeBlockStatements === 'boolean' ||
typeof requireSpaceBeforeBlockStatements === 'boolean' ||
typeof requireSpaceBeforeBlockStatements === 'number',
this.getOptionName() + ' option requires number or bolean'
);
assert(
requireSpaceBeforeBlockStatements >= 1,
this.getOptionName() +
' option requires true value or a number greater than equal to 1 or should be removed'
);
this._count = +requireSpaceBeforeBlockStatements;
},
Function (anonymous_1113)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeBlockStatements';
},
getOptionName: function() {
return 'requireSpaceBeforeBlockStatements';
},
Function (anonymous_1114)
✓ Was called
check: function(file, errors) {···
var count = this._count;
file.iterateNodesByType('BlockStatement', function(node) {
var first = node.getFirstToken();

errors.assert.spacesBetween({
token: file.getPrevToken(first),
nextToken: first,
atLeast: count,
disallowNewLine: true,
message: 'One (or more) spaces required before opening brace for block expressions'
});
});
}
check: function(file, errors) {
var count = this._count;
Function (anonymous_1115)
✓ Was called
file.iterateNodesByType('BlockStatement', function(node) {···
var first = node.getFirstToken();

errors.assert.spacesBetween({
token: file.getPrevToken(first),
nextToken: first,
atLeast: count,
disallowNewLine: true,
message: 'One (or more) spaces required before opening brace for block expressions'
});
});
file.iterateNodesByType('BlockStatement', function(node) {
var first = node.getFirstToken();
errors.assert.spacesBetween({
token: file.getPrevToken(first),
nextToken: first,
atLeast: count,
disallowNewLine: true,
message: 'One (or more) spaces required before opening brace for block expressions'
});
});
}
};
require-space-before-comma.js
/**
* Requires space before comma
*
* Types: `Boolean`
*
* Values: `true` to require a space before any comma
*
* #### Example
*
* ```js
* "requireSpaceBeforeComma": true
* ```
*
* ##### Valid
*
* ```js
* var a ,b;
* ```
*
* ##### Invalid
*
* ```js
* var a,b;
* ```
*/
var assert = require('assert');
Function (anonymous_1116)
✓ Was called
module.exports = function() {···
};
module.exports = function() {
};
module.exports.prototype = {
Function (anonymous_1117)
✓ Was called
configure: function(option) {···
assert(
option === true,
this.getOptionName() + ' option requires true value'
);
},
configure: function(option) {
assert(
option === true,
this.getOptionName() + ' option requires true value'
);
},
Function (anonymous_1118)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeComma';
},
getOptionName: function() {
return 'requireSpaceBeforeComma';
},
Function (anonymous_1119)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Space required before comma'
});
});
}
check: function(file, errors) {
Function (anonymous_1120)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {···
var prevToken = token.getPreviousCodeToken();

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Space required before comma'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Space required before comma'
});
});
}
};
require-space-before-destructured-values.js
/**
* Require space after colon in object destructuring.
*
* Type: `Boolean`
*
* Value: `true`
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireSpaceBeforeDestructuredValues": true
* ```
*
* ##### Valid
* ```js
* const { foo: objectsFoo } = SomeObject;
* ```
* ##### Invalid
* ```js
* const { foo:objectsFoo } = SomeObject;
* ```
*
* ##### Valid
* ```js
* const { [ { foo: objectsFoo } ] } = SomeObject;
* ```
* ##### Invalid
* ```js
* const { [ { foo:objectsFoo } ] } = SomeObject;
* ```
*/
var assert = require('assert');
Function (anonymous_1121)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1122)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1123)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeDestructuredValues';
},
getOptionName: function() {
return 'requireSpaceBeforeDestructuredValues';
},
Function (anonymous_1124)
✓ Was called
check: function(file, errors) {···
var checkSpaceMissing = function(propKey) {
var keyToken = file.getFirstNodeToken(propKey);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
};

var letsCheckThisOne = function(item) {

if (!item) {
return;
}

if (item.type === 'ObjectPattern') {
item.properties.forEach(function(property) {

if (property.shorthand || property.method) {
return;
}

checkSpaceMissing(property.key);

//Strategy for nested structures
var propValue = property.value;

if (!propValue) {
return;
}

letsCheckThisOne(propValue);
});
}

if (item.type === 'ArrayPattern') {
item.elements.forEach(letsCheckThisOne);
}
};

file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {

if (node.type === 'VariableDeclaration') {
node.declarations.forEach(function(declaration) {
letsCheckThisOne(declaration.id || {});
});
}

if (node.type === 'AssignmentExpression') {
var left = node.left;

if (left) {
letsCheckThisOne(left);
}
}
});
}
check: function(file, errors) {
Function (anonymous_1125)
✓ Was called
var checkSpaceMissing = function(propKey) {···
var keyToken = file.getFirstNodeToken(propKey);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
};
var checkSpaceMissing = function(propKey) {
var keyToken = file.getFirstNodeToken(propKey);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');
errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
};
Function (anonymous_1126)
✓ Was called
var letsCheckThisOne = function(item) {···

if (!item) {
return;
}

if (item.type === 'ObjectPattern') {
item.properties.forEach(function(property) {

if (property.shorthand || property.method) {
return;
}

checkSpaceMissing(property.key);

//Strategy for nested structures
var propValue = property.value;

if (!propValue) {
return;
}

letsCheckThisOne(propValue);
});
}

if (item.type === 'ArrayPattern') {
item.elements.forEach(letsCheckThisOne);
}
};
var letsCheckThisOne = function(item) {
Branch IfStatement
✗ Positive was not executed (if)
if (!item) {···
return;
}
✓ Negative was executed (else)
}···

if (item.type === 'ObjectPattern') {
if (!item) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (item.type === 'ObjectPattern') {···
item.properties.forEach(function(property) {

if (property.shorthand || property.method) {
return;
}

checkSpaceMissing(property.key);

//Strategy for nested structures
var propValue = property.value;

if (!propValue) {
return;
}

letsCheckThisOne(propValue);
});
}
✓ Negative was executed (else)
}···

if (item.type === 'ArrayPattern') {
if (item.type === 'ObjectPattern') {
Function (anonymous_1127)
✓ Was called
item.properties.forEach(function(property) {···

if (property.shorthand || property.method) {
return;
}

checkSpaceMissing(property.key);

//Strategy for nested structures
var propValue = property.value;

if (!propValue) {
return;
}

letsCheckThisOne(propValue);
});
item.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
if (property.shorthand || property.method) {···
return;
}
✓ Negative was executed (else)
}···

checkSpaceMissing(property.key);
Branch LogicalExpression
✓ Was returned
if (property.shorthand || property.method) {
✓ Was returned
if (property.shorthand || property.method) {
if (property.shorthand || property.method) {
return;
}
checkSpaceMissing(property.key);
//Strategy for nested structures
var propValue = property.value;
Branch IfStatement
✗ Positive was not executed (if)
if (!propValue) {···
return;
}
✓ Negative was executed (else)
}···

letsCheckThisOne(propValue);
if (!propValue) {
return;
}
letsCheckThisOne(propValue);
});
}
Branch IfStatement
✓ Positive was executed (if)
if (item.type === 'ArrayPattern') {···
item.elements.forEach(letsCheckThisOne);
}
✓ Negative was executed (else)
}···
};
if (item.type === 'ArrayPattern') {
item.elements.forEach(letsCheckThisOne);
}
};
Function (anonymous_1128)
✓ Was called
file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {···

if (node.type === 'VariableDeclaration') {
node.declarations.forEach(function(declaration) {
letsCheckThisOne(declaration.id || {});
});
}

if (node.type === 'AssignmentExpression') {
var left = node.left;

if (left) {
letsCheckThisOne(left);
}
}
});
file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'VariableDeclaration') {···
node.declarations.forEach(function(declaration) {
letsCheckThisOne(declaration.id || {});
});
}
✓ Negative was executed (else)
}···

if (node.type === 'AssignmentExpression') {
if (node.type === 'VariableDeclaration') {
Function (anonymous_1129)
✓ Was called
node.declarations.forEach(function(declaration) {···
letsCheckThisOne(declaration.id || {});
});
node.declarations.forEach(function(declaration) {
Branch LogicalExpression
✗ Was not returned
letsCheckThisOne(declaration.id || {});
✓ Was returned
letsCheckThisOne(declaration.id || {});
letsCheckThisOne(declaration.id || {});
});
}
Branch IfStatement
✓ Positive was executed (if)
if (node.type === 'AssignmentExpression') {···
var left = node.left;

if (left) {
letsCheckThisOne(left);
}
}
✓ Negative was executed (else)
}···
});
if (node.type === 'AssignmentExpression') {
var left = node.left;
Branch IfStatement
✓ Positive was executed (if)
if (left) {···
letsCheckThisOne(left);
}
✗ Negative was not executed (else)
}···
}
if (left) {
letsCheckThisOne(left);
}
}
});
}
};
require-space-before-keywords.js
/**
* Requires space before keyword.
*
* Types: `Array`, `Boolean` or `Object`
*
* Values: `true` to require all possible keywords to have a preceding space (except `function`),
* Array of quoted keywords
* or an Object with the `allExcept` property set with an Array of quoted keywords.
*
* #### Example
*
* ```js
* "requireSpaceBeforeKeywords": [
* "else",
* "while",
* "catch"
* ]
* ```
*
* ##### Valid
*
* ```js
* } else {
* x++;
* }
* ```
*
* ##### Invalid
*
* ```js
* }else {
* x++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
var ignoredKeywords = ['function'];
Function (anonymous_1130)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1131)
✓ Was called
configure: function(keywords) {···
var isValidObject = (keywords === Object(keywords) && keywords.hasOwnProperty('allExcept'));

assert(
Array.isArray(keywords) || keywords === true || isValidObject,
this.getOptionName() + ' option requires array, object with "allExcept" property or true value');

var excludedKeywords = ignoredKeywords;
if (isValidObject) {
excludedKeywords = keywords.allExcept;
}

if (!Array.isArray(keywords)) {
keywords = defaultKeywords.filter(function(keyword) {
return (excludedKeywords.indexOf(keyword) === -1);
});
}

this._keywords = keywords;
},
configure: function(keywords) {
Branch LogicalExpression
✓ Was returned
var isValidObject = (keywords === Object(keywords) && keywords.hasOwnProperty('allExcept'));
✓ Was returned
var isValidObject = (keywords === Object(keywords) && keywords.hasOwnProperty('allExcept'));
var isValidObject = (keywords === Object(keywords) && keywords.hasOwnProperty('allExcept'));
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || keywords === true || isValidObject,
✓ Was returned
Array.isArray(keywords) || keywords === true || isValidObject,
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || keywords === true || isValidObject,
✓ Was returned
Array.isArray(keywords) || keywords === true || isValidObject,
Array.isArray(keywords) || keywords === true || isValidObject,
this.getOptionName() + ' option requires array, object with "allExcept" property or true value');
var excludedKeywords = ignoredKeywords;
Branch IfStatement
✓ Positive was executed (if)
if (isValidObject) {···
excludedKeywords = keywords.allExcept;
}
✓ Negative was executed (else)
}···

if (!Array.isArray(keywords)) {
if (isValidObject) {
excludedKeywords = keywords.allExcept;
}
Branch IfStatement
✓ Positive was executed (if)
if (!Array.isArray(keywords)) {···
keywords = defaultKeywords.filter(function(keyword) {
return (excludedKeywords.indexOf(keyword) === -1);
});
}
✓ Negative was executed (else)
}···

this._keywords = keywords;
if (!Array.isArray(keywords)) {
Function (anonymous_1132)
✓ Was called
keywords = defaultKeywords.filter(function(keyword) {···
return (excludedKeywords.indexOf(keyword) === -1);
});
keywords = defaultKeywords.filter(function(keyword) {
return (excludedKeywords.indexOf(keyword) === -1);
});
}
this._keywords = keywords;
},
Function (anonymous_1133)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeKeywords';
},
getOptionName: function() {
return 'requireSpaceBeforeKeywords';
},
Function (anonymous_1134)
✓ Was called
check: function(file, errors) {···
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
if (!prevToken || prevToken.isComment) {
return;
}

if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before "' + token.value + '" keyword'
});
}
});
}
check: function(file, errors) {
Function (anonymous_1135)
✓ Was called
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
if (!prevToken || prevToken.isComment) {
return;
}

if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before "' + token.value + '" keyword'
});
}
});
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
Branch IfStatement
✓ Positive was executed (if)
if (!prevToken || prevToken.isComment) {···
return;
}
✓ Negative was executed (else)
}···

if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
Branch LogicalExpression
✓ Was returned
if (!prevToken || prevToken.isComment) {
✓ Was returned
if (!prevToken || prevToken.isComment) {
if (!prevToken || prevToken.isComment) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {···
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before "' + token.value + '" keyword'
});
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
✗ Was not returned
if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
if (prevToken.type !== 'Punctuator' || prevToken.value !== ';') {
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before "' + token.value + '" keyword'
});
}
});
}
};
require-space-before-object-values.js
/**
* Requires space after object keys.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSpaceBeforeObjectValues": true
* ```
*
* ##### Valid
* ```js
* var x = {a: 1};
* ```
* ##### Invalid
* ```js
* var x = {a:1};
* ```
*/
var assert = require('assert');
Function (anonymous_1136)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1137)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1138)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforeObjectValues';
},
getOptionName: function() {
return 'requireSpaceBeforeObjectValues';
},
Function (anonymous_1139)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);

var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
});
});
}
check: function(file, errors) {
Function (anonymous_1140)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
node.properties.forEach(function(property) {
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);

var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
});
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_1141)
✓ Was called
node.properties.forEach(function(property) {···
if (
property.type === 'ObjectMethod' &&
(property.kind === 'get' || property.kind === 'set')
) {
return;
}

if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return;
}

var keyToken = file.getFirstNodeToken(property.key);

var colon = file.findNextToken(keyToken, 'Punctuator', ':');

errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
});
node.properties.forEach(function(property) {
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

if (property.shorthand || property.method ||
if (
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
property.type === 'ObjectMethod' &&
property.type === 'ObjectMethod' &&
Branch LogicalExpression
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
✓ Was returned
(property.kind === 'get' || property.kind === 'set')
(property.kind === 'get' || property.kind === 'set')
) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
property.type === 'SpreadProperty') {···
return;
}
✓ Negative was executed (else)
}···

var keyToken = file.getFirstNodeToken(property.key);
Branch LogicalExpression
✓ Was returned
property.type === 'SpreadProperty') {
✓ Was returned
if (property.shorthand || property.method ||
Branch LogicalExpression
✓ Was returned
if (property.shorthand || property.method ||
✓ Was returned
if (property.shorthand || property.method ||
if (property.shorthand || property.method ||
property.type === 'SpreadProperty') {
return;
}
var keyToken = file.getFirstNodeToken(property.key);
var colon = file.findNextToken(keyToken, 'Punctuator', ':');
errors.assert.whitespaceBetween({
token: colon,
nextToken: file.getNextToken(colon),
message: 'Missing space after key colon'
});
});
});
}
};
require-space-before-postfix-unary-operators.js
/**
* Disallows sticking unary operators to the left.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted operators or `true` to require space before postfix for all unary operators
* (i.e. increment/decrement operators).
*
* #### Example
*
* ```js
* "requireSpaceBeforePostfixUnaryOperators": ["++", "--"]
* ```
*
* ##### Valid
*
* ```js
* x = y ++; y = z --;
* ```
*
* ##### Invalid
*
* ```js
* x = y++; y = z--;
* ```
*/
var assert = require('assert');
var defaultOperators = require('../utils').incrementAndDecrementOperators;
Function (anonymous_1142)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1143)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = defaultOperators;
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = defaultOperators;
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = defaultOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_1144)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBeforePostfixUnaryOperators';
},
getOptionName: function() {
return 'requireSpaceBeforePostfixUnaryOperators';
},
Function (anonymous_1145)
✓ Was called
check: function(file, errors) {···
var operatorIndex = this._operatorIndex;

// 'UpdateExpression' involve only ++ and -- operators
file.iterateNodesByType('UpdateExpression', function(node) {
// "!node.prefix" means postfix type of (inc|dec)rement
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);

errors.assert.whitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
}
check: function(file, errors) {
var operatorIndex = this._operatorIndex;
// 'UpdateExpression' involve only ++ and -- operators
Function (anonymous_1146)
✓ Was called
file.iterateNodesByType('UpdateExpression', function(node) {···
// "!node.prefix" means postfix type of (inc|dec)rement
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);

errors.assert.whitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
file.iterateNodesByType('UpdateExpression', function(node) {
// "!node.prefix" means postfix type of (inc|dec)rement
Branch IfStatement
✓ Positive was executed (if)
if (!node.prefix && operatorIndex[node.operator]) {···
var operatorToken = file.getLastNodeToken(node);

errors.assert.whitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
✗ Negative was not executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (!node.prefix && operatorIndex[node.operator]) {
✗ Was not returned
if (!node.prefix && operatorIndex[node.operator]) {
if (!node.prefix && operatorIndex[node.operator]) {
var operatorToken = file.getLastNodeToken(node);
errors.assert.whitespaceBetween({
token: file.getPrevToken(operatorToken),
nextToken: operatorToken,
message: 'Operator ' + node.operator + ' should not stick to operand'
});
}
});
}
};
require-space-between-arguments.js
/**
* Ensure there are spaces after argument separators in call expressions.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSpaceBetweenArguments": true
* ```
*
* ##### Valid
*
* ```js
* a(b, c);
* ```
*
* ##### Invalid
*
* ```js
* a(b,c);
* ```
*/
var assert = require('assert');
Function (anonymous_1147)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1148)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1149)
✓ Was called
getOptionName: function() {···
return 'requireSpaceBetweenArguments';
},
getOptionName: function() {
return 'requireSpaceBetweenArguments';
},
Function (anonymous_1150)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['CallExpression'], function(node) {
node.arguments.forEach(function(param) {
var punctuatorToken = file.getPrevToken(file.getFirstNodeToken(param));
if (punctuatorToken.value === ',') {
errors.assert.whitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken)
});
}
});
});
}
check: function(file, errors) {
Function (anonymous_1151)
✓ Was called
file.iterateNodesByType(['CallExpression'], function(node) {···
node.arguments.forEach(function(param) {
var punctuatorToken = file.getPrevToken(file.getFirstNodeToken(param));
if (punctuatorToken.value === ',') {
errors.assert.whitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken)
});
}
});
});
file.iterateNodesByType(['CallExpression'], function(node) {
Function (anonymous_1152)
✓ Was called
node.arguments.forEach(function(param) {···
var punctuatorToken = file.getPrevToken(file.getFirstNodeToken(param));
if (punctuatorToken.value === ',') {
errors.assert.whitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken)
});
}
});
node.arguments.forEach(function(param) {
var punctuatorToken = file.getPrevToken(file.getFirstNodeToken(param));
Branch IfStatement
✓ Positive was executed (if)
if (punctuatorToken.value === ',') {···
errors.assert.whitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken)
});
}
✓ Negative was executed (else)
}···
});
if (punctuatorToken.value === ',') {
errors.assert.whitespaceBetween({
token: punctuatorToken,
nextToken: file.getNextToken(punctuatorToken)
});
}
});
});
}
};
require-spaces-in-anonymous-function-expression.js
/**
* Requires space before `()` or `{}` in anonymous function expressions.
*
* Type: `Object`
*
* Values:
* - `Object` with the following properties. One of `"beforeOpeningRoundBrace"`
* and `"beforeOpeningCurlyBrace"` must be provided:
* - `"beforeOpeningRoundBrace"` validates that there is a space before
* the opening round brace `()`. If provided, it must be set to `true`.
* - `"beforeOpeningCurlyBrace"` validates that there is a space before
* the opening curly brace `{}`. If provided, it must be set to `true`.
* - `"allExcept"` may be an Array containing `"shorthand"`, or
* the Boolean `true` to enable all configuration exceptions. If
* `"shorthand"` is provided, spaces will not be required for
* ES6 method definitions.
*
* #### Example
*
* ```js
* "requireSpacesInAnonymousFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var foo = function () {};
* var Foo = {
* foo: function () {}
* }
* array.map(function () {});
* ```
*
* ##### Invalid
*
* ```js
* var foo = function() {};
* var Foo = {
* foo: function (){}
* }
* array.map(function(){});
* ```
*/
var assert = require('assert');
Function (anonymous_1153)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1154)
✓ Was called
configure: function(options) {···
this._exceptions = {
'shorthand': false
};

assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

if ('allExcept' in options) {
if (typeof options.allExcept === 'object') {
assert(
Array.isArray(options.allExcept),
this.getOptionName() + ' option requires "allExcept" to be ' +
'an array'
);
assert(
options.allExcept.length > 0,
this.getOptionName() + ' option requires "allExcept" to have ' +
'at least one item or be set to `true`'
);
options.allExcept.forEach(function(except) {
if (except === 'shorthand') {
this._exceptions.shorthand = true;
} else {
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
}, this);
} else {
assert(
options.allExcept === true,
this.getOptionName() + ' option requires a true value or array'
);
this._exceptions.shorthand = true;
}
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
' or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
this._exceptions = {
'shorthand': false
};
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('allExcept' in options) {
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('allExcept' in options) {···
if (typeof options.allExcept === 'object') {
assert(
Array.isArray(options.allExcept),
this.getOptionName() + ' option requires "allExcept" to be ' +
'an array'
);
assert(
options.allExcept.length > 0,
this.getOptionName() + ' option requires "allExcept" to have ' +
'at least one item or be set to `true`'
);
options.allExcept.forEach(function(except) {
if (except === 'shorthand') {
this._exceptions.shorthand = true;
} else {
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
}, this);
} else {
assert(
options.allExcept === true,
this.getOptionName() + ' option requires a true value or array'
);
this._exceptions.shorthand = true;
}
}
✓ Negative was executed (else)
}···

assert(
if ('allExcept' in options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options.allExcept === 'object') {···
assert(
Array.isArray(options.allExcept),
this.getOptionName() + ' option requires "allExcept" to be ' +
'an array'
);
assert(
options.allExcept.length > 0,
this.getOptionName() + ' option requires "allExcept" to have ' +
'at least one item or be set to `true`'
);
options.allExcept.forEach(function(except) {
if (except === 'shorthand') {
this._exceptions.shorthand = true;
} else {
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
}, this);
} else {
✓ Negative was executed (else)
} else {···
assert(
options.allExcept === true,
this.getOptionName() + ' option requires a true value or array'
);
this._exceptions.shorthand = true;
}
if (typeof options.allExcept === 'object') {
assert(
Array.isArray(options.allExcept),
this.getOptionName() + ' option requires "allExcept" to be ' +
'an array'
);
assert(
options.allExcept.length > 0,
this.getOptionName() + ' option requires "allExcept" to have ' +
'at least one item or be set to `true`'
);
Function (anonymous_1155)
✓ Was called
options.allExcept.forEach(function(except) {···
if (except === 'shorthand') {
this._exceptions.shorthand = true;
} else {
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
}, this);
options.allExcept.forEach(function(except) {
Branch IfStatement
✗ Positive was not executed (if)
if (except === 'shorthand') {···
this._exceptions.shorthand = true;
} else {
✓ Negative was executed (else)
} else {···
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
if (except === 'shorthand') {
this._exceptions.shorthand = true;
} else {
assert(false, this.getOptionName() + ' option requires ' +
'"allExcept" to be an array containing "shorthand"');
}
}, this);
} else {
assert(
options.allExcept === true,
this.getOptionName() + ' option requires a true value or array'
);
this._exceptions.shorthand = true;
}
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
' or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_1156)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInAnonymousFunctionExpression';
},
getOptionName: function() {
return 'requireSpacesInAnonymousFunctionExpression';
},
Function (anonymous_1157)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
var exceptions = this._exceptions;

file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
if (exceptions.shorthand) {
return;
}
}

// anonymous function expressions only
if (node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
var exceptions = this._exceptions;
Function (anonymous_1158)
✓ Was called
file.iterateNodesByType(['FunctionExpression'], function(node) {···
var functionNode = node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
if (exceptions.shorthand) {
return;
}
}

// anonymous function expressions only
if (node.id) {
return;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
if (exceptions.shorthand) {
return;
}
}
✓ Negative was executed (else)
}···

// anonymous function expressions only
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
Branch IfStatement
✗ Positive was not executed (if)
if (exceptions.shorthand) {···
return;
}
✗ Negative was not executed (else)
}···
}
if (exceptions.shorthand) {
return;
}
}
// anonymous function expressions only
Branch IfStatement
✓ Positive was executed (if)
if (node.id) {···
return;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
if (node.id) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✓ Positive was executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
};
require-spaces-in-call-expression.js
/**
* Requires space before `()` in call expressions.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSpacesInCallExpression": true
* ```
*
* ##### Valid
*
* ```js
* var x = foobar ();
* ```
*
* ##### Invalid
*
* ```js
* var x = foobar();
* ```
*/
var assert = require('assert');
Function (anonymous_1159)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1160)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1161)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInCallExpression';
},
getOptionName: function() {
return 'requireSpacesInCallExpression';
},
Function (anonymous_1162)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('CallExpression', function(node) {
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');

errors.assert.whitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Missing space before opening round brace'
});
});
}
check: function(file, errors) {
Function (anonymous_1163)
✓ Was called
file.iterateNodesByType('CallExpression', function(node) {···
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');

errors.assert.whitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Missing space before opening round brace'
});
});
file.iterateNodesByType('CallExpression', function(node) {
var lastCalleeToken = file.getLastNodeToken(node.callee);
var roundBraceToken = file.findNextToken(lastCalleeToken, 'Punctuator', '(');
errors.assert.whitespaceBetween({
token: file.getPrevToken(roundBraceToken),
nextToken: roundBraceToken,
message: 'Missing space before opening round brace'
});
});
}
};
require-spaces-in-conditional-expression.js
/**
* Requires space before and/or after `?` or `:` in conditional expressions.
*
* Types: `Object` or `Boolean`
*
* Values: `"afterTest"`, `"beforeConsequent"`, `"afterConsequent"`, `"beforeAlternate"` as child properties,
* or `true` to set all properties to `true`. Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "requireSpacesInConditionalExpression": {
* "afterTest": true,
* "beforeConsequent": true,
* "afterConsequent": true,
* "beforeAlternate": true
* }
* ```
*
* ##### Valid
*
* ```js
* var a = b ? c : d;
* var a= b ? c : d;
* ```
*
* ##### Invalid
*
* ```js
* var a = b? c : d;
* var a = b ?c : d;
* var a = b ? c: d;
* var a = b ? c :d;
* ```
*/
var assert = require('assert');
Function (anonymous_1164)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1165)
✓ Was called
configure: function(options) {···
var validProperties = [
'afterTest',
'beforeConsequent',
'afterConsequent',
'beforeAlternate'
];
var optionName = this.getOptionName();

if (options === true) {
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}

assert(
typeof options === 'object',
optionName + ' option requires a true value or an object'
);

var isProperlyConfigured = validProperties.some(function(key) {
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}

return isPresent;
});

assert(
isProperlyConfigured,
optionName + ' must have at least 1 of the following properties: ' + validProperties.join(', ')
);

validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
},
configure: function(options) {
var validProperties = [
'afterTest',
'beforeConsequent',
'afterConsequent',
'beforeAlternate'
];
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (options === true) {···
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}
✓ Negative was executed (else)
}···

assert(
if (options === true) {
options = {
'afterTest': true,
'beforeConsequent': true,
'afterConsequent': true,
'beforeAlternate': true
};
}
assert(
typeof options === 'object',
optionName + ' option requires a true value or an object'
);
Function (anonymous_1166)
✓ Was called
var isProperlyConfigured = validProperties.some(function(key) {···
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}

return isPresent;
});
var isProperlyConfigured = validProperties.some(function(key) {
var isPresent = key in options;
Branch IfStatement
✓ Positive was executed (if)
if (isPresent) {···
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

return isPresent;
if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
return isPresent;
});
assert(
isProperlyConfigured,
optionName + ' must have at least 1 of the following properties: ' + validProperties.join(', ')
);
Function (anonymous_1167)
✓ Was called
validProperties.forEach(function(property) {···
this['_' + property] = Boolean(options[property]);
}.bind(this));
validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
},
Function (anonymous_1168)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInConditionalExpression';
},
getOptionName: function() {
return 'requireSpacesInConditionalExpression';
},
Function (anonymous_1169)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ConditionalExpression'], function(node) {
var consequent = node.consequent;
var alternate = node.alternate;
var consequentToken = file.getFirstNodeToken(consequent);
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;

if (this._afterTest) {
token = file.getPrevToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Missing space after test'
});
}

if (this._beforeConsequent) {
token = file.getNextToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Missing space before consequent'
});
}

if (this._afterConsequent) {
token = file.getPrevToken(colonToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Missing space after consequent'
});
}

if (this._beforeAlternate) {
token = file.getNextToken(colonToken);
errors.assert.whitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Missing space before alternate'
});
}
}.bind(this));
}
check: function(file, errors) {
Function (anonymous_1170)
✓ Was called
file.iterateNodesByType(['ConditionalExpression'], function(node) {···
var consequent = node.consequent;
var alternate = node.alternate;
var consequentToken = file.getFirstNodeToken(consequent);
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;

if (this._afterTest) {
token = file.getPrevToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Missing space after test'
});
}

if (this._beforeConsequent) {
token = file.getNextToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Missing space before consequent'
});
}

if (this._afterConsequent) {
token = file.getPrevToken(colonToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Missing space after consequent'
});
}

if (this._beforeAlternate) {
token = file.getNextToken(colonToken);
errors.assert.whitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Missing space before alternate'
});
}
}.bind(this));
file.iterateNodesByType(['ConditionalExpression'], function(node) {
var consequent = node.consequent;
var alternate = node.alternate;
var consequentToken = file.getFirstNodeToken(consequent);
var alternateToken = file.getFirstNodeToken(alternate);
var questionMarkToken = file.findPrevOperatorToken(consequentToken, '?');
var colonToken = file.findPrevOperatorToken(alternateToken, ':');
var token;
Branch IfStatement
✓ Positive was executed (if)
if (this._afterTest) {···
token = file.getPrevToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Missing space after test'
});
}
✓ Negative was executed (else)
}···

if (this._beforeConsequent) {
if (this._afterTest) {
token = file.getPrevToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: questionMarkToken,
message: 'Missing space after test'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._beforeConsequent) {···
token = file.getNextToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Missing space before consequent'
});
}
✓ Negative was executed (else)
}···

if (this._afterConsequent) {
if (this._beforeConsequent) {
token = file.getNextToken(questionMarkToken);
errors.assert.whitespaceBetween({
token: questionMarkToken,
nextToken: token,
message: 'Missing space before consequent'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._afterConsequent) {···
token = file.getPrevToken(colonToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Missing space after consequent'
});
}
✓ Negative was executed (else)
}···

if (this._beforeAlternate) {
if (this._afterConsequent) {
token = file.getPrevToken(colonToken);
errors.assert.whitespaceBetween({
token: token,
nextToken: colonToken,
message: 'Missing space after consequent'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (this._beforeAlternate) {···
token = file.getNextToken(colonToken);
errors.assert.whitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Missing space before alternate'
});
}
✓ Negative was executed (else)
}···
}.bind(this));
if (this._beforeAlternate) {
token = file.getNextToken(colonToken);
errors.assert.whitespaceBetween({
token: colonToken,
nextToken: token,
message: 'Missing space before alternate'
});
}
}.bind(this));
}
};
require-spaces-in-for-statement.js
/**
* Requires spaces inbetween for statement.
*
* Type: `Boolean`
*
* Value: `true` to requires spaces inbetween for statement.
*
* #### Example
*
* ```js
* "requireSpacesInForStatement": true
* ```
*
* ##### Valid
*
* ```js
* for(var i = 0; i<l; i++) {
* x++;
* }
* ```
*
* ##### Invalid
*
* ```js
* for(var i = 0;i<l;i++) {
* x++;
* }
* ```
*
* ```js
* for(var i = 0; i<l;i++) {
* x++;
* }
* ```
*
* ```js
* for(var i = 0;i<l; i++) {
* x++;
* }
* ```
*/
var assert = require('assert');
var TokenCategorizer = require('../token-categorizer');
Function (anonymous_1171)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1172)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1173)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInForStatement';
},
getOptionName: function() {
return 'requireSpacesInForStatement';
},
Function (anonymous_1174)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('ForStatement', function(node) {
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
var prevToken = file.getPrevToken(testToken);

if (prevToken.value === '(' &&
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {
testToken = prevToken;
prevToken = file.getPrevToken(prevToken);
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: testToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.spacesBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
});
}
check: function(file, errors) {
Function (anonymous_1175)
✓ Was called
file.iterateNodesByType('ForStatement', function(node) {···
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
var prevToken = file.getPrevToken(testToken);

if (prevToken.value === '(' &&
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {
testToken = prevToken;
prevToken = file.getPrevToken(prevToken);
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: testToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.spacesBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
});
file.iterateNodesByType('ForStatement', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.test) {···
var testToken = file.getFirstNodeToken(node.test);
var prevToken = file.getPrevToken(testToken);

if (prevToken.value === '(' &&
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {
testToken = prevToken;
prevToken = file.getPrevToken(prevToken);
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: testToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
✓ Negative was executed (else)
}···
if (node.update) {
if (node.test) {
var testToken = file.getFirstNodeToken(node.test);
var prevToken = file.getPrevToken(testToken);
Branch IfStatement
✓ Positive was executed (if)
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {···
testToken = prevToken;
prevToken = file.getPrevToken(prevToken);
}
✓ Negative was executed (else)
}···
errors.assert.spacesBetween({
Branch LogicalExpression
✓ Was returned
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {
✓ Was returned
if (prevToken.value === '(' &&
if (prevToken.value === '(' &&
TokenCategorizer.categorizeOpenParen(prevToken) === 'ParenthesizedExpression') {
testToken = prevToken;
prevToken = file.getPrevToken(prevToken);
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: testToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (node.update) {···
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.spacesBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
✓ Negative was executed (else)
}···
});
if (node.update) {
var updateToken = file.getFirstNodeToken(node.update);
errors.assert.spacesBetween({
token: file.getPrevToken(updateToken),
nextToken: updateToken,
exactly: 1,
message: 'One space required after semicolon'
});
}
});
}
};
require-spaces-in-function-declaration.js
/**
* Requires space before `()` or `{}` in function declarations.
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "requireSpacesInFunctionDeclaration": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* function a () {}
* ```
*
* ##### Invalid
*
* ```js
* function a() {}
* function a (){}
* function a(){}
* ```
*/
var assert = require('assert');
Function (anonymous_1176)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1177)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_1178)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInFunctionDeclaration';
},
getOptionName: function() {
return 'requireSpacesInFunctionDeclaration';
},
Function (anonymous_1179)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionDeclaration'], function(node) {
// Exception for `export default function` #1376
if (!node.id) {
return;
}

if (beforeOpeningRoundBrace) {
// for a named function, use node.id
var functionToken = file.getFirstNodeToken(node.id || node);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_1180)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration'], function(node) {···
// Exception for `export default function` #1376
if (!node.id) {
return;
}

if (beforeOpeningRoundBrace) {
// for a named function, use node.id
var functionToken = file.getFirstNodeToken(node.id || node);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionDeclaration'], function(node) {
// Exception for `export default function` #1376
Branch IfStatement
✓ Positive was executed (if)
if (!node.id) {···
return;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
if (!node.id) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
// for a named function, use node.id
var functionToken = file.getFirstNodeToken(node.id || node);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
// for a named function, use node.id
Branch LogicalExpression
✗ Was not returned
var functionToken = file.getFirstNodeToken(node.id || node);
✓ Was returned
var functionToken = file.getFirstNodeToken(node.id || node);
var functionToken = file.getFirstNodeToken(node.id || node);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
};
require-spaces-in-function-expression.js
/**
* Requires space before `()` or `{}` in function expressions (both [named](#requirespacesinnamedfunctionexpression)
* and [anonymous](#requirespacesinanonymousfunctionexpression)).
*
* Type: `Object`
*
* Values: `"beforeOpeningRoundBrace"` and `"beforeOpeningCurlyBrace"` as child properties.
* Child properties must be set to `true`.
*
* #### Example
*
* ```js
* "requireSpacesInFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid
*
* ```js
* var x = function () {};
* var x = function a () {};
* var x = async function () {};
* var x = async function a () {};
* ```
*
* ##### Invalid
*
* ```js
* var x = function() {};
* var x = function (){};
* var x = function(){};
* var x = function a() {};
* var x = function a (){};
* var x = function a(){};
* var x = function async a() {};
* var x = function async a (){};
* var x = function async a(){};
* ```
*/
var assert = require('assert');
Function (anonymous_1181)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1182)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_1183)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInFunctionExpression';
},
getOptionName: function() {
return 'requireSpacesInFunctionExpression';
},
Function (anonymous_1184)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType('FunctionExpression', function(node) {
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_1185)
✓ Was called
file.iterateNodesByType('FunctionExpression', function(node) {···
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
file.iterateNodesByType('FunctionExpression', function(node) {
// for a named function, use node.id
Branch LogicalExpression
✓ Was returned
var functionNode = node.id || node;
✓ Was returned
var functionNode = node.id || node;
var functionNode = node.id || node;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✓ Positive was executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✓ Positive was executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
};
require-spaces-in-function.js
/**
* Requires space before `()` or `{}` in function expressions (both [named](#requirespacesinnamedfunctionexpression)
* and [anonymous](#requirespacesinanonymousfunctionexpression)) and function declarations.
*
* Types: `Object`
*
* - `Object` (at least one of properties must be present and it must be set to true):
* - `'beforeOpeningRoundBrace'`
* - `true` validates that there is a space before `()`
* - `'beforeOpeningCurlyBrace'`
* - `true` validates that there is a space before `{}`
*
* #### Example
*
* ```js
* "requireSpacesInFunction": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
* ```js
* "requireSpacesInFunction": {
* "beforeOpeningRoundBrace": true
* }
* ```
* ```js
* "requireSpacesInFunction": {
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid for mode `{ "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function () {};
* var x = function a () {};
* function a () {}
* var x = async function () {};
* var x = async function a () {};
* async function a () {}
* ```
*
* ##### Valid for mode `{ "beforeOpeningRoundBrace": true }`
*
* ```js
* var x = function (){};
* var x = function a (){};
* function a (){}
* var x = async function (){};
* var x = async function a (){};
* async function a (){}
* ```
*
* ##### Valid for mode `{ "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function() {};
* var x = function a() {};
* function a() {}
* var x = async function() {};
* var x = async function a() {};
* async function a() {}
* ```
*
* ##### Invalid for mode `{ "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function() {};
* var x = function (){};
* var x = function(){};
* var x = function a() {};
* var x = function a (){};
* var x = function a(){};
* function a() {}
* function a (){}
* function a(){}
* var x = async function() {};
* var x = async function (){};
* var x = async function(){};
* var x = async function a() {};
* var x = async function a (){};
* var x = async function a(){};
* async function a() {}
* async function a (){}
* async function a(){}
* ```
*/
var assert = require('assert');
Function (anonymous_1186)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1187)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_1188)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInFunction';
},
getOptionName: function() {
return 'requireSpacesInFunction';
},
Function (anonymous_1189)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_1190)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···
// for a named function, use node.id
var functionNode = node.id || node;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
// for a named function, use node.id
Branch LogicalExpression
✓ Was returned
var functionNode = node.id || node;
✓ Was returned
var functionNode = node.id || node;
var functionNode = node.id || node;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
}
✓ Negative was executed (else)
}···

if (beforeOpeningRoundBrace) {
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✓ Positive was executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
// if generator, set token to be * instead
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
// if generator, set token to be * instead
Branch IfStatement
✗ Positive was not executed (if)
if (node.generator && functionToken.value === 'function') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✗ Was not returned
if (node.generator && functionToken.value === 'function') {
✓ Was returned
if (node.generator && functionToken.value === 'function') {
if (node.generator && functionToken.value === 'function') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
});
}
};
require-spaces-in-generator.js
/**
* Requires space before and after `*` in generator functions
*
* Types: `Object`
*
* - `Object` (at least one of properties must be present and it must be set to true):
* - `'beforeStar'`
* - `true` validates that there is a space before `*`
* - `'afterStar'`
* - `true` validates that there is a space after `*`
*
* #### Example
*
* ```js
* "requireSpacesInGenerator": {
* "beforeStar": true,
* "afterStar": true
* }
* ```
* ##### Valid for mode `{ "beforeStar": true, "afterStar": true }`
*
* ```js
* var x = function * () {};
* function * a() {};
* var x = async function * () {};
* var x = async function * a () {};
* async function * a() {}
* var x = async function * (){};
* ```
*
*/
var assert = require('assert');
Function (anonymous_1191)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1192)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be an object'
);

if ('beforeStar' in options) {
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
if ('afterStar' in options) {
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeStar || options.afterStar,
this.getOptionName() + ' must have beforeStar or afterStar property'
);

this._beforeStar = options.beforeStar;
this._afterStar = options.afterStar;
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be an object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeStar' in options) {···
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
✗ Negative was not executed (else)
}···
if ('afterStar' in options) {
if ('beforeStar' in options) {
assert(
options.beforeStar === true,
this.getOptionName() + '.beforeStar ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('afterStar' in options) {···
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}
✗ Negative was not executed (else)
}···

assert(
if ('afterStar' in options) {
assert(
options.afterStar === true,
this.getOptionName() + '.afterStar ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✗ Was not returned
options.beforeStar || options.afterStar,
✓ Was returned
options.beforeStar || options.afterStar,
options.beforeStar || options.afterStar,
this.getOptionName() + ' must have beforeStar or afterStar property'
);
this._beforeStar = options.beforeStar;
this._afterStar = options.afterStar;
},
Function (anonymous_1193)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInGenerator';
},
getOptionName: function() {
return 'requireSpacesInGenerator';
},
Function (anonymous_1194)
✓ Was called
check: function(file, errors) {···
var beforeStar = this._beforeStar;
var afterStar = this._afterStar;

file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
if (!node.generator) {
return;
}

var parent = node.parentElement;
var shorthand = false;

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
shorthand = true;
node = parent.key;
}

var currentToken = node.getFirstToken();

if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}

if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space before star'
});
}

if (afterStar) {
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space after star'
});
}
});
}
check: function(file, errors) {
var beforeStar = this._beforeStar;
var afterStar = this._afterStar;
Function (anonymous_1195)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···
if (!node.generator) {
return;
}

var parent = node.parentElement;
var shorthand = false;

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
shorthand = true;
node = parent.key;
}

var currentToken = node.getFirstToken();

if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}

if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space before star'
});
}

if (afterStar) {
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space after star'
});
}
});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (!node.generator) {···
return;
}
✓ Negative was executed (else)
}···

var parent = node.parentElement;
if (!node.generator) {
return;
}
var parent = node.parentElement;
var shorthand = false;
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
shorthand = true;
node = parent.key;
}
✓ Negative was executed (else)
}···

var currentToken = node.getFirstToken();
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
shorthand = true;
node = parent.key;
}
var currentToken = node.getFirstToken();
Branch IfStatement
✓ Positive was executed (if)
if (node.async && currentToken.value === 'async') {···
currentToken = file.getNextToken(currentToken);
}
✓ Negative was executed (else)
}···

if (beforeStar && !shorthand) {
Branch LogicalExpression
✓ Was returned
if (node.async && currentToken.value === 'async') {
✓ Was returned
if (node.async && currentToken.value === 'async') {
if (node.async && currentToken.value === 'async') {
currentToken = file.getNextToken(currentToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeStar && !shorthand) {···
// currentToken assigned outside of function
errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space before star'
});
}
✗ Negative was not executed (else)
}···

if (afterStar) {
Branch LogicalExpression
✓ Was returned
if (beforeStar && !shorthand) {
✗ Was not returned
if (beforeStar && !shorthand) {
if (beforeStar && !shorthand) {
// currentToken assigned outside of function
errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space before star'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (afterStar) {···
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}

errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space after star'
});
}
✗ Negative was not executed (else)
}···
});
if (afterStar) {
Branch IfStatement
✗ Positive was not executed (if)
if (shorthand) {···
currentToken = file.getPrevToken(currentToken);
} else {
✓ Negative was executed (else)
} else {···
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}
if (shorthand) {
currentToken = file.getPrevToken(currentToken);
} else {
// currentToken reassigned for star token
currentToken = file.getNextToken(currentToken);
}
errors.assert.whitespaceBetween({
token: currentToken,
nextToken: file.getNextToken(currentToken),
message: 'Missing space after star'
});
}
});
}
};
require-spaces-in-named-function-expression.js
/**
* Requires space before `()` or `{}` in named function expressions.
*
* Types: `Object`
*
* - `Object` (at least one of properties must be present and it must be set to true):
* - `'beforeOpeningRoundBrace'`
* - `true` validates that there is a space before `()`
* - `'beforeOpeningCurlyBrace'`
* - `true` validates that there is a space before `{}`
*
* #### Example
*
* ```js
* "requireSpacesInNamedFunctionExpression": {
* "beforeOpeningRoundBrace": true,
* "beforeOpeningCurlyBrace": true
* }
* ```
* ```js
* "requireSpacesInNamedFunctionExpression": {
* "beforeOpeningRoundBrace": true
* }
* ```
* ```js
* "requireSpacesInNamedFunctionExpression": {
* "beforeOpeningCurlyBrace": true
* }
* ```
*
* ##### Valid for mode `{ "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function a () {};
* ```
*
* ##### Valid for mode `{ "beforeOpeningRoundBrace": true }`
*
* ```js
* var x = function a (){};
* ```
*
* ##### Valid for mode `{ "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function a() {};
* ```
*
* ##### Invalid for mode `{ "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }`
*
* ```js
* var x = function a() {};
* var x = function a (){};
* var x = function a(){};
* ```
*/
var assert = require('assert');
Function (anonymous_1196)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1197)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);

if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}

if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}

assert(
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
'or beforeOpeningRoundBrace property'
);

this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
configure: function(options) {
assert(
typeof options === 'object',
this.getOptionName() + ' option must be the object'
);
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningRoundBrace' in options) {···
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

if ('beforeOpeningCurlyBrace' in options) {
if ('beforeOpeningRoundBrace' in options) {
assert(
options.beforeOpeningRoundBrace === true,
this.getOptionName() + '.beforeOpeningRoundBrace ' +
'property requires true value or should be removed'
);
}
Branch IfStatement
✓ Positive was executed (if)
if ('beforeOpeningCurlyBrace' in options) {···
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···

assert(
if ('beforeOpeningCurlyBrace' in options) {
assert(
options.beforeOpeningCurlyBrace === true,
this.getOptionName() + '.beforeOpeningCurlyBrace ' +
'property requires true value or should be removed'
);
}
assert(
Branch LogicalExpression
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
✓ Was returned
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
options.beforeOpeningCurlyBrace || options.beforeOpeningRoundBrace,
this.getOptionName() + ' must have beforeOpeningCurlyBrace ' +
'or beforeOpeningRoundBrace property'
);
this._beforeOpeningRoundBrace = Boolean(options.beforeOpeningRoundBrace);
this._beforeOpeningCurlyBrace = Boolean(options.beforeOpeningCurlyBrace);
},
Function (anonymous_1198)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInNamedFunctionExpression';
},
getOptionName: function() {
return 'requireSpacesInNamedFunctionExpression';
},
Function (anonymous_1199)
✓ Was called
check: function(file, errors) {···
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;

file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node.id;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

// named function expressions only
if (node.id) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
}
});
}
check: function(file, errors) {
var beforeOpeningRoundBrace = this._beforeOpeningRoundBrace;
var beforeOpeningCurlyBrace = this._beforeOpeningCurlyBrace;
Function (anonymous_1200)
✓ Was called
file.iterateNodesByType(['FunctionExpression'], function(node) {···
var functionNode = node.id;
var parent = node.parentElement;

// Ignore syntactic sugar for getters and setters.
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}

// shorthand or constructor methods
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}

// named function expressions only
if (node.id) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
}
});
file.iterateNodesByType(['FunctionExpression'], function(node) {
var functionNode = node.id;
var parent = node.parentElement;
// Ignore syntactic sugar for getters and setters.
Branch IfStatement
✗ Positive was not executed (if)
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {···
return;
}
✓ Negative was executed (else)
}···

// shorthand or constructor methods
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✓ Was returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
Branch LogicalExpression
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
✗ Was not returned
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
if (parent.type === 'Property' && (parent.kind === 'get' || parent.kind === 'set')) {
return;
}
// shorthand or constructor methods
Branch IfStatement
✗ Positive was not executed (if)
if (parent.method || parent.type === 'MethodDefinition') {···
functionNode = parent.key;
}
✓ Negative was executed (else)
}···

// named function expressions only
Branch LogicalExpression
✓ Was returned
if (parent.method || parent.type === 'MethodDefinition') {
✗ Was not returned
if (parent.method || parent.type === 'MethodDefinition') {
if (parent.method || parent.type === 'MethodDefinition') {
functionNode = parent.key;
}
// named function expressions only
Branch IfStatement
✓ Positive was executed (if)
if (node.id) {···
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}

if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
}
✗ Negative was not executed (else)
}···
});
if (node.id) {
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningRoundBrace) {···
var functionToken = file.getFirstNodeToken(functionNode);
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
✓ Negative was executed (else)
}···

if (beforeOpeningCurlyBrace) {
if (beforeOpeningRoundBrace) {
var functionToken = file.getFirstNodeToken(functionNode);
Branch IfStatement
✗ Positive was not executed (if)
if (node.async && functionToken.value === 'async') {···
functionToken = file.getNextToken(functionToken);
}
✓ Negative was executed (else)
}···
errors.assert.whitespaceBetween({
Branch LogicalExpression
✓ Was returned
if (node.async && functionToken.value === 'async') {
✓ Was returned
if (node.async && functionToken.value === 'async') {
if (node.async && functionToken.value === 'async') {
functionToken = file.getNextToken(functionToken);
}
errors.assert.whitespaceBetween({
token: functionToken,
nextToken: file.getNextToken(functionToken),
message: 'Missing space before opening round brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (beforeOpeningCurlyBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
✓ Negative was executed (else)
}···
}
if (beforeOpeningCurlyBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
errors.assert.whitespaceBetween({
token: file.getPrevToken(bodyToken),
nextToken: bodyToken,
message: 'Missing space before opening curly brace'
});
}
}
});
}
};
require-spaces-inside-array-brackets.js
/**
* Requires space after opening array square bracket and before closing.
* Reports only on arrays, not on property accessors.
* Use [requireSpacesInsideBrackets](http://jscs.info/rule/requireSpacesInsideBrackets.html)
* to report on all brackets.
*
* Types: `String` or `Object`
*
* Values:
* - `String`
* - `"all"`: strict mode
* - `"allButNested"`: (*deprecated* use Object version with `"allExcept": [ "[", "]" ]`) ignores nested
* closing brackets in a row
* - `Object`:
* - `"allExcept"`: Array specifying list of tokens that can occur after an opening square bracket or before a
* closing square bracket without a space
*
* #### Example
*
* ```js
* "requireSpacesInsideArrayBrackets": "all"
* ```
* ```js
* "requireSpacesInsideArrayBrackets": {
* "allExcept": [ "[", "]", "{", "}" ]
* }
* ```
*
* ##### Valid for mode `"all"`
*
* ```js
* var x = [ 1 ];
* var x = a[1];
* ```
*
* ##### Valid for mode `{ "allExcept": [ "[", "]" ] }` or `"allButNested"`
*
* ```js
* var x = [[ 1 ], [ 2 ]];
* ```
*
* ##### Valid for mode `{ "allExcept": [ "[", "]", "{", "}" ] }`
*
* ```js
* var x = [[ 1 ], [ 2 ]];
* var x = [{ a: 1 }, { b: 2}];
* ```
*
* ##### Invalid
*
* ```js
* var x = [1];
* ```
*/
var assert = require('assert');
Function (anonymous_1201)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1202)
✓ Was called
configure: function(value) {···
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule' +
' requires string value "all" or "allButNested" or object';

if (typeof value === 'string') {
assert(modes[value], error);

} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
mode = value;
}

if (mode === 'allButNested') {
this._exceptions['['] = this._exceptions[']'] = true;
}
},
configure: function(value) {
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule' +
' requires string value "all" or "allButNested" or object';
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'string') {···
assert(modes[value], error);

} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
assert(false, error);
}
if (typeof value === 'string') {
assert(modes[value], error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
✓ Negative was executed (else)
} else {···
mode = value;
}
if (isObject) {
Function (anonymous_1203)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
} else {
mode = value;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'allButNested') {···
this._exceptions['['] = this._exceptions[']'] = true;
}
✓ Negative was executed (else)
}···
},
if (mode === 'allButNested') {
this._exceptions['['] = this._exceptions[']'] = true;
}
},
Function (anonymous_1204)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideArrayBrackets';
},
getOptionName: function() {
return 'requireSpacesInsideArrayBrackets';
},
Function (anonymous_1205)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateNodesByType('ArrayExpression', function(node) {
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});

// Skip for empty array brackets
if (afterOpen.value === ']') {
return;
}

if (!(afterOpen.value in exceptions)) {
errors.assert.spacesBetween({
token: openBracket,
nextToken: afterOpen,
exactly: 1,
message: 'One space required after opening bracket'
});
}

if (!(beforeClose.value in exceptions)) {
errors.assert.spacesBetween({
token: beforeClose,
nextToken: closeBracket,
exactly: 1,
message: 'One space required before closing bracket'
});
}
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_1206)
✓ Was called
file.iterateNodesByType('ArrayExpression', function(node) {···
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});

// Skip for empty array brackets
if (afterOpen.value === ']') {
return;
}

if (!(afterOpen.value in exceptions)) {
errors.assert.spacesBetween({
token: openBracket,
nextToken: afterOpen,
exactly: 1,
message: 'One space required after opening bracket'
});
}

if (!(beforeClose.value in exceptions)) {
errors.assert.spacesBetween({
token: beforeClose,
nextToken: closeBracket,
exactly: 1,
message: 'One space required before closing bracket'
});
}
});
file.iterateNodesByType('ArrayExpression', function(node) {
var openBracket = node.getFirstToken();
var afterOpen = file.getNextToken(openBracket, {includeComments: true});
var closeBracket = file.getLastNodeToken(node);
var beforeClose = file.getPrevToken(closeBracket, {includeComments: true});
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (afterOpen.value === ']') {···
return;
}
✓ Negative was executed (else)
}···

if (!(afterOpen.value in exceptions)) {
if (afterOpen.value === ']') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!(afterOpen.value in exceptions)) {···
errors.assert.spacesBetween({
token: openBracket,
nextToken: afterOpen,
exactly: 1,
message: 'One space required after opening bracket'
});
}
✓ Negative was executed (else)
}···

if (!(beforeClose.value in exceptions)) {
if (!(afterOpen.value in exceptions)) {
errors.assert.spacesBetween({
token: openBracket,
nextToken: afterOpen,
exactly: 1,
message: 'One space required after opening bracket'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (!(beforeClose.value in exceptions)) {···
errors.assert.spacesBetween({
token: beforeClose,
nextToken: closeBracket,
exactly: 1,
message: 'One space required before closing bracket'
});
}
✓ Negative was executed (else)
}···
});
if (!(beforeClose.value in exceptions)) {
errors.assert.spacesBetween({
token: beforeClose,
nextToken: closeBracket,
exactly: 1,
message: 'One space required before closing bracket'
});
}
});
}
};
require-spaces-inside-brackets.js
/**
* Requires space after opening square bracket and before closing.
* Reports on all on brackets, even on property accessors.
* Use [requireSpacesInsideArrayBrackets](http://jscs.info/rule/requireSpacesInsideArrayBrackets.html)
* to exclude property accessors.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `Boolean`
* - `true`: strict mode
* - `Object`:
* - `"allExcept"`: Array specifying list of tokens that can occur after an opening square bracket or before a
* closing square bracket without a space
* #### Example
*
* ```js
* "requireSpacesInsideBrackets": true
* ```
* ```js
* "requireSpacesInsideBrackets": {
* "allExcept": [ "[", "]", "{", "}" ]
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = [ 1 ];
* var x = a[ 1 ];
* ```
*
* ##### Valid for mode `{ allExcept": [ "[", "]", "{", "}" ] }`
*
* ```js
* var x = [[ 1 ], [ 2 ]];
* var x = [{ a: 1 }, { b: 2}];
* ```
*
* ##### Invalid
*
* ```js
* var x = [1];
* ```
*/
var assert = require('assert');
Function (anonymous_1207)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1208)
✓ Was called
configure: function(value) {···
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule requires string value true or object';

if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
configure: function(value) {
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule requires string value true or object';
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true, error);
}
if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (isObject) {
Function (anonymous_1209)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
Function (anonymous_1210)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideBrackets';
},
getOptionName: function() {
return 'requireSpacesInsideBrackets';
},
Function (anonymous_1211)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.value;

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === ']') {
return;
}

errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening bracket'
});
});

file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.value;

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === '[') {
return;
}

errors.assert.spacesBetween({
token: prevToken,
nextToken: token,
exactly: 1,
message: 'One space required before closing bracket'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_1212)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {···
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.value;

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === ']') {
return;
}

errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {
var nextToken = file.getNextToken(token, { includeComments: true });
var value = nextToken.value;
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty array brackets
if (value in exceptions) {
return;
}
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (value === ']') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.spacesBetween({
if (value === ']') {
return;
}
errors.assert.spacesBetween({
token: token,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening bracket'
});
});
Function (anonymous_1213)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {···
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.value;

if (value in exceptions) {
return;
}

// Skip for empty array brackets
if (value === '[') {
return;
}

errors.assert.spacesBetween({
token: prevToken,
nextToken: token,
exactly: 1,
message: 'One space required before closing bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {
var prevToken = file.getPrevToken(token, { includeComments: true });
var value = prevToken.value;
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty array brackets
if (value in exceptions) {
return;
}
// Skip for empty array brackets
Branch IfStatement
✓ Positive was executed (if)
if (value === '[') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.spacesBetween({
if (value === '[') {
return;
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: token,
exactly: 1,
message: 'One space required before closing bracket'
});
});
}
};
require-spaces-inside-imported-object-braces.js
/**
* Requires space after opening object curly brace and before closing in import statements.
*
* Type: `Boolean`
*
* Value: `true`
*
* #### Example
*
* ```js
* "requireSpacesInsideImportedObjectBraces": true
* ```
*
* ##### Valid
*
* ```js
* import { foo, bar } from 'foo-bar';
*
* import { foo as f, bar } from 'foo-bar';
* ```
*
* ##### Invalid
*
* ```js
* import {foo, bar} from 'foo-bar';
*
* import {foo as f, bar} from 'foo-bar';
* ```
*/
var assert = require('assert');
Function (anonymous_1214)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1215)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1216)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideImportedObjectBraces';
},
getOptionName: function() {
return 'requireSpacesInsideImportedObjectBraces';
},
Function (anonymous_1217)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['ImportDeclaration'], function(node) {

if (!node.specifiers) {
return;
}

node.specifiers.forEach(function(specifier) {

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.spacesBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
exactly: 1,
message: 'One space required after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.spacesBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
exactly: 1,
message: 'One space required before closing curly brace'
});
}
});
});
}
check: function(file, errors) {
Function (anonymous_1218)
✓ Was called
file.iterateNodesByType(['ImportDeclaration'], function(node) {···

if (!node.specifiers) {
return;
}

node.specifiers.forEach(function(specifier) {

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.spacesBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
exactly: 1,
message: 'One space required after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.spacesBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
exactly: 1,
message: 'One space required before closing curly brace'
});
}
});
});
file.iterateNodesByType(['ImportDeclaration'], function(node) {
Branch IfStatement
✗ Positive was not executed (if)
if (!node.specifiers) {···
return;
}
✓ Negative was executed (else)
}···

node.specifiers.forEach(function(specifier) {
if (!node.specifiers) {
return;
}
Function (anonymous_1219)
✓ Was called
node.specifiers.forEach(function(specifier) {···

if (specifier.type !== 'ImportSpecifier') {
return;
}

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());

if (maybeOpeningBrace.value === '{') {
errors.assert.spacesBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
exactly: 1,
message: 'One space required after opening curly brace'
});
}

if (maybeClosingBrace.value === '}') {
errors.assert.spacesBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
exactly: 1,
message: 'One space required before closing curly brace'
});
}
});
node.specifiers.forEach(function(specifier) {
Branch IfStatement
✓ Positive was executed (if)
if (specifier.type !== 'ImportSpecifier') {···
return;
}
✓ Negative was executed (else)
}···

var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
if (specifier.type !== 'ImportSpecifier') {
return;
}
var maybeOpeningBrace = file.getPrevToken(specifier.getFirstToken());
var maybeClosingBrace = file.getNextToken(specifier.getLastToken());
Branch IfStatement
✓ Positive was executed (if)
if (maybeOpeningBrace.value === '{') {···
errors.assert.spacesBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
exactly: 1,
message: 'One space required after opening curly brace'
});
}
✓ Negative was executed (else)
}···

if (maybeClosingBrace.value === '}') {
if (maybeOpeningBrace.value === '{') {
errors.assert.spacesBetween({
token: maybeOpeningBrace,
nextToken: specifier.getFirstToken(),
exactly: 1,
message: 'One space required after opening curly brace'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (maybeClosingBrace.value === '}') {···
errors.assert.spacesBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
exactly: 1,
message: 'One space required before closing curly brace'
});
}
✓ Negative was executed (else)
}···
});
if (maybeClosingBrace.value === '}') {
errors.assert.spacesBetween({
token: specifier.getLastToken(),
nextToken: maybeClosingBrace,
exactly: 1,
message: 'One space required before closing curly brace'
});
}
});
});
}
};
require-spaces-inside-object-brackets.js
/**
* Requires space after opening object curly brace and before closing.
*
* Types: `String` or `Object`
*
* Values:
* - `String`
* - `"all"`: strict mode
* - `"allButNested"`: (*deprecated* use Object version with `"allExcept": ['}']`) ignores nested
* closing object braces in a row
* - `Object`:
* - `"allExcept"`: Array specifying list of tokens that can occur after an opening object brace or before a
* closing object brace without a space
*
* #### Example
*
* ```js
* "requireSpacesInsideObjectBrackets": {
* "allExcept": [ "}", ")" ]
* }
* ```
* ```js
* "requireSpacesInsideObjectBrackets": "all"
* ```
*
* ##### Valid for mode `"all"`
*
* ```js
* var x = { a: { b: 1 } };
* ```
*
* ##### Valid for mode `{ "allExcept": [ "}" ] }` or `"allButNested"`
*
* ```js
* var x = { a: { b: 1 }};
* ```
*
* ##### Valid for mode `"allExcept": [ "}", ")" ]`
*
* ```js
* var x = { a: (b ? 1 : 2)};
* var x = { a: { b: 1 }};
* ```
*
* ##### Invalid
*
* ```js
* var x = {a: 1};
* ```
*/
var assert = require('assert');
Function (anonymous_1220)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1221)
✓ Was called
configure: function(value) {···
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule' +
' requires string value \'all\' or \'allButNested\' or object';

if (typeof value === 'string') {
assert(modes[value], error);

} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
mode = value;
}

if (mode === 'allButNested') {
this._exceptions['}'] = true;
}
},
configure: function(value) {
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule' +
' requires string value \'all\' or \'allButNested\' or object';
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'string') {···
assert(modes[value], error);

} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
assert(false, error);
}
if (typeof value === 'string') {
assert(modes[value], error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert('allExcept' in value, error);
} else {
assert(false, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);

} else {
✓ Negative was executed (else)
} else {···
mode = value;
}
if (isObject) {
Function (anonymous_1222)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
} else {
mode = value;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'allButNested') {···
this._exceptions['}'] = true;
}
✓ Negative was executed (else)
}···
},
if (mode === 'allButNested') {
this._exceptions['}'] = true;
}
},
Function (anonymous_1223)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideObjectBrackets';
},
getOptionName: function() {
return 'requireSpacesInsideObjectBrackets';
},
Function (anonymous_1224)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

// Don't check empty object
if (nextToken.value === '}') {
return;
}

errors.assert.spacesBetween({
token: openingBracket,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);

if (prevToken.value in exceptions) {
return;
}

errors.assert.spacesBetween({
token: prevToken,
nextToken: closingBracket,
exactly: 1,
message: 'One space required before closing curly brace'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_1225)
✓ Was called
file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {···
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);

// Don't check empty object
if (nextToken.value === '}') {
return;
}

errors.assert.spacesBetween({
token: openingBracket,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening curly brace'
});

var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);

if (prevToken.value in exceptions) {
return;
}

errors.assert.spacesBetween({
token: prevToken,
nextToken: closingBracket,
exactly: 1,
message: 'One space required before closing curly brace'
});
});
file.iterateNodesByType(['ObjectExpression', 'ObjectPattern'], function(node) {
var openingBracket = node.getFirstToken();
var nextToken = file.getNextToken(openingBracket);
// Don't check empty object
Branch IfStatement
✓ Positive was executed (if)
if (nextToken.value === '}') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.spacesBetween({
if (nextToken.value === '}') {
return;
}
errors.assert.spacesBetween({
token: openingBracket,
nextToken: nextToken,
exactly: 1,
message: 'One space required after opening curly brace'
});
var closingBracket = file.getLastNodeToken(node);
var prevToken = file.getPrevToken(closingBracket);
Branch IfStatement
✓ Positive was executed (if)
if (prevToken.value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.spacesBetween({
if (prevToken.value in exceptions) {
return;
}
errors.assert.spacesBetween({
token: prevToken,
nextToken: closingBracket,
exactly: 1,
message: 'One space required before closing curly brace'
});
});
}
};
require-spaces-inside-parentheses.js
/**
* Requires space after opening round bracket and before closing.
*
* Types: `String` or `Object`
*
* Values:
* - `String`
* - `"all"`: strict mode
* - `"allButNested"`: (*deprecated* use Object version with `"except": ["(", ")"]`) ignores nested brackets
* in a row
* - `Object`:
* - `"all"`: true
* - `"ignoreParenthesizedExpression"`: true
* - `"except"`: Array specifying list of tokens that can occur after an opening bracket or before a
* closing bracket without a space
*
* #### Example
*
* ```js
* "requireSpacesInsideParentheses": "all"
* ```
* ```js
* "requireSpacesInsideParentheses": {
* "all": true,
* "except": [ "{", "}", "\"" ]
* }
* ```
*
* ##### Valid for mode `"all"`
*
* ```js
* var x = Math.pow( ( 1 + 2 ), ( 3 + 4 ) );
* ```
*
* ##### Valid for mode `{ "all": true, "except": [ "(", ")" ] }` or `"allButNested"`
*
* ```js
* var x = Math.pow(( 1 + 2 ), ( 3 + 4 ));
* ```
*
* ##### Valid for mode `{ "all": true, "ignoreParenthesizedExpression": true }`
*
* ```js
* if ( !("foo" in obj) ) {}
* ```
*
* ##### Valid for mode `{ "all": true, "except": [ "{", "}" ] }`
*
* ```js
* var x = Math.pow( foo({ test: 1 }) );
* ```
*
* ##### Valid for mode `{ "all": true, "except": [ "\"" ] }`
*
* ```js
* var x = foo("string");
* var x = foo( 1 );
* ```
*
* ##### Invalid
*
* ```js
* var x = Math.pow(1 + 2, 3 + 4);
* ```
*/
var assert = require('assert');
var TokenCategorizer = require('../token-categorizer');
Function (anonymous_1226)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1227)
✓ Was called
configure: function(value) {···
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule' +
' requires string value \'all\' or \'allButNested\' or object';

if (typeof value === 'string') {
assert(modes[value], error);

} else if (isObject) {
assert(
'all' in value || 'allButNested' in value,
error
);
} else {
assert(false, error);
}

this._exceptions = {};
this._exceptSingleQuote = false;
this._exceptDoubleQuote = false;
this._ignoreParenthesizedExpression = false;

if (isObject) {
mode = 'all' in value ? 'all' : 'allButNested';

(value.except || []).forEach(function(value) {
if (value === '\'') {
this._exceptSingleQuote = true;
}

if (value === '"') {
this._exceptDoubleQuote = true;
}

this._exceptions[value] = true;
}, this);

if (value.ignoreParenthesizedExpression === true) {
this._ignoreParenthesizedExpression = true;
}

} else {
mode = value;
}

if (mode === 'allButNested') {
this._exceptions[')'] = this._exceptions['('] = true;
}
},
configure: function(value) {
var mode;
var modes = {
'all': true,
'allButNested': true
};
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule' +
' requires string value \'all\' or \'allButNested\' or object';
Branch IfStatement
✓ Positive was executed (if)
if (typeof value === 'string') {···
assert(modes[value], error);

} else if (isObject) {
✓ Negative was executed (else)
} else if (isObject) {···
assert(
'all' in value || 'allButNested' in value,
error
);
} else {
assert(false, error);
}
if (typeof value === 'string') {
assert(modes[value], error);
Branch IfStatement
✓ Positive was executed (if)
} else if (isObject) {···
assert(
'all' in value || 'allButNested' in value,
error
);
} else {
✓ Negative was executed (else)
} else {···
assert(false, error);
}
} else if (isObject) {
assert(
Branch LogicalExpression
✗ Was not returned
'all' in value || 'allButNested' in value,
✓ Was returned
'all' in value || 'allButNested' in value,
'all' in value || 'allButNested' in value,
error
);
} else {
assert(false, error);
}
this._exceptions = {};
this._exceptSingleQuote = false;
this._exceptDoubleQuote = false;
this._ignoreParenthesizedExpression = false;
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
mode = 'all' in value ? 'all' : 'allButNested';

(value.except || []).forEach(function(value) {
if (value === '\'') {
this._exceptSingleQuote = true;
}

if (value === '"') {
this._exceptDoubleQuote = true;
}

this._exceptions[value] = true;
}, this);

if (value.ignoreParenthesizedExpression === true) {
this._ignoreParenthesizedExpression = true;
}

} else {
✓ Negative was executed (else)
} else {···
mode = value;
}
if (isObject) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
mode = 'all' in value ? 'all' : 'allButNested';
✗ Negative was not returned (: ...)
mode = 'all' in value ? 'all' : 'allButNested';
mode = 'all' in value ? 'all' : 'allButNested';
Function (anonymous_1228)
✓ Was called
(value.except || []).forEach(function(value) {···
if (value === '\'') {
this._exceptSingleQuote = true;
}

if (value === '"') {
this._exceptDoubleQuote = true;
}

this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✓ Was returned
(value.except || []).forEach(function(value) {
✓ Was returned
(value.except || []).forEach(function(value) {
(value.except || []).forEach(function(value) {
Branch IfStatement
✓ Positive was executed (if)
if (value === '\'') {···
this._exceptSingleQuote = true;
}
✓ Negative was executed (else)
}···

if (value === '"') {
if (value === '\'') {
this._exceptSingleQuote = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (value === '"') {···
this._exceptDoubleQuote = true;
}
✓ Negative was executed (else)
}···

this._exceptions[value] = true;
if (value === '"') {
this._exceptDoubleQuote = true;
}
this._exceptions[value] = true;
}, this);
Branch IfStatement
✓ Positive was executed (if)
if (value.ignoreParenthesizedExpression === true) {···
this._ignoreParenthesizedExpression = true;
}
✓ Negative was executed (else)
}···

} else {
if (value.ignoreParenthesizedExpression === true) {
this._ignoreParenthesizedExpression = true;
}
} else {
mode = value;
}
Branch IfStatement
✓ Positive was executed (if)
if (mode === 'allButNested') {···
this._exceptions[')'] = this._exceptions['('] = true;
}
✓ Negative was executed (else)
}···
},
if (mode === 'allButNested') {
this._exceptions[')'] = this._exceptions['('] = true;
}
},
Function (anonymous_1229)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideParentheses';
},
getOptionName: function() {
return 'requireSpacesInsideParentheses';
},
Function (anonymous_1230)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;
var singleQuote = this._exceptSingleQuote;
var doubleQuote = this._exceptDoubleQuote;
var ignoreParenthesizedExpression = this._ignoreParenthesizedExpression;

file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();

if (
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeOpenParen(token) === 'ParenthesizedExpression'
) {
return;
}

if (value in exceptions) {
return;
}

if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
return;
}

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
return;
}

// Skip for empty parentheses
if (value === ')') {
return;
}

errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening round bracket'
});
});

file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();

if (
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeCloseParen(token) === 'ParenthesizedExpression'
) {
return;
}

if (value in exceptions) {

// Special case - foo( object[i] )
if (!(
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
)) {
return;
}
}

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
return;
}

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
return;
}

// Skip for empty parentheses
if (value === '(') {
return;
}

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing round bracket'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
var singleQuote = this._exceptSingleQuote;
var doubleQuote = this._exceptDoubleQuote;
var ignoreParenthesizedExpression = this._ignoreParenthesizedExpression;
Function (anonymous_1231)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {···
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();

if (
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeOpenParen(token) === 'ParenthesizedExpression'
) {
return;
}

if (value in exceptions) {
return;
}

if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
return;
}

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
return;
}

// Skip for empty parentheses
if (value === ')') {
return;
}

errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening round bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.getSourceCode();
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

if (value in exceptions) {
if (
Branch LogicalExpression
✓ Was returned
TokenCategorizer.categorizeOpenParen(token) === 'ParenthesizedExpression'
✓ Was returned
ignoreParenthesizedExpression &&
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeOpenParen(token) === 'ParenthesizedExpression'
) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
if (value in exceptions) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {···
return;
}
✓ Negative was executed (else)
}···

if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
✓ Was returned
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
if (doubleQuote && nextToken.type === 'String' && value[0] === '"') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty parentheses
Branch LogicalExpression
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
Branch LogicalExpression
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
✓ Was returned
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
if (singleQuote && nextToken.type === 'String' && value[0] === '\'') {
return;
}
// Skip for empty parentheses
Branch IfStatement
✓ Positive was executed (if)
if (value === ')') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (value === ')') {
return;
}
errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening round bracket'
});
});
Function (anonymous_1232)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();

if (
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeCloseParen(token) === 'ParenthesizedExpression'
) {
return;
}

if (value in exceptions) {

// Special case - foo( object[i] )
if (!(
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
)) {
return;
}
}

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
return;
}

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
return;
}

// Skip for empty parentheses
if (value === '(') {
return;
}

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing round bracket'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.getSourceCode();
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

if (value in exceptions) {
if (
Branch LogicalExpression
✓ Was returned
TokenCategorizer.categorizeCloseParen(token) === 'ParenthesizedExpression'
✓ Was returned
ignoreParenthesizedExpression &&
ignoreParenthesizedExpression &&
TokenCategorizer.categorizeCloseParen(token) === 'ParenthesizedExpression'
) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (value in exceptions) {···

// Special case - foo( object[i] )
if (!(
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
)) {
return;
}
}
✓ Negative was executed (else)
}···

if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
if (value in exceptions) {
// Special case - foo( object[i] )
Branch IfStatement
✓ Positive was executed (if)
)) {···
return;
}
✓ Negative was executed (else)
}···
}
if (!(
Branch LogicalExpression
✓ Was returned
prevToken.parentElement.type === 'MemberExpression'
✓ Was returned
value === ']' &&
value === ']' &&
prevToken.parentElement.type === 'MemberExpression'
)) {
return;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {···
return;
}
✓ Negative was executed (else)
}···

if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
Branch LogicalExpression
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
✓ Was returned
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
if (doubleQuote && prevToken.type === 'String' && value[value.length - 1] === '"') {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {···
return;
}
✓ Negative was executed (else)
}···

// Skip for empty parentheses
Branch LogicalExpression
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
Branch LogicalExpression
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
✓ Was returned
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
if (singleQuote && prevToken.type === 'String' && value[value.length - 1] === '\'') {
return;
}
// Skip for empty parentheses
Branch IfStatement
✓ Positive was executed (if)
if (value === '(') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (value === '(') {
return;
}
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing round bracket'
});
});
}
};
require-spaces-inside-parenthesized-expression.js
/**
* Requires space after opening and before closing grouping parentheses.
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`: always require spaces inside grouping parentheses
* - `Object`:
* - `"allExcept"`: `[ "{", "}", "function" ]` Ignore parenthesized objects and functions
*
* #### Example
*
* ```js
* "requireSpacesInsideParenthesizedExpression": true
*
* // or
*
* "requireSpacesInsideParenthesizedExpression": {
* "allExcept": [ "{", "}" ]
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = ( 1 + obj.size ) * ( 2 );
* ```
*
* ##### Valid for mode `{ allExcept": [ "{", "}", "function" ] }`
*
* ```js
* var x = ( options || { x: true }).x;
* var global = (function() { return this; })();
* ```
*
* ##### Invalid
*
* ```js
* var x = (1 + obj.size) * (2);
* ```
*/
var assert = require('assert');
var TokenCategorizer = require('../token-categorizer');
Function (anonymous_1233)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1234)
✓ Was called
configure: function(value) {···
var isObject = typeof value === 'object';

var error = this.getOptionName() + ' rule requires string value true or object';

if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}

this._exceptions = {};

if (isObject) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
configure: function(value) {
var isObject = typeof value === 'object';
var error = this.getOptionName() + ' rule requires string value true or object';
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
assert('allExcept' in value, error);
} else {
✓ Negative was executed (else)
} else {···
assert(value === true, error);
}
if (isObject) {
assert('allExcept' in value, error);
} else {
assert(value === true, error);
}
this._exceptions = {};
Branch IfStatement
✓ Positive was executed (if)
if (isObject) {···
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
✓ Negative was executed (else)
}···
},
if (isObject) {
Function (anonymous_1235)
✓ Was called
(value.allExcept || []).forEach(function(value) {···
this._exceptions[value] = true;
}, this);
Branch LogicalExpression
✗ Was not returned
(value.allExcept || []).forEach(function(value) {
✓ Was returned
(value.allExcept || []).forEach(function(value) {
(value.allExcept || []).forEach(function(value) {
this._exceptions[value] = true;
}, this);
}
},
Function (anonymous_1236)
✓ Was called
getOptionName: function() {···
return 'requireSpacesInsideParenthesizedExpression';
},
getOptionName: function() {
return 'requireSpacesInsideParenthesizedExpression';
},
Function (anonymous_1237)
✓ Was called
check: function(file, errors) {···
var exceptions = this._exceptions;

file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.isComment ?
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;

// Skip empty parentheses and explicit exceptions
if (value === ')' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening grouping parenthesis'
});
});

file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.isComment ?
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;

// Skip empty parentheses and explicit exceptions
if (value === '(' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing grouping parenthesis'
});
});
}
check: function(file, errors) {
var exceptions = this._exceptions;
Function (anonymous_1238)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {···
var nextToken = file.getNextToken(token, {includeComments: true});
var value = nextToken.isComment ?
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;

// Skip empty parentheses and explicit exceptions
if (value === ')' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening grouping parenthesis'
});
});
file.iterateTokensByTypeAndValue('Punctuator', '(', function(token) {
var nextToken = file.getNextToken(token, {includeComments: true});
Branch ConditionalExpression
✓ Positive was returned (? ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
✓ Negative was returned (: ...)
nextToken.value;
var value = nextToken.isComment ?
Branch ConditionalExpression
✓ Positive was returned (? ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
✓ Negative was returned (: ...)
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.type === 'CommentBlock' ? '/*' : '//' :
nextToken.value;
// Skip empty parentheses and explicit exceptions
Branch IfStatement
✓ Positive was executed (if)
if (value === ')' || value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip non-expression parentheses
Branch LogicalExpression
✓ Was returned
if (value === ')' || value in exceptions) {
✓ Was returned
if (value === ')' || value in exceptions) {
if (value === ')' || value in exceptions) {
return;
}
// Skip non-expression parentheses
var type = TokenCategorizer.categorizeOpenParen(token);
Branch IfStatement
✓ Positive was executed (if)
if (type !== 'ParenthesizedExpression') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (type !== 'ParenthesizedExpression') {
return;
}
errors.assert.whitespaceBetween({
token: token,
nextToken: nextToken,
message: 'Missing space after opening grouping parenthesis'
});
});
Function (anonymous_1239)
✓ Was called
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {···
var prevToken = file.getPrevToken(token, {includeComments: true});
var value = prevToken.isComment ?
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;

// Skip empty parentheses and explicit exceptions
if (value === '(' || value in exceptions) {
return;
}

// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
if (type !== 'ParenthesizedExpression') {
return;
}

errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing grouping parenthesis'
});
});
file.iterateTokensByTypeAndValue('Punctuator', ')', function(token) {
var prevToken = file.getPrevToken(token, {includeComments: true});
Branch ConditionalExpression
✓ Positive was returned (? ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
✓ Negative was returned (: ...)
prevToken.value;
var value = prevToken.isComment ?
Branch ConditionalExpression
✓ Positive was returned (? ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
✓ Negative was returned (: ...)
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.type === 'CommentBlock' ? '*/' : '' :
prevToken.value;
// Skip empty parentheses and explicit exceptions
Branch IfStatement
✓ Positive was executed (if)
if (value === '(' || value in exceptions) {···
return;
}
✓ Negative was executed (else)
}···

// Skip non-expression parentheses
Branch LogicalExpression
✓ Was returned
if (value === '(' || value in exceptions) {
✓ Was returned
if (value === '(' || value in exceptions) {
if (value === '(' || value in exceptions) {
return;
}
// Skip non-expression parentheses
var type = TokenCategorizer.categorizeCloseParen(token);
Branch IfStatement
✓ Positive was executed (if)
if (type !== 'ParenthesizedExpression') {···
return;
}
✓ Negative was executed (else)
}···

errors.assert.whitespaceBetween({
if (type !== 'ParenthesizedExpression') {
return;
}
errors.assert.whitespaceBetween({
token: prevToken,
nextToken: token,
message: 'Missing space before closing grouping parenthesis'
});
});
}
};
require-spread.js
/**
* Disallows using `.apply` in favor of the spread operator
*
* Types: `Boolean`
*
* Values:
* - `true` specifies that apply `.apply` is disallowed
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireSpread": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* const wrap = (f, g) => (...args) => g(f, ...args)
* instance.method(...args)
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* const wrap = (f, g) => (...args) => g.apply(g, [f].concat(args))
* instance.method.apply(instance, args);
* ```
*/
var assert = require('assert');
Function (anonymous_1240)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1241)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
Function (anonymous_1242)
✓ Was called
getOptionName: function() {···
return 'requireSpread';
},
getOptionName: function() {
return 'requireSpread';
},
Function (anonymous_1243)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType('CallExpression', function(node) {
var callee = node.callee;
var firstParameter = node.arguments[0];

if (node.arguments.length === 2 &&
callee.property && callee.property.name === 'apply' &&
callee.object && callee.object.name === firstParameter.name) {
errors.add(
'Illegal use of apply method. Use the spread operator instead',
node.callee.property
);
}
});
}
check: function(file, errors) {
Function (anonymous_1244)
✓ Was called
file.iterateNodesByType('CallExpression', function(node) {···
var callee = node.callee;
var firstParameter = node.arguments[0];

if (node.arguments.length === 2 &&
callee.property && callee.property.name === 'apply' &&
callee.object && callee.object.name === firstParameter.name) {
errors.add(
'Illegal use of apply method. Use the spread operator instead',
node.callee.property
);
}
});
file.iterateNodesByType('CallExpression', function(node) {
var callee = node.callee;
var firstParameter = node.arguments[0];
Branch IfStatement
✓ Positive was executed (if)
callee.object && callee.object.name === firstParameter.name) {···
errors.add(
'Illegal use of apply method. Use the spread operator instead',
node.callee.property
);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
callee.object && callee.object.name === firstParameter.name) {
✓ Was returned
if (node.arguments.length === 2 &&···
callee.property && callee.property.name === 'apply' &&
callee.object && callee.object.name === firstParameter.name) {
Branch LogicalExpression
✓ Was returned
callee.object && callee.object.name === firstParameter.name) {
✓ Was returned
if (node.arguments.length === 2 &&···
callee.property && callee.property.name === 'apply' &&
Branch LogicalExpression
✓ Was returned
callee.property && callee.property.name === 'apply' &&
✓ Was returned
if (node.arguments.length === 2 &&···
callee.property && callee.property.name === 'apply' &&
Branch LogicalExpression
✓ Was returned
callee.property && callee.property.name === 'apply' &&
✓ Was returned
if (node.arguments.length === 2 &&
if (node.arguments.length === 2 &&
callee.property && callee.property.name === 'apply' &&
callee.object && callee.object.name === firstParameter.name) {
errors.add(
'Illegal use of apply method. Use the spread operator instead',
node.callee.property
);
}
});
}
};
require-template-strings.js
/**
* Requires the use of template strings instead of string concatenation.
*
* Types: `Boolean` or `Object`
*
* Values:
* - true
* - `Object`:
* - `"allExcept"`: array of quoted exceptions:
* - `"stringConcatenation"` ignores strings concatenated with other strings
*
* Version: `ES6`
*
* #### Example
*
* ```js
* "requireTemplateStrings": true
* "requireTemplateStrings": { "allExcept": ["stringConcatenation"] }
* ```
*
* ##### Valid
*
* ```js
* function sayHi(name) {
* return `How are you, ${name}?`;
* }
* `a ${b + c}`
* `a ${a()}`
* ```
*
* ##### Valid for `{ "allExcept": ["stringConcatenation"] }`
*
* ```js
* function sayBye(name) {
* return `It was good seeing you, ${name}! Let's hang out again sometime and` +
* ' grab some chicken and waffles.';
* }
* ```
*
* ##### Invalid
*
* ```js
* function sayHi(name) {
* return 'How are you, ' + name + '?';
* }
* "a" + (b + c)
* "a" + a()
* ```
*/
var assert = require('assert');
Function (anonymous_1245)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1246)
✓ Was called
configure: function(options) {···
this._allowStringConcatenation = false;
var optionName = this.getOptionName();

if (typeof options === 'object') {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');
options.allExcept.forEach(function(except) {
if (except === 'stringConcatenation') {
this._allowStringConcatenation = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'"stringConcatenation"');
}
}, this);
} else {
assert(
options === true,
optionName + ' option requires true value or object'
);
}
},
configure: function(options) {
this._allowStringConcatenation = false;
var optionName = this.getOptionName();
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');
options.allExcept.forEach(function(except) {
if (except === 'stringConcatenation') {
this._allowStringConcatenation = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'"stringConcatenation"');
}
}, this);
} else {
✓ Negative was executed (else)
} else {···
assert(
options === true,
optionName + ' option requires true value or object'
);
}
if (typeof options === 'object') {
assert(Array.isArray(options.allExcept), optionName + ' option requires "allExcept" ' +
'to be an array');
assert(options.allExcept.length > 0, optionName + ' option requires "allExcept" ' +
'to have at least one item or be set to `true`');
Function (anonymous_1247)
✓ Was called
options.allExcept.forEach(function(except) {···
if (except === 'stringConcatenation') {
this._allowStringConcatenation = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'"stringConcatenation"');
}
}, this);
options.allExcept.forEach(function(except) {
Branch IfStatement
✓ Positive was executed (if)
if (except === 'stringConcatenation') {···
this._allowStringConcatenation = true;
} else {
✓ Negative was executed (else)
} else {···
assert(false, optionName + ' option requires "allExcept" to only have ' +
'"stringConcatenation"');
}
if (except === 'stringConcatenation') {
this._allowStringConcatenation = true;
} else {
assert(false, optionName + ' option requires "allExcept" to only have ' +
'"stringConcatenation"');
}
}, this);
} else {
assert(
options === true,
optionName + ' option requires true value or object'
);
}
},
Function (anonymous_1248)
✓ Was called
getOptionName: function() {···
return 'requireTemplateStrings';
},
getOptionName: function() {
return 'requireTemplateStrings';
},
Function (anonymous_1249)
✓ Was called
check: function(file, errors) {···
var allowStringConcatenation = this._allowStringConcatenation;

function add(node) {
errors.add(
'Illegal use of string concatenation. Use template strings instead.',
node.left
);
}

file.iterateNodesByType('BinaryExpression', function(node) {
if (node.operator !== '+') {
return;
}

var leftIsString = node.left;
var rightIsString = node.right;

// Left side could also be binary expression (See gh-2050),
// but not the right one
while (leftIsString.type === 'BinaryExpression') {
leftIsString = leftIsString.left;
}

leftIsString = typeof leftIsString.value === 'string' ||
leftIsString.type === 'TemplateLiteral';

rightIsString = typeof rightIsString.value === 'string' ||
rightIsString.type === 'TemplateLiteral';

if (allowStringConcatenation && leftIsString && rightIsString) {
return;
}

// At least one of the operands should be a string or template string,
// otherwise this is not a concatenation
if (leftIsString || rightIsString) {
add(node);
}
});
}
check: function(file, errors) {
var allowStringConcatenation = this._allowStringConcatenation;
Function add
✓ Was called
function add(node) {···
errors.add(
'Illegal use of string concatenation. Use template strings instead.',
node.left
);
}
function add(node) {
errors.add(
'Illegal use of string concatenation. Use template strings instead.',
node.left
);
}
Function (anonymous_1251)
✓ Was called
file.iterateNodesByType('BinaryExpression', function(node) {···
if (node.operator !== '+') {
return;
}

var leftIsString = node.left;
var rightIsString = node.right;

// Left side could also be binary expression (See gh-2050),
// but not the right one
while (leftIsString.type === 'BinaryExpression') {
leftIsString = leftIsString.left;
}

leftIsString = typeof leftIsString.value === 'string' ||
leftIsString.type === 'TemplateLiteral';

rightIsString = typeof rightIsString.value === 'string' ||
rightIsString.type === 'TemplateLiteral';

if (allowStringConcatenation && leftIsString && rightIsString) {
return;
}

// At least one of the operands should be a string or template string,
// otherwise this is not a concatenation
if (leftIsString || rightIsString) {
add(node);
}
});
file.iterateNodesByType('BinaryExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (node.operator !== '+') {···
return;
}
✓ Negative was executed (else)
}···

var leftIsString = node.left;
if (node.operator !== '+') {
return;
}
var leftIsString = node.left;
var rightIsString = node.right;
// Left side could also be binary expression (See gh-2050),
// but not the right one
while (leftIsString.type === 'BinaryExpression') {
leftIsString = leftIsString.left;
}
Branch LogicalExpression
✓ Was returned
leftIsString.type === 'TemplateLiteral';
✓ Was returned
leftIsString = typeof leftIsString.value === 'string' ||
leftIsString = typeof leftIsString.value === 'string' ||
leftIsString.type === 'TemplateLiteral';
Branch LogicalExpression
✓ Was returned
rightIsString.type === 'TemplateLiteral';
✓ Was returned
rightIsString = typeof rightIsString.value === 'string' ||
rightIsString = typeof rightIsString.value === 'string' ||
rightIsString.type === 'TemplateLiteral';
Branch IfStatement
✓ Positive was executed (if)
if (allowStringConcatenation && leftIsString && rightIsString) {···
return;
}
✓ Negative was executed (else)
}···

// At least one of the operands should be a string or template string,
Branch LogicalExpression
✓ Was returned
if (allowStringConcatenation && leftIsString && rightIsString) {
✓ Was returned
if (allowStringConcatenation && leftIsString && rightIsString) {
Branch LogicalExpression
✓ Was returned
if (allowStringConcatenation && leftIsString && rightIsString) {
✓ Was returned
if (allowStringConcatenation && leftIsString && rightIsString) {
if (allowStringConcatenation && leftIsString && rightIsString) {
return;
}
// At least one of the operands should be a string or template string,
// otherwise this is not a concatenation
Branch IfStatement
✓ Positive was executed (if)
if (leftIsString || rightIsString) {···
add(node);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (leftIsString || rightIsString) {
✓ Was returned
if (leftIsString || rightIsString) {
if (leftIsString || rightIsString) {
add(node);
}
});
}
};
require-trailing-comma.js
/**
* Requires an extra comma following the final element of an array or object literal.
*
* Types: `Boolean` or `Object`
*
* Values:
*
* - `true`: validates all arrays and objects
* - `Object`:
* - `ignoreSingleValue`: allows single property objects and single element arrays to not require a trailing comma
* - `ignoreSingleLine`: allows objects and arrays on a single line to not require a trailing comma
*
* #### Example
*
* ```js
* "requireTrailingComma": true
* ```
*
* ##### Valid
*
* ```js
* var foo = [1, 2, 3,];
* var bar = {a: "a", b: "b",}
* ```
*
* ##### Valid with ignoreSingleValue
*
* ```js
* var car = [1];
* var dar = {a: "a"};
* ```
*
* ##### Valid with ignoreSingleLine
*
* ```js
* var car = [1, 2, 3];
* var dar = {a: "a", b: "b"};
* ```
*
* ##### Invalid
*
* ```js
* var foo = [1, 2, 3];
* var bar = {a: "a", b: "b"}
* ```
*/
/* jshint ignore:start */
// jscs:disable
var assert = require('assert');
var cst = require('cst');
var Token = cst.Token;
Function (anonymous_1252)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1253)
✓ Was called
configure: function(options) {···

if (typeof options === 'object') {
if ('ignoreSingleValue' in options) {
assert(
options.ignoreSingleValue === true,
this.getOptionName() + ' option ignoreSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
}
if ('ignoreSingleLine' in options) {
assert(
options.ignoreSingleLine === true,
this.getOptionName() + ' option ignoreSingleLine requires true value or should be removed'
);
this._ignoreSingleLine = true;
}
} else {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
}
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
if ('ignoreSingleValue' in options) {
assert(
options.ignoreSingleValue === true,
this.getOptionName() + ' option ignoreSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
}
if ('ignoreSingleLine' in options) {
assert(
options.ignoreSingleLine === true,
this.getOptionName() + ' option ignoreSingleLine requires true value or should be removed'
);
this._ignoreSingleLine = true;
}
} else {
✓ Negative was executed (else)
} else {···
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
}
if (typeof options === 'object') {
Branch IfStatement
✓ Positive was executed (if)
if ('ignoreSingleValue' in options) {···
assert(
options.ignoreSingleValue === true,
this.getOptionName() + ' option ignoreSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
}
✓ Negative was executed (else)
}···
if ('ignoreSingleLine' in options) {
if ('ignoreSingleValue' in options) {
assert(
options.ignoreSingleValue === true,
this.getOptionName() + ' option ignoreSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
}
Branch IfStatement
✓ Positive was executed (if)
if ('ignoreSingleLine' in options) {···
assert(
options.ignoreSingleLine === true,
this.getOptionName() + ' option ignoreSingleLine requires true value or should be removed'
);
this._ignoreSingleLine = true;
}
✓ Negative was executed (else)
}···
} else {
if ('ignoreSingleLine' in options) {
assert(
options.ignoreSingleLine === true,
this.getOptionName() + ' option ignoreSingleLine requires true value or should be removed'
);
this._ignoreSingleLine = true;
}
} else {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
}
},
Function (anonymous_1254)
✓ Was called
getOptionName: function() {···
return 'requireTrailingComma';
},
getOptionName: function() {
return 'requireTrailingComma';
},
Function (anonymous_1255)
✓ Was called
check: function(file, errors) {···
var _this = this;

file.iterateNodesByType([
'ObjectExpression', 'ArrayExpression',
'ObjectPattern', 'ArrayPattern'
], function(node) {
var isLikeObject = node.type === 'ObjectExpression' || node.type === 'ObjectPattern';
var entities = isLikeObject ? node.properties : node.elements;

if (entities.length === 0) {
return;
}

if (_this._ignoreSingleValue && entities.length === 1) {
return;
}

if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
return;
}

var possibleComma = file.getLastNodeToken(node).getPreviousCodeToken();

if (possibleComma.value !== ',') {
errors.cast({
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
element: possibleComma,
additional: node
});
}
});
},
check: function(file, errors) {
var _this = this;
file.iterateNodesByType([
'ObjectExpression', 'ArrayExpression',
'ObjectPattern', 'ArrayPattern'
Function (anonymous_1256)
✓ Was called
], function(node) {···
var isLikeObject = node.type === 'ObjectExpression' || node.type === 'ObjectPattern';
var entities = isLikeObject ? node.properties : node.elements;

if (entities.length === 0) {
return;
}

if (_this._ignoreSingleValue && entities.length === 1) {
return;
}

if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
return;
}

var possibleComma = file.getLastNodeToken(node).getPreviousCodeToken();

if (possibleComma.value !== ',') {
errors.cast({
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
element: possibleComma,
additional: node
});
}
});
], function(node) {
Branch LogicalExpression
✓ Was returned
var isLikeObject = node.type === 'ObjectExpression' || node.type === 'ObjectPattern';
✓ Was returned
var isLikeObject = node.type === 'ObjectExpression' || node.type === 'ObjectPattern';
var isLikeObject = node.type === 'ObjectExpression' || node.type === 'ObjectPattern';
Branch ConditionalExpression
✓ Positive was returned (? ...)
var entities = isLikeObject ? node.properties : node.elements;
✓ Negative was returned (: ...)
var entities = isLikeObject ? node.properties : node.elements;
var entities = isLikeObject ? node.properties : node.elements;
Branch IfStatement
✓ Positive was executed (if)
if (entities.length === 0) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._ignoreSingleValue && entities.length === 1) {
if (entities.length === 0) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._ignoreSingleValue && entities.length === 1) {···
return;
}
✓ Negative was executed (else)
}···

if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
Branch LogicalExpression
✓ Was returned
if (_this._ignoreSingleValue && entities.length === 1) {
✓ Was returned
if (_this._ignoreSingleValue && entities.length === 1) {
if (_this._ignoreSingleValue && entities.length === 1) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {···
return;
}
✓ Negative was executed (else)
}···

var possibleComma = file.getLastNodeToken(node).getPreviousCodeToken();
Branch LogicalExpression
✓ Was returned
if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
✓ Was returned
if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
if (_this._ignoreSingleLine && node.getNewlineCount() === 0) {
return;
}
var possibleComma = file.getLastNodeToken(node).getPreviousCodeToken();
Branch IfStatement
✓ Positive was executed (if)
if (possibleComma.value !== ',') {···
errors.cast({
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
element: possibleComma,
additional: node
});
}
✓ Negative was executed (else)
}···
});
if (possibleComma.value !== ',') {
errors.cast({
Branch ConditionalExpression
✓ Positive was returned (? ...)
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
✓ Negative was returned (: ...)
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
message: 'Missing comma before closing ' + (isLikeObject ? 'curly brace' : 'bracket'),
element: possibleComma,
additional: node
});
}
});
},
Function (anonymous_1257)
✓ Was called
_fix: function(file, error) {···
var parent = error.additional;
var afterProp;

// ArrayPattern/ArrayExpression
if (parent.type.indexOf('Array') === 0) {
afterProp = parent.elements[parent.elements.length - 1].lastChild.getNextToken();

// ObjectExpression/ObjectPattern
} else {
afterProp = parent.properties[parent.properties.length - 1].lastChild.getNextToken();
}

parent.insertChildBefore(new Token('Punctuator', ','), afterProp);
}
_fix: function(file, error) {
var parent = error.additional;
var afterProp;
// ArrayPattern/ArrayExpression
Branch IfStatement
✓ Positive was executed (if)
if (parent.type.indexOf('Array') === 0) {···
afterProp = parent.elements[parent.elements.length - 1].lastChild.getNextToken();

// ObjectExpression/ObjectPattern
} else {
✓ Negative was executed (else)
} else {···
afterProp = parent.properties[parent.properties.length - 1].lastChild.getNextToken();
}
if (parent.type.indexOf('Array') === 0) {
afterProp = parent.elements[parent.elements.length - 1].lastChild.getNextToken();
// ObjectExpression/ObjectPattern
} else {
afterProp = parent.properties[parent.properties.length - 1].lastChild.getNextToken();
}
parent.insertChildBefore(new Token('Punctuator', ','), afterProp);
}
};
require-use-strict.js
/**
* Requires `'use strict';` statements
*
* Values:
* - `true` for default behavior (require 'use strict' statements for files)
*
* #### Example
*
* ```js
* "requireUseStrict": true
* ```
*
* ##### Valid
*
* ```js
* 'use strict';
* // code
* ```
*
* ```js
* // comment line or block
* 'use strict';
* // code
* ```
*
* ```js
* // comment line or block
*
* 'use strict';
* // code
* ```
*
* ##### Invalid
*
* ```js
* // code
* ```
*/
var assert = require('assert');
Function (anonymous_1258)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1259)
✓ Was called
configure: function(options) {···
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {files: true};
return this.configure(_options);
}

this._checkFiles = (options.files === true);
},
configure: function(options) {
Branch IfStatement
✓ Positive was executed (if)
if (typeof options !== 'object') {···
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);

var _options = {files: true};
return this.configure(_options);
}
✓ Negative was executed (else)
}···

this._checkFiles = (options.files === true);
if (typeof options !== 'object') {
assert(
options === true,
this.getOptionName() + ' option requires either a true value or an object'
);
var _options = {files: true};
return this.configure(_options);
}
this._checkFiles = (options.files === true);
},
Function (anonymous_1260)
✓ Was called
getOptionName: function() {···
return 'requireUseStrict';
},
getOptionName: function() {
return 'requireUseStrict';
},
Function (anonymous_1261)
✓ Was called
check: function(file, errors) {···
var program = file.getProgram();
var directive = program.directives[0];

if (directive) {
return;
}

errors.add(
'`"use strict";` is required at the top of each file',
program
);
}
check: function(file, errors) {
var program = file.getProgram();
var directive = program.directives[0];
Branch IfStatement
✓ Positive was executed (if)
if (directive) {···
return;
}
✓ Negative was executed (else)
}···

errors.add(
if (directive) {
return;
}
errors.add(
'`"use strict";` is required at the top of each file',
program
);
}
};
require-var-decl-first.js
/**
* Requires `var` declaration to be on the top of an enclosing scope
*
* Types: `Boolean`
*
* Values:
*
* - `true` specifies that `var` declarations must occur the top of a function scope.
*
* #### Example
*
* ```js
* "requireVarDeclFirst": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = 1,
* y = 2;
* ```
* ```js
* 'use strict;'
* var x = 1,
* y = 2;
* ```
* ```js
* var x = 1;
* var y = 2;
* ```
* ```js
* var x = 1;
* // comments
* var y = 2;
* ```
* ```js
* var x = 1;
* // comments
* // comments 2
* var y = 2;
* ```
* ```js
* const a = 1;
* const b = 2;
* ```
* ```js
* var x = 1;
* function y() {var z;};
* ```
* ```js
* var x = 1;
* var y = function () {var z;};
* ```
* ```js
* var w = 1;
* function x() {
* var y;
* // comments
* // comments 2
* var z;
* };
* ```
* ```js
* var w = 1;
* function x() {
* "use strict";
* var y;
* };
* ```
* ```js
* var x = 1;
* var y;
* for (y = 0; y < 10; y++) {};
* ```
*
* ##### Invalid
*
* ```js
* var x;
* x = 1;
* var y = 2;
* ```
* ```js
* var w = 1;
* function x() {var y;};
* var z = 2;
* ```
* ```js
* var w = 1;
* function x() {
* var y;
* y = 2;
* var z;
* };
* ```
* ```js
* var a;
* for(var count=0;count < 10;count++){}
* ```
* ```js
* var x;
* for(var count=0;count < 10;count++){
* var y;
* }
* ```
*
*/
var assert = require('assert');
Function isScopeElement
✓ Was called
function isScopeElement(elem) {···
return elem.type === 'Program' ||
elem.type === 'BlockStatement' && (
elem.parentElement.type === 'FunctionExpression' ||
elem.parentElement.type === 'FunctionDeclaration' ||
elem.parentElement.type === 'ArrowFunctionExpression'
);
}
function isScopeElement(elem) {
Branch LogicalExpression
✓ Was returned
elem.type === 'BlockStatement' && (···
elem.parentElement.type === 'FunctionExpression' ||
elem.parentElement.type === 'FunctionDeclaration' ||
elem.parentElement.type === 'ArrowFunctionExpression'
);
✓ Was returned
return elem.type === 'Program' ||
return elem.type === 'Program' ||
Branch LogicalExpression
✓ Was returned
elem.parentElement.type === 'FunctionExpression' ||···
elem.parentElement.type === 'FunctionDeclaration' ||
elem.parentElement.type === 'ArrowFunctionExpression'
✗ Was not returned
elem.type === 'BlockStatement' && (
elem.type === 'BlockStatement' && (
Branch LogicalExpression
✓ Was returned
elem.parentElement.type === 'ArrowFunctionExpression'
✓ Was returned
elem.parentElement.type === 'FunctionExpression' ||···
elem.parentElement.type === 'FunctionDeclaration' ||
Branch LogicalExpression
✓ Was returned
elem.parentElement.type === 'FunctionDeclaration' ||
✓ Was returned
elem.parentElement.type === 'FunctionExpression' ||
elem.parentElement.type === 'FunctionExpression' ||
elem.parentElement.type === 'FunctionDeclaration' ||
elem.parentElement.type === 'ArrowFunctionExpression'
);
}
/**
* Checks for allowed elements before variable declaration.
*
* @param {Object} elem
* @returns {Boolean}
*/
Function isRelevantElement
✓ Was called
function isRelevantElement(elem) {···
// Allow comments and whitespaces.
var itIs = elem.isComment || elem.isWhitespace;

// Variable declaration itself.
itIs = itIs || elem.type === 'VariableDeclaration';

// For '{' in `function() { var a; }`.
itIs = itIs || elem.type === 'Punctuator';

// Skip 'use strict' statements at the beginning.
itIs = itIs || elem.type === 'Directive';

return itIs;
}
function isRelevantElement(elem) {
// Allow comments and whitespaces.
Branch LogicalExpression
✓ Was returned
var itIs = elem.isComment || elem.isWhitespace;
✓ Was returned
var itIs = elem.isComment || elem.isWhitespace;
var itIs = elem.isComment || elem.isWhitespace;
// Variable declaration itself.
Branch LogicalExpression
✓ Was returned
itIs = itIs || elem.type === 'VariableDeclaration';
✓ Was returned
itIs = itIs || elem.type === 'VariableDeclaration';
itIs = itIs || elem.type === 'VariableDeclaration';
// For '{' in `function() { var a; }`.
Branch LogicalExpression
✓ Was returned
itIs = itIs || elem.type === 'Punctuator';
✓ Was returned
itIs = itIs || elem.type === 'Punctuator';
itIs = itIs || elem.type === 'Punctuator';
// Skip 'use strict' statements at the beginning.
Branch LogicalExpression
✓ Was returned
itIs = itIs || elem.type === 'Directive';
✓ Was returned
itIs = itIs || elem.type === 'Directive';
itIs = itIs || elem.type === 'Directive';
return itIs;
}
Function isVarDeclFirst
✓ Was called
function isVarDeclFirst(varDecl) {···
var elem = varDecl;

// All elements should be relevant.
while (elem && isRelevantElement(elem)) {
elem = elem.previousSibling;
}

return elem === null;
}
function isVarDeclFirst(varDecl) {
var elem = varDecl;
// All elements should be relevant.
Branch LogicalExpression
✓ Was returned
while (elem && isRelevantElement(elem)) {
✓ Was returned
while (elem && isRelevantElement(elem)) {
while (elem && isRelevantElement(elem)) {
elem = elem.previousSibling;
}
return elem === null;
}
Function (anonymous_1265)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1266)
✓ Was called
configure: function(options) {···
assert(
options === true,
this.getOptionName() + ' option requires a true value'
);
},
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value'
);
},
Function (anonymous_1267)
✓ Was called
getOptionName: function() {···
return 'requireVarDeclFirst';
},
getOptionName: function() {
return 'requireVarDeclFirst';
},
Function (anonymous_1268)
✓ Was called
check: function(file, errors) {···
file.iterateNodesByType(['VariableDeclaration'], function(varDecl) {
// Ignore let and const for now #1783
if (varDecl.kind !== 'var') {
return;
}

// Checking scope to not allow vars inside block statements.
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {
return;
}

errors.add('Variable declarations must be the first statements of a function scope.',
varDecl);
});
}
check: function(file, errors) {
Function (anonymous_1269)
✓ Was called
file.iterateNodesByType(['VariableDeclaration'], function(varDecl) {···
// Ignore let and const for now #1783
if (varDecl.kind !== 'var') {
return;
}

// Checking scope to not allow vars inside block statements.
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {
return;
}

errors.add('Variable declarations must be the first statements of a function scope.',
varDecl);
});
file.iterateNodesByType(['VariableDeclaration'], function(varDecl) {
// Ignore let and const for now #1783
Branch IfStatement
✗ Positive was not executed (if)
if (varDecl.kind !== 'var') {···
return;
}
✓ Negative was executed (else)
}···

// Checking scope to not allow vars inside block statements.
if (varDecl.kind !== 'var') {
return;
}
// Checking scope to not allow vars inside block statements.
Branch IfStatement
✓ Positive was executed (if)
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {···
return;
}
✓ Negative was executed (else)
}···

errors.add('Variable declarations must be the first statements of a function scope.',
Branch LogicalExpression
✓ Was returned
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {
✓ Was returned
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {
if (isScopeElement(varDecl.parentElement) && isVarDeclFirst(varDecl)) {
return;
}
errors.add('Variable declarations must be the first statements of a function scope.',
varDecl);
});
}
};
require-yoda-conditions.js
/**
* Requires the variable to be the right hand operator when doing a boolean comparison
*
* Types: `Array` or `Boolean`
*
* Values:
* - `true` specifies that yoda conditions are required for most possible comparison operators
* - `Array`: represents the list of quoted operators that requires yoda conditions
*
* #### Example
*
* ```js
* "requireYodaConditions": true
* ```
* ```js
* "requireYodaConditions": [
* "==",
* "===",
* "!=",
* "!=="
* ]
* ```
*
* ##### Valid for mode `true` or `['==']`
* ```js
* if (1 == a) {
* return
* }
* ```
*
* ##### Invalid for mode `true` or `['==']`
*
* ```js
* if (a == 1) {
* return
* }
* ```
*/
var assert = require('assert');
Function (anonymous_1270)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1271)
✓ Was called
configure: function(operators) {···
var isTrue = operators === true;

assert(
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);

if (isTrue) {
operators = ['==', '===', '!=', '!=='];
}

this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
configure: function(operators) {
var isTrue = operators === true;
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(operators) || isTrue,
✓ Was returned
Array.isArray(operators) || isTrue,
Array.isArray(operators) || isTrue,
this.getOptionName() + ' option requires array or true value'
);
Branch IfStatement
✓ Positive was executed (if)
if (isTrue) {···
operators = ['==', '===', '!=', '!=='];
}
✓ Negative was executed (else)
}···

this._operatorIndex = {};
if (isTrue) {
operators = ['==', '===', '!=', '!=='];
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
Function (anonymous_1272)
✓ Was called
getOptionName: function() {···
return 'requireYodaConditions';
},
getOptionName: function() {
return 'requireYodaConditions';
},
Function (anonymous_1273)
✓ Was called
check: function(file, errors) {···
var operators = this._operatorIndex;
file.iterateNodesByType('BinaryExpression', function(node) {
if (operators[node.operator]) {
if (
node.right.type.indexOf('Literal') > -1 ||
(node.right.type === 'Identifier' && node.right.name === 'undefined')
) {
errors.add('Not yoda condition', node.left);
}
}
});
}
check: function(file, errors) {
var operators = this._operatorIndex;
Function (anonymous_1274)
✓ Was called
file.iterateNodesByType('BinaryExpression', function(node) {···
if (operators[node.operator]) {
if (
node.right.type.indexOf('Literal') > -1 ||
(node.right.type === 'Identifier' && node.right.name === 'undefined')
) {
errors.add('Not yoda condition', node.left);
}
}
});
file.iterateNodesByType('BinaryExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
if (operators[node.operator]) {···
if (
node.right.type.indexOf('Literal') > -1 ||
(node.right.type === 'Identifier' && node.right.name === 'undefined')
) {
errors.add('Not yoda condition', node.left);
}
}
✓ Negative was executed (else)
}···
});
if (operators[node.operator]) {
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add('Not yoda condition', node.left);
}
✓ Negative was executed (else)
}···
}
if (
Branch LogicalExpression
✓ Was returned
(node.right.type === 'Identifier' && node.right.name === 'undefined')
✓ Was returned
node.right.type.indexOf('Literal') > -1 ||
node.right.type.indexOf('Literal') > -1 ||
Branch LogicalExpression
✓ Was returned
(node.right.type === 'Identifier' && node.right.name === 'undefined')
✓ Was returned
(node.right.type === 'Identifier' && node.right.name === 'undefined')
(node.right.type === 'Identifier' && node.right.name === 'undefined')
) {
errors.add('Not yoda condition', node.left);
}
}
});
}
};
safe-context-keyword.js
/**
* Option to check `var that = this` expressions
*
* Types: `String`, `Array`
*
* Values:
* - `String`: represents the keyword that can assigned to `this` context
* - `Array`: represents the list of keywords that can assigned to `this` context
*
* #### Example
*
* ```js
* "safeContextKeyword": ["that"]
* ```
*
* ##### Valid for mode `["that"]`
*
* ```js
* var that = this;
* ```
*
* ##### Invalid for mode `["that"]`
*
* ```js
* var _this = this;
* ```
*/
var assert = require('assert');
Function (anonymous_1275)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1276)
✓ Was called
configure: function(keywords) {···
assert(
Array.isArray(keywords) || typeof keywords === 'string',
this.getOptionName() + ' option requires string or array value'
);

this._keywords = keywords;
},
configure: function(keywords) {
assert(
Branch LogicalExpression
✓ Was returned
Array.isArray(keywords) || typeof keywords === 'string',
✓ Was returned
Array.isArray(keywords) || typeof keywords === 'string',
Array.isArray(keywords) || typeof keywords === 'string',
this.getOptionName() + ' option requires string or array value'
);
this._keywords = keywords;
},
Function (anonymous_1277)
✓ Was called
getOptionName: function() {···
return 'safeContextKeyword';
},
getOptionName: function() {
return 'safeContextKeyword';
},
Function (anonymous_1278)
✓ Was called
check: function(file, errors) {···
var keywords = typeof this._keywords === 'string' ? [this._keywords] : this._keywords;

// var that = this
file.iterateNodesByType('VariableDeclaration', function(node) {

for (var i = 0; i < node.declarations.length; i++) {
var decl = node.declarations[i];

// Miss destructing assignment (#1699, #2119)
if (decl.firstChild.type === 'ObjectPattern') {
continue;
}

// decl.init === null in case of "var foo;"
if (decl.init &&
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
}
});

// that = this
file.iterateNodesByType('AssignmentExpression', function(node) {

if (
// filter property assignments "foo.bar = this"
node.left.type === 'Identifier' &&
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
});
}
check: function(file, errors) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
var keywords = typeof this._keywords === 'string' ? [this._keywords] : this._keywords;
✓ Negative was returned (: ...)
var keywords = typeof this._keywords === 'string' ? [this._keywords] : this._keywords;
var keywords = typeof this._keywords === 'string' ? [this._keywords] : this._keywords;
// var that = this
Function (anonymous_1279)
✓ Was called
file.iterateNodesByType('VariableDeclaration', function(node) {···

for (var i = 0; i < node.declarations.length; i++) {
var decl = node.declarations[i];

// Miss destructing assignment (#1699, #2119)
if (decl.firstChild.type === 'ObjectPattern') {
continue;
}

// decl.init === null in case of "var foo;"
if (decl.init &&
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
}
});
file.iterateNodesByType('VariableDeclaration', function(node) {
for (var i = 0; i < node.declarations.length; i++) {
var decl = node.declarations[i];
// Miss destructing assignment (#1699, #2119)
Branch IfStatement
✓ Positive was executed (if)
if (decl.firstChild.type === 'ObjectPattern') {···
continue;
}
✓ Negative was executed (else)
}···

// decl.init === null in case of "var foo;"
if (decl.firstChild.type === 'ObjectPattern') {
continue;
}
// decl.init === null in case of "var foo;"
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
✓ Was returned
if (decl.init &&
if (decl.init &&
Branch LogicalExpression
✓ Was returned
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
✓ Was returned
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
(decl.init.type === 'ThisExpression' && checkKeywords(decl.id.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
}
});
// that = this
Function (anonymous_1280)
✓ Was called
file.iterateNodesByType('AssignmentExpression', function(node) {···

if (
// filter property assignments "foo.bar = this"
node.left.type === 'Identifier' &&
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
});
file.iterateNodesByType('AssignmentExpression', function(node) {
Branch IfStatement
✓ Positive was executed (if)
) {···
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
✓ Negative was executed (else)
}···
});
if (
// filter property assignments "foo.bar = this"
Branch LogicalExpression
✓ Was returned
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
✓ Was returned
node.left.type === 'Identifier' &&
node.left.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
✓ Was returned
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
(node.right.type === 'ThisExpression' && checkKeywords(node.left.name, keywords))
) {
errors.add(
'You should use "' + keywords.join('" or "') + '" to save a reference to "this"',
node
);
}
});
}
};
/**
* Check if at least one keyword equals to passed name.
*
* @param {String} name
* @param {Array} keywords
* @return {Boolean}
*/
Function checkKeywords
✓ Was called
function checkKeywords(name, keywords) {···
for (var i = 0; i < keywords.length; i++) {
if (name === keywords[i]) {
return false;
}
}

return true;
}
function checkKeywords(name, keywords) {
for (var i = 0; i < keywords.length; i++) {
Branch IfStatement
✓ Positive was executed (if)
if (name === keywords[i]) {···
return false;
}
✓ Negative was executed (else)
}···
}
if (name === keywords[i]) {
return false;
}
}
return true;
}
validate-aligned-function-parameters.js
/**
* Validates proper alignment of function parameters.
*
* Types: `Boolean`, `Object`
*
* Values:
* - `true`: setting this is the same as validating the rule using
* `{lineBreakAfterOpeningBrace: true, lineBreakBeforeClosingBrace: true}`
* - `Object`:
* - `lineBreakAfterOpeningBrace`
* - `true` specifies that the first function parameter must not be on the same line as the opening brace `(`
* of the function parameters list
* - `lineBreakBeforeClosingBrace`
* - `true` specifies that the last function parameter must not be on the same line as the closing brace `)`
* of the function parameters list
*
* #### Example
*
* ```js
* "validateAlignedFunctionParameters": {
* "lineBreakAfterOpeningBrace": true,
* "lineBreakBeforeClosingBrace": true
* }
* ```
*
* ##### Valid for mode `{ "lineBreakAfterOpeningBrace": true, "lineBreakBeforeClosingBrace": true}`
* ```js
* function (
* thisIs,
* theLongestList,
* ofParametersEverWritten
* ) {}
* ```
* ##### Invalid for mode `{ "lineBreakAfterOpeningBrace": true, "lineBreakBeforeClosingBrace": true}`
* ```js
* function (thisIs,
* theLongestList,
* ofParametersEverWritten) {}
* ```
*/
var assert = require('assert');
Function (anonymous_1282)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1283)
✓ Was called
configure: function(options) {···
var validProperties = [
'lineBreakAfterOpeningBrace',
'lineBreakBeforeClosingBrace'
];
var optionName = this.getOptionName();

assert(
typeof options === 'object' || options === true,
optionName + ' option must be an object or boolean true'
);

if (typeof options === 'object') {
validProperties.forEach(function(key) {
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
});

validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
}
},
configure: function(options) {
var validProperties = [
'lineBreakAfterOpeningBrace',
'lineBreakBeforeClosingBrace'
];
var optionName = this.getOptionName();
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'object' || options === true,
✓ Was returned
typeof options === 'object' || options === true,
typeof options === 'object' || options === true,
optionName + ' option must be an object or boolean true'
);
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
validProperties.forEach(function(key) {
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
});

validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
}
✓ Negative was executed (else)
}···
},
if (typeof options === 'object') {
Function (anonymous_1284)
✓ Was called
validProperties.forEach(function(key) {···
var isPresent = key in options;

if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
});
validProperties.forEach(function(key) {
var isPresent = key in options;
Branch IfStatement
✓ Positive was executed (if)
if (isPresent) {···
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
✓ Negative was executed (else)
}···
});
if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
});
Function (anonymous_1285)
✓ Was called
validProperties.forEach(function(property) {···
this['_' + property] = Boolean(options[property]);
}.bind(this));
validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
}
},
Function (anonymous_1286)
✓ Was called
getOptionName: function() {···
return 'validateAlignedFunctionParameters';
},
getOptionName: function() {
return 'validateAlignedFunctionParameters';
},
Function (anonymous_1287)
✓ Was called
check: function(file, errors) {···
var lineBreakAfterOpeningBrace = this._lineBreakAfterOpeningBrace;
var lineBreakBeforeClosingBrace = this._lineBreakBeforeClosingBrace;

file.iterateNodesByType([
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression'
], function(node) {

// ignore this rule if there are no parameters
if (node.params.length === 0) {
return;
}

// ignore this rule if the parameters are not multi-line
var firstParameter = file.getFirstNodeToken(node.params[0]);
var lastParameter = node.params[node.params.length - 1];
if (file.isOnTheSameLine(firstParameter, lastParameter)) {
return;
}

// look for the furthest parameter start position
var maxParamStartPos = 0;
node.params.forEach(function(parameter) {
maxParamStartPos = Math.max(maxParamStartPos, parameter.getLoc().start.column);
});

// make sure all parameters are lined up
node.params.forEach(function(parameter) {
if (parameter.getLoc().start.column !== maxParamStartPos) {
errors.add('Multi-line parameters are not aligned.', parameter);
}
});

// make sure the first parameter is on a new line
if (lineBreakAfterOpeningBrace) {
var openingBrace = file.getPrevToken(firstParameter);
errors.assert.differentLine({
token: openingBrace,
nextToken: firstParameter,
message: 'There is no line break after the opening brace'
});
}

// make sure the closing brace is on a new line
if (lineBreakBeforeClosingBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
var closingBrace = file.getPrevToken(bodyToken);
errors.assert.differentLine({
token: lastParameter,
nextToken: closingBrace,
message: 'There is no line break before the closing brace'
});
}

});
}
check: function(file, errors) {
var lineBreakAfterOpeningBrace = this._lineBreakAfterOpeningBrace;
var lineBreakBeforeClosingBrace = this._lineBreakBeforeClosingBrace;
file.iterateNodesByType([
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression'
Function (anonymous_1288)
✓ Was called
], function(node) {···

// ignore this rule if there are no parameters
if (node.params.length === 0) {
return;
}

// ignore this rule if the parameters are not multi-line
var firstParameter = file.getFirstNodeToken(node.params[0]);
var lastParameter = node.params[node.params.length - 1];
if (file.isOnTheSameLine(firstParameter, lastParameter)) {
return;
}

// look for the furthest parameter start position
var maxParamStartPos = 0;
node.params.forEach(function(parameter) {
maxParamStartPos = Math.max(maxParamStartPos, parameter.getLoc().start.column);
});

// make sure all parameters are lined up
node.params.forEach(function(parameter) {
if (parameter.getLoc().start.column !== maxParamStartPos) {
errors.add('Multi-line parameters are not aligned.', parameter);
}
});

// make sure the first parameter is on a new line
if (lineBreakAfterOpeningBrace) {
var openingBrace = file.getPrevToken(firstParameter);
errors.assert.differentLine({
token: openingBrace,
nextToken: firstParameter,
message: 'There is no line break after the opening brace'
});
}

// make sure the closing brace is on a new line
if (lineBreakBeforeClosingBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
var closingBrace = file.getPrevToken(bodyToken);
errors.assert.differentLine({
token: lastParameter,
nextToken: closingBrace,
message: 'There is no line break before the closing brace'
});
}

});
], function(node) {
// ignore this rule if there are no parameters
Branch IfStatement
✓ Positive was executed (if)
if (node.params.length === 0) {···
return;
}
✓ Negative was executed (else)
}···

// ignore this rule if the parameters are not multi-line
if (node.params.length === 0) {
return;
}
// ignore this rule if the parameters are not multi-line
var firstParameter = file.getFirstNodeToken(node.params[0]);
var lastParameter = node.params[node.params.length - 1];
Branch IfStatement
✓ Positive was executed (if)
if (file.isOnTheSameLine(firstParameter, lastParameter)) {···
return;
}
✓ Negative was executed (else)
}···

// look for the furthest parameter start position
if (file.isOnTheSameLine(firstParameter, lastParameter)) {
return;
}
// look for the furthest parameter start position
var maxParamStartPos = 0;
Function (anonymous_1289)
✓ Was called
node.params.forEach(function(parameter) {···
maxParamStartPos = Math.max(maxParamStartPos, parameter.getLoc().start.column);
});
node.params.forEach(function(parameter) {
maxParamStartPos = Math.max(maxParamStartPos, parameter.getLoc().start.column);
});
// make sure all parameters are lined up
Function (anonymous_1290)
✓ Was called
node.params.forEach(function(parameter) {···
if (parameter.getLoc().start.column !== maxParamStartPos) {
errors.add('Multi-line parameters are not aligned.', parameter);
}
});
node.params.forEach(function(parameter) {
Branch IfStatement
✓ Positive was executed (if)
if (parameter.getLoc().start.column !== maxParamStartPos) {···
errors.add('Multi-line parameters are not aligned.', parameter);
}
✓ Negative was executed (else)
}···
});
if (parameter.getLoc().start.column !== maxParamStartPos) {
errors.add('Multi-line parameters are not aligned.', parameter);
}
});
// make sure the first parameter is on a new line
Branch IfStatement
✓ Positive was executed (if)
if (lineBreakAfterOpeningBrace) {···
var openingBrace = file.getPrevToken(firstParameter);
errors.assert.differentLine({
token: openingBrace,
nextToken: firstParameter,
message: 'There is no line break after the opening brace'
});
}
✓ Negative was executed (else)
}···

// make sure the closing brace is on a new line
if (lineBreakAfterOpeningBrace) {
var openingBrace = file.getPrevToken(firstParameter);
errors.assert.differentLine({
token: openingBrace,
nextToken: firstParameter,
message: 'There is no line break after the opening brace'
});
}
// make sure the closing brace is on a new line
Branch IfStatement
✓ Positive was executed (if)
if (lineBreakBeforeClosingBrace) {···
var bodyToken = file.getFirstNodeToken(node.body);
var closingBrace = file.getPrevToken(bodyToken);
errors.assert.differentLine({
token: lastParameter,
nextToken: closingBrace,
message: 'There is no line break before the closing brace'
});
}
✓ Negative was executed (else)
}···

});
if (lineBreakBeforeClosingBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
var closingBrace = file.getPrevToken(bodyToken);
errors.assert.differentLine({
token: lastParameter,
nextToken: closingBrace,
message: 'There is no line break before the closing brace'
});
}
});
}
};
validate-comment-position.js
/**
* This rule is for validating the positioning of line comments. Block comments are ignored.
*
* Comments that start with the following keywords are also ignored:
* `eslint`, `jshint`, `jslint`, `istanbul`, `global`, `exported`, `jscs`, `falls through`
* eg. // jshint strict: true
*
* Type: `Object`
*
* Value:
*
* - `Object`:
* - `position`: `above` or `beside`
* - `allExcept`: array of quoted exceptions (comments that start with these values will be excepted)
*
* #### Example
*
* ```js
* "validateCommentPosition": { position: `above`, allExcept: [`pragma`] }
* ```
*
* ##### Valid
*
* ```js
* // This is a valid comment
* 1 + 1;
* ```
*
* ##### Invalid
*
* ```js
* 1 + 1; // This is an invalid comment
* 2 + 2; // pragma (this comment is fine)
* ```
*
* ```js
* "validateCommentPosition": { position: `beside` }
* ```
*
* ##### Valid
*
* ```js
* 1 + 1; // This is a valid comment
* ```
*
* ##### Invalid
*
* ```js
* // This is an invalid comment
* 1 + 1;
* ```
*/
var assert = require('assert');
var isPragma = require('../utils').isPragma;
Function (anonymous_1291)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1292)
✓ Was called
configure: function(options) {···
var validPositions = {
'above': 'above',
'beside': 'beside'
};
var allExcept = options.allExcept;
assert(
typeof options === 'object' && validPositions[options.position],
this.getOptionName() + ' requires one of the following values: ' + Object.keys(validPositions).join(', ')
);
if (Array.isArray(allExcept)) {
assert(
allExcept.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + allExcept + ' should be an array of strings'
);
this._isExcepted = isPragma(allExcept);
} else {
this._isExcepted = isPragma();
}
this._position = options.position;
},
configure: function(options) {
var validPositions = {
'above': 'above',
'beside': 'beside'
};
var allExcept = options.allExcept;
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'object' && validPositions[options.position],
✓ Was returned
typeof options === 'object' && validPositions[options.position],
typeof options === 'object' && validPositions[options.position],
this.getOptionName() + ' requires one of the following values: ' + Object.keys(validPositions).join(', ')
);
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(allExcept)) {···
assert(
allExcept.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + allExcept + ' should be an array of strings'
);
this._isExcepted = isPragma(allExcept);
} else {
✓ Negative was executed (else)
} else {···
this._isExcepted = isPragma();
}
if (Array.isArray(allExcept)) {
assert(
Function (anonymous_1293)
✓ Was called
allExcept.every(function(el) { return typeof el === 'string'; }),
allExcept.every(function(el) { return typeof el === 'string'; }),
'Property `allExcept` in ' + allExcept + ' should be an array of strings'
);
this._isExcepted = isPragma(allExcept);
} else {
this._isExcepted = isPragma();
}
this._position = options.position;
},
Function (anonymous_1294)
✓ Was called
getOptionName: function() {···
return 'validateCommentPosition';
},
getOptionName: function() {
return 'validateCommentPosition';
},
Function (anonymous_1295)
✓ Was called
check: function(file, errors) {···
var position = this._position;
var isExcepted = this._isExcepted;
file.iterateTokensByType('CommentLine', function(comment) {
if (isExcepted(comment.value)) {
return;
}

var isFirstToken = true;
var currentToken = comment.getPreviousToken();
while (currentToken) {
if (currentToken.isWhitespace) {
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
isFirstToken = false;
}

currentToken = currentToken.getPreviousToken();
}

if (position === 'above' && !isFirstToken) {
errors.add('Expected comments to be above the code not beside', comment);
}
if (position === 'beside' && isFirstToken) {
errors.add('Expected comments to be beside the code not above', comment);
}
});
}
check: function(file, errors) {
var position = this._position;
var isExcepted = this._isExcepted;
Function (anonymous_1296)
✓ Was called
file.iterateTokensByType('CommentLine', function(comment) {···
if (isExcepted(comment.value)) {
return;
}

var isFirstToken = true;
var currentToken = comment.getPreviousToken();
while (currentToken) {
if (currentToken.isWhitespace) {
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
isFirstToken = false;
}

currentToken = currentToken.getPreviousToken();
}

if (position === 'above' && !isFirstToken) {
errors.add('Expected comments to be above the code not beside', comment);
}
if (position === 'beside' && isFirstToken) {
errors.add('Expected comments to be beside the code not above', comment);
}
});
file.iterateTokensByType('CommentLine', function(comment) {
Branch IfStatement
✓ Positive was executed (if)
if (isExcepted(comment.value)) {···
return;
}
✓ Negative was executed (else)
}···

var isFirstToken = true;
if (isExcepted(comment.value)) {
return;
}
var isFirstToken = true;
var currentToken = comment.getPreviousToken();
while (currentToken) {
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isWhitespace) {···
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
✓ Negative was executed (else)
} else {···
isFirstToken = false;
}
if (currentToken.isWhitespace) {
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.getNewlineCount() > 0) {···
break;
}
✓ Negative was executed (else)
}···
} else {
if (currentToken.getNewlineCount() > 0) {
break;
}
} else {
isFirstToken = false;
}
currentToken = currentToken.getPreviousToken();
}
Branch IfStatement
✓ Positive was executed (if)
if (position === 'above' && !isFirstToken) {···
errors.add('Expected comments to be above the code not beside', comment);
}
✓ Negative was executed (else)
}···
if (position === 'beside' && isFirstToken) {
Branch LogicalExpression
✓ Was returned
if (position === 'above' && !isFirstToken) {
✓ Was returned
if (position === 'above' && !isFirstToken) {
if (position === 'above' && !isFirstToken) {
errors.add('Expected comments to be above the code not beside', comment);
}
Branch IfStatement
✓ Positive was executed (if)
if (position === 'beside' && isFirstToken) {···
errors.add('Expected comments to be beside the code not above', comment);
}
✓ Negative was executed (else)
}···
});
Branch LogicalExpression
✓ Was returned
if (position === 'beside' && isFirstToken) {
✓ Was returned
if (position === 'beside' && isFirstToken) {
if (position === 'beside' && isFirstToken) {
errors.add('Expected comments to be beside the code not above', comment);
}
});
}
};
validate-indentation.js
/**
* Validates indentation for switch statements and block statements
*
* Types: `Integer`, `String` or `Object`
*
* Values:
* - `Integer`: A positive number of spaces
* - `String`: `"\t"` for tab indentation
* - `Object`:
* - `value`: (required) the same effect as the non-object values
* - `includeEmptyLines` (*deprecated*): (default: `false`) require empty lines to be indented
* - `'allExcept'` array of exceptions:
* - `'comments'` ignores comments
* - `'emptyLines'` ignore empty lines, included by default
*
* JSHint: [`indent`](http://jshint.com/docs/options/#indent)
*
* #### Example
*
* ```js
* "validateIndentation": "\t"
* ```
*
* ##### Valid example for mode `2`
*
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
* }
* ```
*
* ##### Invalid example for mode `2`
*
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
* }
* ```
*
* ##### Valid example for mode `"\t"`
*
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
* }
* ```
*
* ##### Invalid example for mode `"\t"`
*
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
* }
* ```
*
* ##### Valid example for mode `{ "value": "\t", "allExcept": ["emptyLines"] }`
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
*
* } // single tab character on previous line
* ```
*
* ##### Invalid example for mode `{ "value": "\t", "allExcept": ["emptyLines"] } }`
* ```js
* if (a) {
* b=c;
* function(d) {
* e=f;
* }
*
* } // no tab character on previous line
* ```
*
* ##### Valid example for mode `{ "value": "\t", "allExcept": ["comments"] }`
* ```js
* if (a) {
* b=c;
* // e=f
* }
* ```
*/
var assert = require('assert');
var cst = require('cst');
var nonBlockIndentChecks = {
'IfStatement': ['consequent', 'alternate'],
'DoWhileStatement': ['body'],
'WhileStatement': ['body'],
'ForStatement': ['body'],
'ForInStatement': ['body'],
'ForOfStatement': ['body']
};
var keywordsToCheck = {
'else': true,
'finally': true,
'catch': true,
'while': true
};
var LINE_SEPARATOR = /\r\n|\r|\n/g;
var NON_WHITESPACE = /[^\s]/;
/**
* Returns lines and line offsets for specified string.
*
* @param {String} code
* @returns {({line: String, offset: Number})[]}
*/
Function getLineData
✓ Was called
function getLineData(code) {···
var lines = [];
var lastPos = 0;
LINE_SEPARATOR.lastIndex = 0;
var match;
while ((match = LINE_SEPARATOR.exec(code)) !== null) {
var separatorLength = match[0].length;
lines.push({
line: code.slice(lastPos, match.index),
separator: code.substr(match.index, separatorLength),
offset: lastPos
});
lastPos = match.index + separatorLength;
}
lines.push({line: code.slice(lastPos), offset: lastPos, separator: ''});
return lines;
}
function getLineData(code) {
var lines = [];
var lastPos = 0;
LINE_SEPARATOR.lastIndex = 0;
var match;
while ((match = LINE_SEPARATOR.exec(code)) !== null) {
var separatorLength = match[0].length;
lines.push({
line: code.slice(lastPos, match.index),
separator: code.substr(match.index, separatorLength),
offset: lastPos
});
lastPos = match.index + separatorLength;
}
lines.push({line: code.slice(lastPos), offset: lastPos, separator: ''});
return lines;
}
/**
* @param {Object[]} lines
* @returns {String}
*/
Function convertLinesToString
✓ Was called
function convertLinesToString(lines) {···
return lines
.map(function(lineItem) {
return lineItem.line + lineItem.separator;
})
.join('');
}
function convertLinesToString(lines) {
return lines
Function (anonymous_1299)
✓ Was called
.map(function(lineItem) {···
return lineItem.line + lineItem.separator;
})
.map(function(lineItem) {
return lineItem.line + lineItem.separator;
})
.join('');
}
/**
* Applies indentation diff.
*
* @param {String} code
* @param {Number} diff
* @param {String} indentChar
* @param {Boolean} includeEmptyLines
*/
Function applyIndentationDiff
✓ Was called
function applyIndentationDiff(code, diff, indentChar, includeEmptyLines) {···
var lines = getLineData(code);
for (var i = 1; i < lines.length; i++) {
var lineData = lines[i];
var currentIndent;
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
continue;
}
var match = NON_WHITESPACE.exec(lineData.line);
if (match) {
currentIndent = match.index;
} else {
currentIndent = lineData.line.length;
}
lineData.line = new Array(Math.max(currentIndent + diff, 0) + 1).join(indentChar) +
lineData.line.slice(currentIndent);
}
return convertLinesToString(lines);
}
function applyIndentationDiff(code, diff, indentChar, includeEmptyLines) {
var lines = getLineData(code);
for (var i = 1; i < lines.length; i++) {
var lineData = lines[i];
var currentIndent;
Branch IfStatement
✓ Positive was executed (if)
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {···
continue;
}
✓ Negative was executed (else)
}···
var match = NON_WHITESPACE.exec(lineData.line);
Branch LogicalExpression
✓ Was returned
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
✓ Was returned
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
Branch LogicalExpression
✓ Was returned
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
✓ Was returned
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
if (lineData.line.length === 0 && i !== lines.length - 1 && !includeEmptyLines) {
continue;
}
var match = NON_WHITESPACE.exec(lineData.line);
Branch IfStatement
✓ Positive was executed (if)
if (match) {···
currentIndent = match.index;
} else {
✓ Negative was executed (else)
} else {···
currentIndent = lineData.line.length;
}
if (match) {
currentIndent = match.index;
} else {
currentIndent = lineData.line.length;
}
lineData.line = new Array(Math.max(currentIndent + diff, 0) + 1).join(indentChar) +
lineData.line.slice(currentIndent);
}
return convertLinesToString(lines);
}
/**
* Returns true if function expression is passed.
*
* @param {Node} node
* @returns {Boolean}
*/
Function isFunctionExpression
✓ Was called
function isFunctionExpression(node) {···
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
function isFunctionExpression(node) {
Branch LogicalExpression
✓ Was returned
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
✓ Was returned
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
/**
* Returns module block statement. Works with IIFE, require, define.
*
* @param {Program} program
* @returns {BlockStatement|null}
*/
Function getModuleBody
✓ Was called
function getModuleBody(program) {···
if (program.body.length !== 1) {
return null;
}
if (program.body[0].type !== 'ExpressionStatement') {
return null;
}
var expression = program.body[0].expression;
if (expression.type === 'CallExpression') {
var callee = expression.callee;
var args = expression.arguments;

// full file IIFE
if (isFunctionExpression(callee)) {

// detect UMD Shim, where the file body is the body of the factory,
// which is the sole argument to the IIFE
if (args.length === 1 && isFunctionExpression(args[0])) {
return args[0].body;
} else {
return callee.body;
}
}

// full file IIFE with call/apply
if (
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
(callee.property.name === 'apply' || callee.property.name === 'call')
) {
if (isFunctionExpression(callee.object)) {
return callee.object.body;
}
}

// require / define
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (isFunctionExpression(arg)) {
return arg.body;
}
}
}
}

return null;
}
function getModuleBody(program) {
Branch IfStatement
✓ Positive was executed (if)
if (program.body.length !== 1) {···
return null;
}
✓ Negative was executed (else)
}···
if (program.body[0].type !== 'ExpressionStatement') {
if (program.body.length !== 1) {
return null;
}
Branch IfStatement
✓ Positive was executed (if)
if (program.body[0].type !== 'ExpressionStatement') {···
return null;
}
✓ Negative was executed (else)
}···
var expression = program.body[0].expression;
if (program.body[0].type !== 'ExpressionStatement') {
return null;
}
var expression = program.body[0].expression;
Branch IfStatement
✓ Positive was executed (if)
if (expression.type === 'CallExpression') {···
var callee = expression.callee;
var args = expression.arguments;

// full file IIFE
if (isFunctionExpression(callee)) {

// detect UMD Shim, where the file body is the body of the factory,
// which is the sole argument to the IIFE
if (args.length === 1 && isFunctionExpression(args[0])) {
return args[0].body;
} else {
return callee.body;
}
}

// full file IIFE with call/apply
if (
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
(callee.property.name === 'apply' || callee.property.name === 'call')
) {
if (isFunctionExpression(callee.object)) {
return callee.object.body;
}
}

// require / define
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (isFunctionExpression(arg)) {
return arg.body;
}
}
}
}
✓ Negative was executed (else)
}···

return null;
if (expression.type === 'CallExpression') {
var callee = expression.callee;
var args = expression.arguments;
// full file IIFE
Branch IfStatement
✓ Positive was executed (if)
if (isFunctionExpression(callee)) {···

// detect UMD Shim, where the file body is the body of the factory,
// which is the sole argument to the IIFE
if (args.length === 1 && isFunctionExpression(args[0])) {
return args[0].body;
} else {
return callee.body;
}
}
✓ Negative was executed (else)
}···

// full file IIFE with call/apply
if (isFunctionExpression(callee)) {
// detect UMD Shim, where the file body is the body of the factory,
// which is the sole argument to the IIFE
Branch IfStatement
✓ Positive was executed (if)
if (args.length === 1 && isFunctionExpression(args[0])) {···
return args[0].body;
} else {
✓ Negative was executed (else)
} else {···
return callee.body;
}
Branch LogicalExpression
✓ Was returned
if (args.length === 1 && isFunctionExpression(args[0])) {
✗ Was not returned
if (args.length === 1 && isFunctionExpression(args[0])) {
if (args.length === 1 && isFunctionExpression(args[0])) {
return args[0].body;
} else {
return callee.body;
}
}
// full file IIFE with call/apply
Branch IfStatement
✓ Positive was executed (if)
) {···
if (isFunctionExpression(callee.object)) {
return callee.object.body;
}
}
✓ Negative was executed (else)
}···

// require / define
if (
Branch LogicalExpression
✓ Was returned
(callee.property.name === 'apply' || callee.property.name === 'call')
✓ Was returned
callee.type === 'MemberExpression' &&···
callee.property.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
callee.property.type === 'Identifier' &&
✓ Was returned
callee.type === 'MemberExpression' &&
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
Branch LogicalExpression
✓ Was returned
(callee.property.name === 'apply' || callee.property.name === 'call')
✓ Was returned
(callee.property.name === 'apply' || callee.property.name === 'call')
(callee.property.name === 'apply' || callee.property.name === 'call')
) {
Branch IfStatement
✓ Positive was executed (if)
if (isFunctionExpression(callee.object)) {···
return callee.object.body;
}
✗ Negative was not executed (else)
}···
}
if (isFunctionExpression(callee.object)) {
return callee.object.body;
}
}
// require / define
Branch IfStatement
✓ Positive was executed (if)
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {···
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (isFunctionExpression(arg)) {
return arg.body;
}
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
✗ Was not returned
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
Branch LogicalExpression
✓ Was returned
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
✓ Was returned
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
if (callee.type === 'Identifier' && (callee.name === 'define' || callee.name === 'require')) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
Branch IfStatement
✓ Positive was executed (if)
if (isFunctionExpression(arg)) {···
return arg.body;
}
✓ Negative was executed (else)
}···
}
if (isFunctionExpression(arg)) {
return arg.body;
}
}
}
}
return null;
}
/**
* Checks for: `case 'xxx': {`
*
* @param {Element} element
* @returns {Boolean}
*/
Function isBlockOnTheSameLineWithCase
✓ Was called
function isBlockOnTheSameLineWithCase(element) {···
var currentSwitchElement = element.parentElement
.consequent[0]
.getPreviousCodeToken()
.nextSibling;
while (currentSwitchElement) {
if (currentSwitchElement === element) {
return true;
}
if (currentSwitchElement.getNewlineCount() > 0) {
break;
}
currentSwitchElement = currentSwitchElement.nextSibling;
}
return false;
}
function isBlockOnTheSameLineWithCase(element) {
var currentSwitchElement = element.parentElement
.consequent[0]
.getPreviousCodeToken()
.nextSibling;
while (currentSwitchElement) {
Branch IfStatement
✓ Positive was executed (if)
if (currentSwitchElement === element) {···
return true;
}
✓ Negative was executed (else)
}···
if (currentSwitchElement.getNewlineCount() > 0) {
if (currentSwitchElement === element) {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (currentSwitchElement.getNewlineCount() > 0) {···
break;
}
✓ Negative was executed (else)
}···
currentSwitchElement = currentSwitchElement.nextSibling;
if (currentSwitchElement.getNewlineCount() > 0) {
break;
}
currentSwitchElement = currentSwitchElement.nextSibling;
}
return false;
}
/**
* Returns true for situations like `if ... else`, `try ... catch`.
* I.e. two blocks within one statement.
*
* @param {Element} blockStatement
* @returns {*}
*/
Function hasFollowingClause
✓ Was called
function hasFollowingClause(blockStatement) {···
var parent = blockStatement.parentElement;
if (parent.type === 'IfStatement') {
return parent.consequent === blockStatement && parent.alternate;
}
if (parent.type === 'TryStatement') {
return true;
}
if (parent.type === 'DoWhileStatement') {
return true;
}
if (parent.type === 'CatchClause') {
return parent.parentElement.finalizer;
}
}
function hasFollowingClause(blockStatement) {
var parent = blockStatement.parentElement;
Branch IfStatement
✓ Positive was executed (if)
if (parent.type === 'IfStatement') {···
return parent.consequent === blockStatement && parent.alternate;
}
✓ Negative was executed (else)
}···
if (parent.type === 'TryStatement') {
if (parent.type === 'IfStatement') {
Branch LogicalExpression
✓ Was returned
return parent.consequent === blockStatement && parent.alternate;
✗ Was not returned
return parent.consequent === blockStatement && parent.alternate;
return parent.consequent === blockStatement && parent.alternate;
}
Branch IfStatement
✓ Positive was executed (if)
if (parent.type === 'TryStatement') {···
return true;
}
✓ Negative was executed (else)
}···
if (parent.type === 'DoWhileStatement') {
if (parent.type === 'TryStatement') {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parent.type === 'DoWhileStatement') {···
return true;
}
✓ Negative was executed (else)
}···
if (parent.type === 'CatchClause') {
if (parent.type === 'DoWhileStatement') {
return true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parent.type === 'CatchClause') {···
return parent.parentElement.finalizer;
}
✓ Negative was executed (else)
}···
}
if (parent.type === 'CatchClause') {
return parent.parentElement.finalizer;
}
}
Function (anonymous_1305)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1306)
✓ Was called
configure: function(options) {···
this._includeEmptyLines = false;
this._exceptComments = false;

if (typeof options === 'object') {
this._includeEmptyLines = (options.includeEmptyLines === true);
if (Array.isArray(options.allExcept)) {
this._exceptComments = options.allExcept.indexOf('comments') > -1;
this._includeEmptyLines = options.allExcept.indexOf('emptyLines') === -1;
}

options = options.value;
}

assert(
options === '\t' ||
(typeof options === 'number' && options > 0),
this.getOptionName() + ' option requires a positive number of spaces or "\\t"' +
' or options object with "value" property'
);

if (typeof options === 'number') {
this._indentChar = ' ';
this._nonIndentChar = '\t';
this._indentSize = options;
} else {
this._nonIndentChar = ' ';
this._indentChar = '\t';
this._indentSize = 1;
}

this._indentBreaks = null;
this._indentModuleBodies = null;
},
configure: function(options) {
this._includeEmptyLines = false;
this._exceptComments = false;
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'object') {···
this._includeEmptyLines = (options.includeEmptyLines === true);
if (Array.isArray(options.allExcept)) {
this._exceptComments = options.allExcept.indexOf('comments') > -1;
this._includeEmptyLines = options.allExcept.indexOf('emptyLines') === -1;
}

options = options.value;
}
✓ Negative was executed (else)
}···

assert(
if (typeof options === 'object') {
this._includeEmptyLines = (options.includeEmptyLines === true);
Branch IfStatement
✓ Positive was executed (if)
if (Array.isArray(options.allExcept)) {···
this._exceptComments = options.allExcept.indexOf('comments') > -1;
this._includeEmptyLines = options.allExcept.indexOf('emptyLines') === -1;
}
✓ Negative was executed (else)
}···

options = options.value;
if (Array.isArray(options.allExcept)) {
this._exceptComments = options.allExcept.indexOf('comments') > -1;
this._includeEmptyLines = options.allExcept.indexOf('emptyLines') === -1;
}
options = options.value;
}
assert(
Branch LogicalExpression
✓ Was returned
(typeof options === 'number' && options > 0),
✓ Was returned
options === '\t' ||
options === '\t' ||
Branch LogicalExpression
✓ Was returned
(typeof options === 'number' && options > 0),
✓ Was returned
(typeof options === 'number' && options > 0),
(typeof options === 'number' && options > 0),
this.getOptionName() + ' option requires a positive number of spaces or "\\t"' +
' or options object with "value" property'
);
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'number') {···
this._indentChar = ' ';
this._nonIndentChar = '\t';
this._indentSize = options;
} else {
✓ Negative was executed (else)
} else {···
this._nonIndentChar = ' ';
this._indentChar = '\t';
this._indentSize = 1;
}
if (typeof options === 'number') {
this._indentChar = ' ';
this._nonIndentChar = '\t';
this._indentSize = options;
} else {
this._nonIndentChar = ' ';
this._indentChar = '\t';
this._indentSize = 1;
}
this._indentBreaks = null;
this._indentModuleBodies = null;
},
Function (anonymous_1307)
✓ Was called
getOptionName: function() {···
return 'validateIndentation';
},
getOptionName: function() {
return 'validateIndentation';
},
/**
* Calculates user-implied indent for function expression.
*
* @param {FunctionExpression|ArrowFunctionExpression} functionExpression
* @param {Number} indent
* @returns {Number}
* @private
*/
Function (anonymous_1308)
✓ Was called
_getFunctionIndent: function(functionExpression, indent) {···
var functionIndent = 0;
var indentBeforeClosingBrace = this._getElementDirectIndent(functionExpression.body.lastChild);
if (indentBeforeClosingBrace !== null) {
functionIndent = indentBeforeClosingBrace + 1;
}
var indentBeforeFunction = this._getElementDirectIndent(functionExpression);
if (indentBeforeFunction !== null) {
functionIndent = Math.min(functionIndent, indentBeforeFunction + 1);
}
return Math.max(indent, functionIndent);
},
_getFunctionIndent: function(functionExpression, indent) {
var functionIndent = 0;
var indentBeforeClosingBrace = this._getElementDirectIndent(functionExpression.body.lastChild);
Branch IfStatement
✓ Positive was executed (if)
if (indentBeforeClosingBrace !== null) {···
functionIndent = indentBeforeClosingBrace + 1;
}
✓ Negative was executed (else)
}···
var indentBeforeFunction = this._getElementDirectIndent(functionExpression);
if (indentBeforeClosingBrace !== null) {
functionIndent = indentBeforeClosingBrace + 1;
}
var indentBeforeFunction = this._getElementDirectIndent(functionExpression);
Branch IfStatement
✓ Positive was executed (if)
if (indentBeforeFunction !== null) {···
functionIndent = Math.min(functionIndent, indentBeforeFunction + 1);
}
✓ Negative was executed (else)
}···
return Math.max(indent, functionIndent);
if (indentBeforeFunction !== null) {
functionIndent = Math.min(functionIndent, indentBeforeFunction + 1);
}
return Math.max(indent, functionIndent);
},
/**
* Calculates user-implied indent for object expression.
*
* @param {ObjectExpression} objectExpression
* @param {Number} indent
* @returns {Number}
* @private
*/
Function (anonymous_1309)
✓ Was called
_getObjectExpressionIndent: function(objectExpression, indent) {···
var objectIndent = 0;
var properties = objectExpression.properties;

// Handling nested one-line objects, i.e. `{prop: {\n`
if (objectExpression.parentElement.type === 'ObjectProperty') {
var parentObjectExpressionBrace = objectExpression.parentElement.parentElement.firstChild;
var currentToken = objectExpression.getPreviousToken();
while (currentToken) {
if (currentToken === parentObjectExpressionBrace) {
indent--;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
currentToken = currentToken.getPreviousToken();
}
}
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
objectIndent = this._getElementDirectIndent(property);
if (objectIndent !== null) {
break;
}

}
return Math.max(indent, objectIndent);
},
_getObjectExpressionIndent: function(objectExpression, indent) {
var objectIndent = 0;
var properties = objectExpression.properties;
// Handling nested one-line objects, i.e. `{prop: {\n`
Branch IfStatement
✓ Positive was executed (if)
if (objectExpression.parentElement.type === 'ObjectProperty') {···
var parentObjectExpressionBrace = objectExpression.parentElement.parentElement.firstChild;
var currentToken = objectExpression.getPreviousToken();
while (currentToken) {
if (currentToken === parentObjectExpressionBrace) {
indent--;
break;
}
if (currentToken.getNewlineCount() > 0) {
break;
}
currentToken = currentToken.getPreviousToken();
}
}
✓ Negative was executed (else)
}···
for (var i = 0; i < properties.length; i++) {
if (objectExpression.parentElement.type === 'ObjectProperty') {
var parentObjectExpressionBrace = objectExpression.parentElement.parentElement.firstChild;
var currentToken = objectExpression.getPreviousToken();
while (currentToken) {
Branch IfStatement
✓ Positive was executed (if)
if (currentToken === parentObjectExpressionBrace) {···
indent--;
break;
}
✓ Negative was executed (else)
}···
if (currentToken.getNewlineCount() > 0) {
if (currentToken === parentObjectExpressionBrace) {
indent--;
break;
}
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.getNewlineCount() > 0) {···
break;
}
✓ Negative was executed (else)
}···
currentToken = currentToken.getPreviousToken();
if (currentToken.getNewlineCount() > 0) {
break;
}
currentToken = currentToken.getPreviousToken();
}
}
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
objectIndent = this._getElementDirectIndent(property);
Branch IfStatement
✓ Positive was executed (if)
if (objectIndent !== null) {···
break;
}
✓ Negative was executed (else)
}···

}
if (objectIndent !== null) {
break;
}
}
return Math.max(indent, objectIndent);
},
/**
* Returns indentation for specified element if element is indented.
*
* @param {Node} node
* @returns {Number|null}
* @private
*/
Function (anonymous_1310)
✓ Was called
_getElementDirectIndent: function(node) {···
var whitespaceToken = node.getPreviousToken();
if (whitespaceToken.isWhitespace && whitespaceToken.getNewlineCount() > 0) {
var endTokenLines = whitespaceToken.getSourceCodeLines();
return Math.floor(endTokenLines[endTokenLines.length - 1].length / this._indentSize);
}
return null;
},
_getElementDirectIndent: function(node) {
var whitespaceToken = node.getPreviousToken();
Branch IfStatement
✓ Positive was executed (if)
if (whitespaceToken.isWhitespace && whitespaceToken.getNewlineCount() > 0) {···
var endTokenLines = whitespaceToken.getSourceCodeLines();
return Math.floor(endTokenLines[endTokenLines.length - 1].length / this._indentSize);
}
✓ Negative was executed (else)
}···
return null;
Branch LogicalExpression
✓ Was returned
if (whitespaceToken.isWhitespace && whitespaceToken.getNewlineCount() > 0) {
✓ Was returned
if (whitespaceToken.isWhitespace && whitespaceToken.getNewlineCount() > 0) {
if (whitespaceToken.isWhitespace && whitespaceToken.getNewlineCount() > 0) {
var endTokenLines = whitespaceToken.getSourceCodeLines();
return Math.floor(endTokenLines[endTokenLines.length - 1].length / this._indentSize);
}
return null;
},
/**
* Checks indentation for an AST Node.
*
* @param {Node} parentElement
* @param {Errors} errors
* @param {Number} initialIndent
* @param {Object} options
* @param {BlockStatement|null} options.moduleBody
* @param {BlockStatement|null} options.firstWhitespace
* @private
*/
Function (anonymous_1311)
✓ Was called
_checkNode: function(parentElement, errors, initialIndent, options) {···
var moduleBody = options.moduleBody;
var firstWhitespace = options.firstWhitespace;
var isBlock = false;
var isModuleBody = false;
var checkBlockIndentation = false;
var indent = initialIndent;
var isSwitchStatement = parentElement.type === 'SwitchStatement';
var calculateFunctionExpressionIndent = null;
var indentCases = null;

if (isSwitchStatement) {
indent++;
isBlock = true;
checkBlockIndentation = true;
}
if (parentElement.type === 'Program') {
checkBlockIndentation = true;
}
if (parentElement.type === 'BlockStatement') {
indent++;
isBlock = true;
checkBlockIndentation = true;
isModuleBody = parentElement === moduleBody;
if (isModuleBody && this._indentModuleBodies === false) {
indent--;
} else if (parentElement.parentElement.type === 'SwitchCase') {
// Avoiding additional indentation if `{` is on the same line with case block start
if (isBlockOnTheSameLineWithCase(parentElement)) {
indent--;
}
} else {
// Calculating indentation for function expressions.
calculateFunctionExpressionIndent = isFunctionExpression(parentElement.parentElement);
if (calculateFunctionExpressionIndent) {
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
}
}
if (parentElement.type === 'ClassBody') {
indent++;
isBlock = true;
checkBlockIndentation = true;
}
if (parentElement.type === 'SwitchCase') {
indent++;
checkBlockIndentation = true;
}
if (parentElement.type === 'ObjectExpression') {
indent++;
indent = this._getObjectExpressionIndent(parentElement, indent);
isBlock = true;
checkBlockIndentation = true;
}
var nonBlockChecks = nonBlockIndentChecks[parentElement.type];
var statementsToCheck;
if (nonBlockChecks) {
statementsToCheck = nonBlockChecks.filter(function(propName) {
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
});
}

var element = parentElement.firstChild;
while (element) {
if (element.isToken) {
var isFirstWhitespace = element === firstWhitespace;
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
var lines = getLineData(element.getSourceCode());
var lineOffset = this._includeEmptyLines ?
(isFirstWhitespace ? 0 : 1) :
lines.length - 1;
lines = lines.slice(lineOffset);

for (var i = 0; i < lines.length; i++) {
var line = lines[i].line;
if (line.indexOf(this._nonIndentChar) !== -1) {
errors.add(
'Invalid indentation character: ' + this._nonIndentChar,
element,
lines[i].offset
);
}
var nextSibling = element.nextSibling;
var checkForStatement = false;
var checkForKeyword = false;
if (!checkBlockIndentation) {
if (statementsToCheck && statementsToCheck.length > 0) {
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
var nextToken = element.getNextToken();
if (nextToken &&
nextToken.isToken &&
nextToken.type === 'Keyword' &&
keywordsToCheck[nextToken.value]
) {
checkForKeyword = true;
}
}
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
var isLastLine = i === lines.length - 1;
var expectedIndent = indent;

if (checkForStatement) {
expectedIndent++;
}

// If it is the last line in the multiline indent
if (isLastLine && nextSibling) {

var hasExpectedIndent = expectedIndent * this._indentSize === line.length;

if (isBlock) {

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}

// Allowing "break" statement have lesser indentation.
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}

var expectedLineLengths = [expectedIndent * this._indentSize];

// Excluding comments if necessary.
if (isLastLine && nextSibling && nextSibling.isComment) {
if (this._exceptComments) {
break;
}
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}

if (expectedLineLengths.indexOf(line.length) === -1) {
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
adjustElement: isLastLine && nextSibling
}
});
}
}
}
}
} else {
this._checkNode(element, errors, indent, options);
}
element = element.nextSibling;
}
},
_checkNode: function(parentElement, errors, initialIndent, options) {
var moduleBody = options.moduleBody;
var firstWhitespace = options.firstWhitespace;
var isBlock = false;
var isModuleBody = false;
var checkBlockIndentation = false;
var indent = initialIndent;
var isSwitchStatement = parentElement.type === 'SwitchStatement';
var calculateFunctionExpressionIndent = null;
var indentCases = null;
Branch IfStatement
✓ Positive was executed (if)
if (isSwitchStatement) {···
indent++;
isBlock = true;
checkBlockIndentation = true;
}
✓ Negative was executed (else)
}···
if (parentElement.type === 'Program') {
if (isSwitchStatement) {
indent++;
isBlock = true;
checkBlockIndentation = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'Program') {···
checkBlockIndentation = true;
}
✓ Negative was executed (else)
}···
if (parentElement.type === 'BlockStatement') {
if (parentElement.type === 'Program') {
checkBlockIndentation = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'BlockStatement') {···
indent++;
isBlock = true;
checkBlockIndentation = true;
isModuleBody = parentElement === moduleBody;
if (isModuleBody && this._indentModuleBodies === false) {
indent--;
} else if (parentElement.parentElement.type === 'SwitchCase') {
// Avoiding additional indentation if `{` is on the same line with case block start
if (isBlockOnTheSameLineWithCase(parentElement)) {
indent--;
}
} else {
// Calculating indentation for function expressions.
calculateFunctionExpressionIndent = isFunctionExpression(parentElement.parentElement);
if (calculateFunctionExpressionIndent) {
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
}
}
✓ Negative was executed (else)
}···
if (parentElement.type === 'ClassBody') {
if (parentElement.type === 'BlockStatement') {
indent++;
isBlock = true;
checkBlockIndentation = true;
isModuleBody = parentElement === moduleBody;
Branch IfStatement
✗ Positive was not executed (if)
if (isModuleBody && this._indentModuleBodies === false) {···
indent--;
} else if (parentElement.parentElement.type === 'SwitchCase') {
✓ Negative was executed (else)
} else if (parentElement.parentElement.type === 'SwitchCase') {···
// Avoiding additional indentation if `{` is on the same line with case block start
if (isBlockOnTheSameLineWithCase(parentElement)) {
indent--;
}
} else {
// Calculating indentation for function expressions.
calculateFunctionExpressionIndent = isFunctionExpression(parentElement.parentElement);
if (calculateFunctionExpressionIndent) {
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
}
Branch LogicalExpression
✓ Was returned
if (isModuleBody && this._indentModuleBodies === false) {
✓ Was returned
if (isModuleBody && this._indentModuleBodies === false) {
if (isModuleBody && this._indentModuleBodies === false) {
indent--;
Branch IfStatement
✓ Positive was executed (if)
} else if (parentElement.parentElement.type === 'SwitchCase') {···
// Avoiding additional indentation if `{` is on the same line with case block start
if (isBlockOnTheSameLineWithCase(parentElement)) {
indent--;
}
} else {
✓ Negative was executed (else)
} else {···
// Calculating indentation for function expressions.
calculateFunctionExpressionIndent = isFunctionExpression(parentElement.parentElement);
if (calculateFunctionExpressionIndent) {
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
}
} else if (parentElement.parentElement.type === 'SwitchCase') {
// Avoiding additional indentation if `{` is on the same line with case block start
Branch IfStatement
✓ Positive was executed (if)
if (isBlockOnTheSameLineWithCase(parentElement)) {···
indent--;
}
✓ Negative was executed (else)
}···
} else {
if (isBlockOnTheSameLineWithCase(parentElement)) {
indent--;
}
} else {
// Calculating indentation for function expressions.
calculateFunctionExpressionIndent = isFunctionExpression(parentElement.parentElement);
Branch IfStatement
✓ Positive was executed (if)
if (calculateFunctionExpressionIndent) {···
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
✓ Negative was executed (else)
}···
}
if (calculateFunctionExpressionIndent) {
indent = this._getFunctionIndent(parentElement.parentElement, indent);
}
}
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'ClassBody') {···
indent++;
isBlock = true;
checkBlockIndentation = true;
}
✓ Negative was executed (else)
}···
if (parentElement.type === 'SwitchCase') {
if (parentElement.type === 'ClassBody') {
indent++;
isBlock = true;
checkBlockIndentation = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'SwitchCase') {···
indent++;
checkBlockIndentation = true;
}
✓ Negative was executed (else)
}···
if (parentElement.type === 'ObjectExpression') {
if (parentElement.type === 'SwitchCase') {
indent++;
checkBlockIndentation = true;
}
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'ObjectExpression') {···
indent++;
indent = this._getObjectExpressionIndent(parentElement, indent);
isBlock = true;
checkBlockIndentation = true;
}
✓ Negative was executed (else)
}···
var nonBlockChecks = nonBlockIndentChecks[parentElement.type];
if (parentElement.type === 'ObjectExpression') {
indent++;
indent = this._getObjectExpressionIndent(parentElement, indent);
isBlock = true;
checkBlockIndentation = true;
}
var nonBlockChecks = nonBlockIndentChecks[parentElement.type];
var statementsToCheck;
Branch IfStatement
✓ Positive was executed (if)
if (nonBlockChecks) {···
statementsToCheck = nonBlockChecks.filter(function(propName) {
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
});
}
✓ Negative was executed (else)
}···

var element = parentElement.firstChild;
if (nonBlockChecks) {
Function (anonymous_1312)
✓ Was called
statementsToCheck = nonBlockChecks.filter(function(propName) {···
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
});
statementsToCheck = nonBlockChecks.filter(function(propName) {
Branch LogicalExpression
✓ Was returned
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
✓ Was returned
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
return parentElement[propName] && parentElement[propName].type !== 'BlockStatement';
});
}
var element = parentElement.firstChild;
while (element) {
Branch IfStatement
✓ Positive was executed (if)
if (element.isToken) {···
var isFirstWhitespace = element === firstWhitespace;
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
var lines = getLineData(element.getSourceCode());
var lineOffset = this._includeEmptyLines ?
(isFirstWhitespace ? 0 : 1) :
lines.length - 1;
lines = lines.slice(lineOffset);

for (var i = 0; i < lines.length; i++) {
var line = lines[i].line;
if (line.indexOf(this._nonIndentChar) !== -1) {
errors.add(
'Invalid indentation character: ' + this._nonIndentChar,
element,
lines[i].offset
);
}
var nextSibling = element.nextSibling;
var checkForStatement = false;
var checkForKeyword = false;
if (!checkBlockIndentation) {
if (statementsToCheck && statementsToCheck.length > 0) {
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
var nextToken = element.getNextToken();
if (nextToken &&
nextToken.isToken &&
nextToken.type === 'Keyword' &&
keywordsToCheck[nextToken.value]
) {
checkForKeyword = true;
}
}
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
var isLastLine = i === lines.length - 1;
var expectedIndent = indent;

if (checkForStatement) {
expectedIndent++;
}

// If it is the last line in the multiline indent
if (isLastLine && nextSibling) {

var hasExpectedIndent = expectedIndent * this._indentSize === line.length;

if (isBlock) {

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}

// Allowing "break" statement have lesser indentation.
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}

var expectedLineLengths = [expectedIndent * this._indentSize];

// Excluding comments if necessary.
if (isLastLine && nextSibling && nextSibling.isComment) {
if (this._exceptComments) {
break;
}
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}

if (expectedLineLengths.indexOf(line.length) === -1) {
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
adjustElement: isLastLine && nextSibling
}
});
}
}
}
}
} else {
✓ Negative was executed (else)
} else {···
this._checkNode(element, errors, indent, options);
}
if (element.isToken) {
var isFirstWhitespace = element === firstWhitespace;
Branch IfStatement
✓ Positive was executed (if)
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {···
var lines = getLineData(element.getSourceCode());
var lineOffset = this._includeEmptyLines ?
(isFirstWhitespace ? 0 : 1) :
lines.length - 1;
lines = lines.slice(lineOffset);

for (var i = 0; i < lines.length; i++) {
var line = lines[i].line;
if (line.indexOf(this._nonIndentChar) !== -1) {
errors.add(
'Invalid indentation character: ' + this._nonIndentChar,
element,
lines[i].offset
);
}
var nextSibling = element.nextSibling;
var checkForStatement = false;
var checkForKeyword = false;
if (!checkBlockIndentation) {
if (statementsToCheck && statementsToCheck.length > 0) {
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
var nextToken = element.getNextToken();
if (nextToken &&
nextToken.isToken &&
nextToken.type === 'Keyword' &&
keywordsToCheck[nextToken.value]
) {
checkForKeyword = true;
}
}
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
var isLastLine = i === lines.length - 1;
var expectedIndent = indent;

if (checkForStatement) {
expectedIndent++;
}

// If it is the last line in the multiline indent
if (isLastLine && nextSibling) {

var hasExpectedIndent = expectedIndent * this._indentSize === line.length;

if (isBlock) {

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}

// Allowing "break" statement have lesser indentation.
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}

var expectedLineLengths = [expectedIndent * this._indentSize];

// Excluding comments if necessary.
if (isLastLine && nextSibling && nextSibling.isComment) {
if (this._exceptComments) {
break;
}
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}

if (expectedLineLengths.indexOf(line.length) === -1) {
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
adjustElement: isLastLine && nextSibling
}
});
}
}
}
}
✓ Negative was executed (else)
}···
} else {
Branch LogicalExpression
✓ Was returned
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
✓ Was returned
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
Branch LogicalExpression
✓ Was returned
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
✓ Was returned
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
if (element.isWhitespace && (element.getNewlineCount() > 0 || isFirstWhitespace)) {
var lines = getLineData(element.getSourceCode());
Branch ConditionalExpression
✓ Positive was returned (? ...)
(isFirstWhitespace ? 0 : 1) :
✓ Negative was returned (: ...)
lines.length - 1;
var lineOffset = this._includeEmptyLines ?
Branch ConditionalExpression
✓ Positive was returned (? ...)
(isFirstWhitespace ? 0 : 1) :
✓ Negative was returned (: ...)
(isFirstWhitespace ? 0 : 1) :
(isFirstWhitespace ? 0 : 1) :
lines.length - 1;
lines = lines.slice(lineOffset);
for (var i = 0; i < lines.length; i++) {
var line = lines[i].line;
Branch IfStatement
✗ Positive was not executed (if)
if (line.indexOf(this._nonIndentChar) !== -1) {···
errors.add(
'Invalid indentation character: ' + this._nonIndentChar,
element,
lines[i].offset
);
}
✓ Negative was executed (else)
}···
var nextSibling = element.nextSibling;
if (line.indexOf(this._nonIndentChar) !== -1) {
errors.add(
'Invalid indentation character: ' + this._nonIndentChar,
element,
lines[i].offset
);
}
var nextSibling = element.nextSibling;
var checkForStatement = false;
var checkForKeyword = false;
Branch IfStatement
✓ Positive was executed (if)
if (!checkBlockIndentation) {···
if (statementsToCheck && statementsToCheck.length > 0) {
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
var nextToken = element.getNextToken();
if (nextToken &&
nextToken.isToken &&
nextToken.type === 'Keyword' &&
keywordsToCheck[nextToken.value]
) {
checkForKeyword = true;
}
}
✓ Negative was executed (else)
}···
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
if (!checkBlockIndentation) {
Branch IfStatement
✓ Positive was executed (if)
if (statementsToCheck && statementsToCheck.length > 0) {···
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
✓ Negative was executed (else)
}···
var nextToken = element.getNextToken();
Branch LogicalExpression
✓ Was returned
if (statementsToCheck && statementsToCheck.length > 0) {
✓ Was returned
if (statementsToCheck && statementsToCheck.length > 0) {
if (statementsToCheck && statementsToCheck.length > 0) {
Branch IfStatement
✗ Positive was not executed (if)
if (statementsToCheck.indexOf(nextSibling) !== -1) {···
checkForStatement = true;
}
✓ Negative was executed (else)
}···
}
if (statementsToCheck.indexOf(nextSibling) !== -1) {
checkForStatement = true;
}
}
var nextToken = element.getNextToken();
Branch IfStatement
✓ Positive was executed (if)
) {···
checkForKeyword = true;
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
keywordsToCheck[nextToken.value]
✓ Was returned
if (nextToken &&···
nextToken.isToken &&
nextToken.type === 'Keyword' &&
Branch LogicalExpression
✓ Was returned
nextToken.type === 'Keyword' &&
✗ Was not returned
if (nextToken &&···
nextToken.isToken &&
Branch LogicalExpression
✓ Was returned
nextToken.isToken &&
✗ Was not returned
if (nextToken &&
if (nextToken &&
nextToken.isToken &&
nextToken.type === 'Keyword' &&
keywordsToCheck[nextToken.value]
) {
checkForKeyword = true;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (checkBlockIndentation || checkForStatement || checkForKeyword) {···
var isLastLine = i === lines.length - 1;
var expectedIndent = indent;

if (checkForStatement) {
expectedIndent++;
}

// If it is the last line in the multiline indent
if (isLastLine && nextSibling) {

var hasExpectedIndent = expectedIndent * this._indentSize === line.length;

if (isBlock) {

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}

// Allowing "break" statement have lesser indentation.
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}

var expectedLineLengths = [expectedIndent * this._indentSize];

// Excluding comments if necessary.
if (isLastLine && nextSibling && nextSibling.isComment) {
if (this._exceptComments) {
break;
}
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}

if (expectedLineLengths.indexOf(line.length) === -1) {
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
adjustElement: isLastLine && nextSibling
}
});
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
✓ Was returned
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
Branch LogicalExpression
✓ Was returned
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
✓ Was returned
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
if (checkBlockIndentation || checkForStatement || checkForKeyword) {
var isLastLine = i === lines.length - 1;
var expectedIndent = indent;
Branch IfStatement
✗ Positive was not executed (if)
if (checkForStatement) {···
expectedIndent++;
}
✓ Negative was executed (else)
}···

// If it is the last line in the multiline indent
if (checkForStatement) {
expectedIndent++;
}
// If it is the last line in the multiline indent
Branch IfStatement
✓ Positive was executed (if)
if (isLastLine && nextSibling) {···

var hasExpectedIndent = expectedIndent * this._indentSize === line.length;

if (isBlock) {

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}

// Allowing "break" statement have lesser indentation.
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}
✓ Negative was executed (else)
}···

var expectedLineLengths = [expectedIndent * this._indentSize];
Branch LogicalExpression
✓ Was returned
if (isLastLine && nextSibling) {
✓ Was returned
if (isLastLine && nextSibling) {
if (isLastLine && nextSibling) {
var hasExpectedIndent = expectedIndent * this._indentSize === line.length;
Branch IfStatement
✓ Positive was executed (if)
if (isBlock) {···

// Handling "{" and "}" in block statements.
if (
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}
✓ Negative was executed (else)
}···

// Allowing "break" statement have lesser indentation.
if (isBlock) {
// Handling "{" and "}" in block statements.
Branch IfStatement
✓ Positive was executed (if)
) {···
expectedIndent = Math.max(0, expectedIndent - 1);

// Handling module bodies (i.e. require, define)
} else if (isModuleBody) {
✓ Negative was executed (else)
} else if (isModuleBody) {···
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
if (
Branch LogicalExpression
✓ Was returned
nextSibling === parentElement.firstChild
✓ Was returned
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.lastChild ||
nextSibling === parentElement.firstChild
) {
expectedIndent = Math.max(0, expectedIndent - 1);
// Handling module bodies (i.e. require, define)
Branch IfStatement
✓ Positive was executed (if)
} else if (isModuleBody) {···
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}

// Handling switch statement cases
} else if (isSwitchStatement) {
✓ Negative was executed (else)
} else if (isSwitchStatement) {···
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
} else if (isModuleBody) {
Branch IfStatement
✓ Positive was executed (if)
if (this._indentModuleBodies === null) {···
this._indentModuleBodies = hasExpectedIndent;
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}
✗ Negative was not executed (else)
}···

// Handling switch statement cases
if (this._indentModuleBodies === null) {
this._indentModuleBodies = hasExpectedIndent;
Branch IfStatement
✓ Positive was executed (if)
if (!this._indentModuleBodies) {···
indent--;
expectedIndent--;
}
✓ Negative was executed (else)
}···
}
if (!this._indentModuleBodies) {
indent--;
expectedIndent--;
}
}
// Handling switch statement cases
Branch IfStatement
✓ Positive was executed (if)
} else if (isSwitchStatement) {···
if (indentCases === null) {
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}

// Handling functions in expressions (with unclear initial indent).
} else if (calculateFunctionExpressionIndent) {
✓ Negative was executed (else)
} else if (calculateFunctionExpressionIndent) {···
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
} else if (isSwitchStatement) {
Branch IfStatement
✓ Positive was executed (if)
if (indentCases === null) {···
indentCases = hasExpectedIndent;
if (!indentCases) {
indent--;
expectedIndent--;
}
}
✓ Negative was executed (else)
}···

// Handling functions in expressions (with unclear initial indent).
if (indentCases === null) {
indentCases = hasExpectedIndent;
Branch IfStatement
✓ Positive was executed (if)
if (!indentCases) {···
indent--;
expectedIndent--;
}
✓ Negative was executed (else)
}···
}
if (!indentCases) {
indent--;
expectedIndent--;
}
}
// Handling functions in expressions (with unclear initial indent).
Branch IfStatement
✓ Positive was executed (if)
} else if (calculateFunctionExpressionIndent) {···
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
✓ Negative was executed (else)
}···
}
} else if (calculateFunctionExpressionIndent) {
indent = Math.max(indent, Math.floor(line.length / this._indentSize));
expectedIndent = indent;
calculateFunctionExpressionIndent = false;
}
}
// Allowing "break" statement have lesser indentation.
Branch IfStatement
✓ Positive was executed (if)
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {···
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
✓ Was returned
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
if (parentElement.type === 'SwitchCase' && nextSibling.type === 'BreakStatement') {
Branch IfStatement
✓ Positive was executed (if)
if (this._indentBreaks === null) {···
this._indentBreaks = hasExpectedIndent;
}
✓ Negative was executed (else)
}···
if (!this._indentBreaks) {
if (this._indentBreaks === null) {
this._indentBreaks = hasExpectedIndent;
}
Branch IfStatement
✓ Positive was executed (if)
if (!this._indentBreaks) {···
expectedIndent--;
}
✓ Negative was executed (else)
}···
}
if (!this._indentBreaks) {
expectedIndent--;
}
}
}
var expectedLineLengths = [expectedIndent * this._indentSize];
// Excluding comments if necessary.
Branch IfStatement
✓ Positive was executed (if)
if (isLastLine && nextSibling && nextSibling.isComment) {···
if (this._exceptComments) {
break;
}
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}
✓ Negative was executed (else)
}···

if (expectedLineLengths.indexOf(line.length) === -1) {
Branch LogicalExpression
✓ Was returned
if (isLastLine && nextSibling && nextSibling.isComment) {
✓ Was returned
if (isLastLine && nextSibling && nextSibling.isComment) {
Branch LogicalExpression
✓ Was returned
if (isLastLine && nextSibling && nextSibling.isComment) {
✓ Was returned
if (isLastLine && nextSibling && nextSibling.isComment) {
if (isLastLine && nextSibling && nextSibling.isComment) {
Branch IfStatement
✓ Positive was executed (if)
if (this._exceptComments) {···
break;
}
✓ Negative was executed (else)
}···
if (isSwitchStatement && indentCases) {
if (this._exceptComments) {
break;
}
Branch IfStatement
✓ Positive was executed (if)
if (isSwitchStatement && indentCases) {···
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
✓ Negative was executed (else)
}···
var brace = nextSibling.getNextNonWhitespaceToken();
Branch LogicalExpression
✓ Was returned
if (isSwitchStatement && indentCases) {
✓ Was returned
if (isSwitchStatement && indentCases) {
if (isSwitchStatement && indentCases) {
expectedLineLengths.push(expectedLineLengths[0] + this._indentSize);
}
var brace = nextSibling.getNextNonWhitespaceToken();
Branch IfStatement
✓ Positive was executed (if)
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {···
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
✓ Was returned
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
Branch LogicalExpression
✓ Was returned
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
✓ Was returned
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
if (isBlock && brace === parentElement.lastChild && hasFollowingClause(parentElement)) {
expectedLineLengths.push(expectedLineLengths[0] - this._indentSize);
}
}
Branch IfStatement
✓ Positive was executed (if)
if (expectedLineLengths.indexOf(line.length) === -1) {···
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
adjustElement: isLastLine && nextSibling
}
});
}
✓ Negative was executed (else)
}···
}
if (expectedLineLengths.indexOf(line.length) === -1) {
errors.cast({
message: 'Expected indentation of ' + expectedLineLengths[0] + ' characters',
element: element,
offset: lines[i].offset,
additional: {
line: lineOffset + i,
indentDiff: expectedLineLengths[0] - line.length,
Branch LogicalExpression
✓ Was returned
adjustElement: isLastLine && nextSibling
✓ Was returned
adjustElement: isLastLine && nextSibling
adjustElement: isLastLine && nextSibling
}
});
}
}
}
}
} else {
this._checkNode(element, errors, indent, options);
}
element = element.nextSibling;
}
},
Function (anonymous_1313)
✓ Was called
check: function(file, errors) {···
var program = file.getProgram();
var firstWhitespace;
if (program.getFirstToken().isWhitespace) {
firstWhitespace = program.getFirstToken();
}
this._checkNode(program, errors, 0, {
moduleBody: getModuleBody(program),
firstWhitespace: firstWhitespace
});
},
check: function(file, errors) {
var program = file.getProgram();
var firstWhitespace;
Branch IfStatement
✓ Positive was executed (if)
if (program.getFirstToken().isWhitespace) {···
firstWhitespace = program.getFirstToken();
}
✓ Negative was executed (else)
}···
this._checkNode(program, errors, 0, {
if (program.getFirstToken().isWhitespace) {
firstWhitespace = program.getFirstToken();
}
this._checkNode(program, errors, 0, {
moduleBody: getModuleBody(program),
firstWhitespace: firstWhitespace
});
},
Function (anonymous_1314)
✓ Was called
_fix: function(file, error) {···
var indentChar = this._indentChar;
var whitespaceToken = error.element;

var fixData = error.additional;
var indentDiff = fixData.indentDiff;

var lineItemsData = getLineData(whitespaceToken.value);
var lineItemToFix = lineItemsData[fixData.line];
if (lineItemToFix) {
var originalIndentLength = lineItemToFix.line.length;
var finalIndentLength = originalIndentLength + indentDiff;
lineItemToFix.line = new Array(finalIndentLength + 1).join(indentChar);
var newWhitespaceToken = new cst.Token(
'Whitespace',
convertLinesToString(lineItemsData)
);
whitespaceToken.parentElement.replaceChild(newWhitespaceToken, whitespaceToken);

var adjustElement = fixData.adjustElement;
if (adjustElement && adjustElement.getNewlineCount() > 0) {
var currentToken = adjustElement.getFirstToken();
var lastToken = adjustElement.getLastToken();
while (true) {
var nextToken = currentToken.getNextToken();
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
var newSubWhitespaceToken = new cst.Token(
currentToken.type,
applyIndentationDiff(currentToken.value, indentDiff, indentChar, this._includeEmptyLines)
);
currentToken.parentElement.replaceChild(newSubWhitespaceToken, currentToken);
}
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
var prev = currentToken.getPreviousToken();
var commentIndent = 0;
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
-commentIndent :
indentDiff;
var newCommentToken = new cst.Token(
currentToken.type,
applyIndentationDiff(
currentToken.value,
commentDiff,
indentChar,
this._includeEmptyLines
)
);
currentToken.parentElement.replaceChild(newCommentToken, currentToken);
}
if (currentToken === lastToken) {
break;
}
currentToken = nextToken;
}
}
}
}
_fix: function(file, error) {
var indentChar = this._indentChar;
var whitespaceToken = error.element;
var fixData = error.additional;
var indentDiff = fixData.indentDiff;
var lineItemsData = getLineData(whitespaceToken.value);
var lineItemToFix = lineItemsData[fixData.line];
Branch IfStatement
✓ Positive was executed (if)
if (lineItemToFix) {···
var originalIndentLength = lineItemToFix.line.length;
var finalIndentLength = originalIndentLength + indentDiff;
lineItemToFix.line = new Array(finalIndentLength + 1).join(indentChar);
var newWhitespaceToken = new cst.Token(
'Whitespace',
convertLinesToString(lineItemsData)
);
whitespaceToken.parentElement.replaceChild(newWhitespaceToken, whitespaceToken);

var adjustElement = fixData.adjustElement;
if (adjustElement && adjustElement.getNewlineCount() > 0) {
var currentToken = adjustElement.getFirstToken();
var lastToken = adjustElement.getLastToken();
while (true) {
var nextToken = currentToken.getNextToken();
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
var newSubWhitespaceToken = new cst.Token(
currentToken.type,
applyIndentationDiff(currentToken.value, indentDiff, indentChar, this._includeEmptyLines)
);
currentToken.parentElement.replaceChild(newSubWhitespaceToken, currentToken);
}
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
var prev = currentToken.getPreviousToken();
var commentIndent = 0;
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
-commentIndent :
indentDiff;
var newCommentToken = new cst.Token(
currentToken.type,
applyIndentationDiff(
currentToken.value,
commentDiff,
indentChar,
this._includeEmptyLines
)
);
currentToken.parentElement.replaceChild(newCommentToken, currentToken);
}
if (currentToken === lastToken) {
break;
}
currentToken = nextToken;
}
}
}
✗ Negative was not executed (else)
}···
}
if (lineItemToFix) {
var originalIndentLength = lineItemToFix.line.length;
var finalIndentLength = originalIndentLength + indentDiff;
lineItemToFix.line = new Array(finalIndentLength + 1).join(indentChar);
var newWhitespaceToken = new cst.Token(
'Whitespace',
convertLinesToString(lineItemsData)
);
whitespaceToken.parentElement.replaceChild(newWhitespaceToken, whitespaceToken);
var adjustElement = fixData.adjustElement;
Branch IfStatement
✓ Positive was executed (if)
if (adjustElement && adjustElement.getNewlineCount() > 0) {···
var currentToken = adjustElement.getFirstToken();
var lastToken = adjustElement.getLastToken();
while (true) {
var nextToken = currentToken.getNextToken();
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
var newSubWhitespaceToken = new cst.Token(
currentToken.type,
applyIndentationDiff(currentToken.value, indentDiff, indentChar, this._includeEmptyLines)
);
currentToken.parentElement.replaceChild(newSubWhitespaceToken, currentToken);
}
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
var prev = currentToken.getPreviousToken();
var commentIndent = 0;
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
-commentIndent :
indentDiff;
var newCommentToken = new cst.Token(
currentToken.type,
applyIndentationDiff(
currentToken.value,
commentDiff,
indentChar,
this._includeEmptyLines
)
);
currentToken.parentElement.replaceChild(newCommentToken, currentToken);
}
if (currentToken === lastToken) {
break;
}
currentToken = nextToken;
}
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (adjustElement && adjustElement.getNewlineCount() > 0) {
✓ Was returned
if (adjustElement && adjustElement.getNewlineCount() > 0) {
if (adjustElement && adjustElement.getNewlineCount() > 0) {
var currentToken = adjustElement.getFirstToken();
var lastToken = adjustElement.getLastToken();
while (true) {
var nextToken = currentToken.getNextToken();
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {···
var newSubWhitespaceToken = new cst.Token(
currentToken.type,
applyIndentationDiff(currentToken.value, indentDiff, indentChar, this._includeEmptyLines)
);
currentToken.parentElement.replaceChild(newSubWhitespaceToken, currentToken);
}
✓ Negative was executed (else)
}···
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
Branch LogicalExpression
✓ Was returned
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
✓ Was returned
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
if (currentToken.isWhitespace && currentToken.getNewlineCount() > 0) {
var newSubWhitespaceToken = new cst.Token(
currentToken.type,
applyIndentationDiff(currentToken.value, indentDiff, indentChar, this._includeEmptyLines)
);
currentToken.parentElement.replaceChild(newSubWhitespaceToken, currentToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {···
var prev = currentToken.getPreviousToken();
var commentIndent = 0;
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
-commentIndent :
indentDiff;
var newCommentToken = new cst.Token(
currentToken.type,
applyIndentationDiff(
currentToken.value,
commentDiff,
indentChar,
this._includeEmptyLines
)
);
currentToken.parentElement.replaceChild(newCommentToken, currentToken);
}
✓ Negative was executed (else)
}···
if (currentToken === lastToken) {
Branch LogicalExpression
✓ Was returned
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
✓ Was returned
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
if (currentToken.isComment && currentToken.getNewlineCount() > 0) {
var prev = currentToken.getPreviousToken();
var commentIndent = 0;
Branch IfStatement
✓ Positive was executed (if)
if (prev.isWhitespace && prev.getNewlineCount() > 0) {···
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
✗ Negative was not executed (else)
}···
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
Branch LogicalExpression
✓ Was returned
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
✗ Was not returned
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
if (prev.isWhitespace && prev.getNewlineCount() > 0) {
commentIndent = prev.getSourceCodeLines().concat().pop().length;
}
Branch ConditionalExpression
✓ Positive was returned (? ...)
-commentIndent :
✓ Negative was returned (: ...)
indentDiff;
Branch LogicalExpression
✓ Was returned
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
✓ Was returned
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
var commentDiff = indentDiff < 0 && commentIndent < -indentDiff ?
-commentIndent :
indentDiff;
var newCommentToken = new cst.Token(
currentToken.type,
applyIndentationDiff(
currentToken.value,
commentDiff,
indentChar,
this._includeEmptyLines
)
);
currentToken.parentElement.replaceChild(newCommentToken, currentToken);
}
Branch IfStatement
✓ Positive was executed (if)
if (currentToken === lastToken) {···
break;
}
✓ Negative was executed (else)
}···
currentToken = nextToken;
if (currentToken === lastToken) {
break;
}
currentToken = nextToken;
}
}
}
}
};
validate-line-breaks.js
/**
* Option to check line break characters
*
* Types: `String`, `Object`
*
* Values:
* - `String`: setting this is the same as validating the rule using `{character: String, reportOncePerFile: false}`
* - `Object`:
* - `character`
* - `String` specifies the line break character that is allowed. (Values allowed: `"CR"`, `"LF"` or `"CRLF"`)
* - `reportOncePerFile`
* - `true` specifies that validation for the file should stop running upon encountering the first rule
* violation and return the details of that violation in the report
* - `false` specifies that all lines in the file should be validated with all rule violations captured in
* the final report
*
* #### Example
*
* ```js
* "validateLineBreaks": "LF"
* ```
*
* ##### Valid for mode `"LF"`
* ```js
* var x = 1;<LF>
* x++;
* ```
*
* ##### Invalid for mode `"LF"`
* ```js
* var x = 1;<CRLF>
* x++;
* ```
*/
var assert = require('assert');
var LINE_BREAKS = /\r\n|\n|\r/g;
Function (anonymous_1315)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1316)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'string' || typeof options === 'object',
this.getOptionName() + ' option requires string or object value'
);

if (typeof options === 'string') {
options = { character: options };
}

var lineBreaks = {
CR: '\r',
LF: '\n',
CRLF: '\r\n'
};
this._allowedLineBreak = lineBreaks[options.character];

this._reportOncePerFile = options.reportOncePerFile !== false;
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'string' || typeof options === 'object',
✓ Was returned
typeof options === 'string' || typeof options === 'object',
typeof options === 'string' || typeof options === 'object',
this.getOptionName() + ' option requires string or object value'
);
Branch IfStatement
✓ Positive was executed (if)
if (typeof options === 'string') {···
options = { character: options };
}
✓ Negative was executed (else)
}···

var lineBreaks = {
if (typeof options === 'string') {
options = { character: options };
}
var lineBreaks = {
CR: '\r',
LF: '\n',
CRLF: '\r\n'
};
this._allowedLineBreak = lineBreaks[options.character];
this._reportOncePerFile = options.reportOncePerFile !== false;
},
Function (anonymous_1317)
✓ Was called
getOptionName: function() {···
return 'validateLineBreaks';
},
getOptionName: function() {
return 'validateLineBreaks';
},
Function (anonymous_1318)
✓ Was called
check: function(file, errors) {···
var lines = file.getLines();
if (lines.length < 2) {
return;
}

file.getProgram().selectTokensByType('Whitespace').some(function(whitespace) {
LINE_BREAKS.lastIndex = 0;
var match;
while ((match = LINE_BREAKS.exec(whitespace.value)) !== null) {
if (match[0] !== this._allowedLineBreak) {
errors.add('Invalid line break', whitespace, match.index);
return this._reportOncePerFile;
}
}
}, this);
}
check: function(file, errors) {
var lines = file.getLines();
Branch IfStatement
✓ Positive was executed (if)
if (lines.length < 2) {···
return;
}
✓ Negative was executed (else)
}···

file.getProgram().selectTokensByType('Whitespace').some(function(whitespace) {
if (lines.length < 2) {
return;
}
Function (anonymous_1319)
✓ Was called
file.getProgram().selectTokensByType('Whitespace').some(function(whitespace) {···
LINE_BREAKS.lastIndex = 0;
var match;
while ((match = LINE_BREAKS.exec(whitespace.value)) !== null) {
if (match[0] !== this._allowedLineBreak) {
errors.add('Invalid line break', whitespace, match.index);
return this._reportOncePerFile;
}
}
}, this);
file.getProgram().selectTokensByType('Whitespace').some(function(whitespace) {
LINE_BREAKS.lastIndex = 0;
var match;
while ((match = LINE_BREAKS.exec(whitespace.value)) !== null) {
Branch IfStatement
✓ Positive was executed (if)
if (match[0] !== this._allowedLineBreak) {···
errors.add('Invalid line break', whitespace, match.index);
return this._reportOncePerFile;
}
✓ Negative was executed (else)
}···
}
if (match[0] !== this._allowedLineBreak) {
errors.add('Invalid line break', whitespace, match.index);
return this._reportOncePerFile;
}
}
}, this);
}
};
validate-newline-after-array-elements.js
/**
* Requires each element in array on a single line when array length is more than passed maximum
* number or array fills more than one line.
*
* Types: `Boolean`, `Integer`, `Object`
*
* Values:
* - `true`: setting this is the same as validating the rule using `{maximum: Infinity, ignoreBrackets: false}`
* - `Integer`: setting this is the same as validating the rule using `{maximum: Integer, ignoreBrackets: false}`
* - `Object`:
* - `maximum`
* - `Integer` specifies the maximum number of elements that a single line array can contain
* - `ignoreBrackets`
* - `true` specifies that the `[` and `]` brackets can be placed on the same line as the array elements
*
* #### Example
*
* ```js
* "validateNewlineAfterArrayElements": {
* "maximum": 3
* }
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = [{a: 1}, [2], '3', 4, 5, 6];
* var x = [
* {a: 1},
* [2],
* '3',
* 4
* ];
* ```
*
* ##### Invalid for mode `true`
*
* ```js
* var x = [1,
* 2];
* ```
*
* ##### Valid for mode `3`
*
* ```js
* var x = [{a: 1}, [2], '3'];
* var x = [
* 1,
* 2,
* 3,
* 4
* ];
* ```
*
* ##### Invalid for mode `3`
*
* ```js
* var x = [1, 2, 3, 4];
* var x = [1,
* 2,
* 3];
* var x = [
* 1, 2
* ];
* ```
*
* ##### Valid for mode `{maximum: 2, ignoreBrackets: true}`
*
* ```js
* var x = [{a: 1}, [2]];
* var x = [1,
* 2,
* 3];
* ```
*
* ##### Invalid for mode `{maximum: 2, ignoreBrackets: true}`
*
* ```js
* var x = [1, 2, 3];
* var x = [1, 2,
* 3];
* var x = [1,
* 2, 3];
* ```
*/
var assert = require('assert');
Function (anonymous_1320)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1321)
✓ Was called
configure: function(opts) {···
assert(
opts === true ||
typeof opts === 'number' && opts >= 1 ||
typeof opts === 'object',
this.getOptionName() + ' option requires maximal number of items ' +
'or true value either should be removed'
);
if (typeof opts === 'object') {
this._options = {
maximum: Infinity,
ignoreBrackets: false
};

if ('maximum' in opts) {
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
'maximum property requires a positive number or should be removed');
this._options.maximum = opts.maximum;
}

if ('ignoreBrackets' in opts) {
assert(opts.ignoreBrackets === true,
'ignoreBrackets property requires true value or should be removed');
this._options.ignoreBrackets = true;
}
} else {
this._options = {
maximum: opts === true ? Infinity : opts,
ignoreBrackets: false
};
}
},
configure: function(opts) {
assert(
Branch LogicalExpression
✓ Was returned
typeof opts === 'object',
✓ Was returned
opts === true ||···
typeof opts === 'number' && opts >= 1 ||
Branch LogicalExpression
✓ Was returned
typeof opts === 'number' && opts >= 1 ||
✓ Was returned
opts === true ||
opts === true ||
Branch LogicalExpression
✓ Was returned
typeof opts === 'number' && opts >= 1 ||
✓ Was returned
typeof opts === 'number' && opts >= 1 ||
typeof opts === 'number' && opts >= 1 ||
typeof opts === 'object',
this.getOptionName() + ' option requires maximal number of items ' +
'or true value either should be removed'
);
Branch IfStatement
✓ Positive was executed (if)
if (typeof opts === 'object') {···
this._options = {
maximum: Infinity,
ignoreBrackets: false
};

if ('maximum' in opts) {
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
'maximum property requires a positive number or should be removed');
this._options.maximum = opts.maximum;
}

if ('ignoreBrackets' in opts) {
assert(opts.ignoreBrackets === true,
'ignoreBrackets property requires true value or should be removed');
this._options.ignoreBrackets = true;
}
} else {
✓ Negative was executed (else)
} else {···
this._options = {
maximum: opts === true ? Infinity : opts,
ignoreBrackets: false
};
}
if (typeof opts === 'object') {
this._options = {
maximum: Infinity,
ignoreBrackets: false
};
Branch IfStatement
✓ Positive was executed (if)
if ('maximum' in opts) {···
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
'maximum property requires a positive number or should be removed');
this._options.maximum = opts.maximum;
}
✓ Negative was executed (else)
}···

if ('ignoreBrackets' in opts) {
if ('maximum' in opts) {
Branch LogicalExpression
✓ Was returned
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
✓ Was returned
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
assert(typeof opts.maximum === 'number' && opts.maximum >= 1,
'maximum property requires a positive number or should be removed');
this._options.maximum = opts.maximum;
}
Branch IfStatement
✓ Positive was executed (if)
if ('ignoreBrackets' in opts) {···
assert(opts.ignoreBrackets === true,
'ignoreBrackets property requires true value or should be removed');
this._options.ignoreBrackets = true;
}
✓ Negative was executed (else)
}···
} else {
if ('ignoreBrackets' in opts) {
assert(opts.ignoreBrackets === true,
'ignoreBrackets property requires true value or should be removed');
this._options.ignoreBrackets = true;
}
} else {
this._options = {
Branch ConditionalExpression
✓ Positive was returned (? ...)
maximum: opts === true ? Infinity : opts,
✓ Negative was returned (: ...)
maximum: opts === true ? Infinity : opts,
maximum: opts === true ? Infinity : opts,
ignoreBrackets: false
};
}
},
Function (anonymous_1322)
✓ Was called
getOptionName: function() {···
return 'validateNewlineAfterArrayElements';
},
getOptionName: function() {
return 'validateNewlineAfterArrayElements';
},
Function (anonymous_1323)
✓ Was called
check: function(file, errors) {···
var maximum = this._options.maximum;
var ignoreBrackets = this._options.ignoreBrackets;

file.iterateNodesByType(['ArrayExpression'], function(node) {
var els = node.elements;
var firstEl = els[0];
var lastEl = els[els.length - 1];
var bracket;
var elToken;

if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {
return;
}

if (!ignoreBrackets) {
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
bracket = file.getFirstNodeToken(node);
elToken = file.getNextToken(bracket);

errors.assert.differentLine({
token: bracket,
nextToken: elToken,
message: 'First element should be placed on new line'
});
}
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
bracket = file.getLastNodeToken(node);
elToken = file.getPrevToken(bracket);

errors.assert.differentLine({
token: elToken,
nextToken: bracket,
message: 'Closing bracket should be placed on new line'
});
}
}

els.forEach(function(elem) {
var elToken;
var comma;

if (!elem) {
// skip holes
return;
}

if (firstEl !== elem) {
elToken = file.getFirstNodeToken(elem);
comma = file.getPrevToken(elToken);

errors.assert.differentLine({
token: comma,
nextToken: elToken,
message: 'Multiple elements at a single line in multiline array'
});
}
});
});
}
check: function(file, errors) {
var maximum = this._options.maximum;
var ignoreBrackets = this._options.ignoreBrackets;
Function (anonymous_1324)
✓ Was called
file.iterateNodesByType(['ArrayExpression'], function(node) {···
var els = node.elements;
var firstEl = els[0];
var lastEl = els[els.length - 1];
var bracket;
var elToken;

if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {
return;
}

if (!ignoreBrackets) {
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
bracket = file.getFirstNodeToken(node);
elToken = file.getNextToken(bracket);

errors.assert.differentLine({
token: bracket,
nextToken: elToken,
message: 'First element should be placed on new line'
});
}
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
bracket = file.getLastNodeToken(node);
elToken = file.getPrevToken(bracket);

errors.assert.differentLine({
token: elToken,
nextToken: bracket,
message: 'Closing bracket should be placed on new line'
});
}
}

els.forEach(function(elem) {
var elToken;
var comma;

if (!elem) {
// skip holes
return;
}

if (firstEl !== elem) {
elToken = file.getFirstNodeToken(elem);
comma = file.getPrevToken(elToken);

errors.assert.differentLine({
token: comma,
nextToken: elToken,
message: 'Multiple elements at a single line in multiline array'
});
}
});
});
file.iterateNodesByType(['ArrayExpression'], function(node) {
var els = node.elements;
var firstEl = els[0];
var lastEl = els[els.length - 1];
var bracket;
var elToken;
Branch IfStatement
✓ Positive was executed (if)
if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {···
return;
}
✓ Negative was executed (else)
}···

if (!ignoreBrackets) {
Branch LogicalExpression
✓ Was returned
if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {
✓ Was returned
if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {
if (els.length <= maximum && node.getLoc().start.line === node.getLoc().end.line) {
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (!ignoreBrackets) {···
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
bracket = file.getFirstNodeToken(node);
elToken = file.getNextToken(bracket);

errors.assert.differentLine({
token: bracket,
nextToken: elToken,
message: 'First element should be placed on new line'
});
}
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
bracket = file.getLastNodeToken(node);
elToken = file.getPrevToken(bracket);

errors.assert.differentLine({
token: elToken,
nextToken: bracket,
message: 'Closing bracket should be placed on new line'
});
}
}
✓ Negative was executed (else)
}···

els.forEach(function(elem) {
if (!ignoreBrackets) {
Branch IfStatement
✓ Positive was executed (if)
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {···
bracket = file.getFirstNodeToken(node);
elToken = file.getNextToken(bracket);

errors.assert.differentLine({
token: bracket,
nextToken: elToken,
message: 'First element should be placed on new line'
});
}
✓ Negative was executed (else)
}···
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
Branch LogicalExpression
✓ Was returned
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
✓ Was returned
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
if (firstEl && firstEl.getLoc().start.line === node.getLoc().start.line) {
bracket = file.getFirstNodeToken(node);
elToken = file.getNextToken(bracket);
errors.assert.differentLine({
token: bracket,
nextToken: elToken,
message: 'First element should be placed on new line'
});
}
Branch IfStatement
✓ Positive was executed (if)
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {···
bracket = file.getLastNodeToken(node);
elToken = file.getPrevToken(bracket);

errors.assert.differentLine({
token: elToken,
nextToken: bracket,
message: 'Closing bracket should be placed on new line'
});
}
✓ Negative was executed (else)
}···
}
Branch LogicalExpression
✓ Was returned
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
✓ Was returned
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
if (lastEl && lastEl.getLoc().end.line === node.getLoc().end.line) {
bracket = file.getLastNodeToken(node);
elToken = file.getPrevToken(bracket);
errors.assert.differentLine({
token: elToken,
nextToken: bracket,
message: 'Closing bracket should be placed on new line'
});
}
}
Function (anonymous_1325)
✓ Was called
els.forEach(function(elem) {···
var elToken;
var comma;

if (!elem) {
// skip holes
return;
}

if (firstEl !== elem) {
elToken = file.getFirstNodeToken(elem);
comma = file.getPrevToken(elToken);

errors.assert.differentLine({
token: comma,
nextToken: elToken,
message: 'Multiple elements at a single line in multiline array'
});
}
});
els.forEach(function(elem) {
var elToken;
var comma;
Branch IfStatement
✓ Positive was executed (if)
if (!elem) {···
// skip holes
return;
}
✓ Negative was executed (else)
}···

if (firstEl !== elem) {
if (!elem) {
// skip holes
return;
}
Branch IfStatement
✓ Positive was executed (if)
if (firstEl !== elem) {···
elToken = file.getFirstNodeToken(elem);
comma = file.getPrevToken(elToken);

errors.assert.differentLine({
token: comma,
nextToken: elToken,
message: 'Multiple elements at a single line in multiline array'
});
}
✓ Negative was executed (else)
}···
});
if (firstEl !== elem) {
elToken = file.getFirstNodeToken(elem);
comma = file.getPrevToken(elToken);
errors.assert.differentLine({
token: comma,
nextToken: elToken,
message: 'Multiple elements at a single line in multiline array'
});
}
});
});
}
};
validate-order-in-object-keys.js
/**
* Validates the order in object keys.
*
* Types: `Boolean` or `String`
*
* Values:
* - `true` (alias to `asc`)
* - `"asc"`: requires sorting in ascending order
* - `"asc-insensitive"`: requires sorting in ascending order (case-insensitive)
* - `"asc-natural"`: requires sorting in ascending natural order
* - `"desc"`: requires sorting in descending order
* - `"desc-insensitive"`: requires sorting in descending order (case-insensitive)
* - `"desc-natural"`: requires sorting in descending natural order
*
* #### Example
*
* ```js
* "validateOrderInObjectKeys": "asc"
* ```
*
* ##### Valid
*
* ```js
* var x = {
* x: 'foo',
* y: 'bar'
* }
* ```
*
* ##### Invalid
*
* ```js
* var x = {
* y: 'foo',
* x: 'bar'
* }
* ```
*/
var assert = require('assert');
var naturalSort = require('natural-compare');
/**
* Sort in ascending order.
*/
Function asc
✓ Was called
function asc(a, b) {···
return String(a) < String(b) ? -1 : 1;
}
function asc(a, b) {
Branch ConditionalExpression
✓ Positive was returned (? ...)
return String(a) < String(b) ? -1 : 1;
✓ Negative was returned (: ...)
return String(a) < String(b) ? -1 : 1;
return String(a) < String(b) ? -1 : 1;
}
/**
* Sort in ascending order (case-insensitive).
*/
Function ascInsensitive
✓ Was called
function ascInsensitive(a, b) {···
var lowercaseA = String(a).toLowerCase();
var lowercaseB = String(b).toLowerCase();

if (lowercaseA < lowercaseB) {
return -1;
}

if (lowercaseA > lowercaseB) {
return 1;
}

return asc(a, b);
}
function ascInsensitive(a, b) {
var lowercaseA = String(a).toLowerCase();
var lowercaseB = String(b).toLowerCase();
Branch IfStatement
✓ Positive was executed (if)
if (lowercaseA < lowercaseB) {···
return -1;
}
✓ Negative was executed (else)
}···

if (lowercaseA > lowercaseB) {
if (lowercaseA < lowercaseB) {
return -1;
}
Branch IfStatement
✓ Positive was executed (if)
if (lowercaseA > lowercaseB) {···
return 1;
}
✓ Negative was executed (else)
}···

return asc(a, b);
if (lowercaseA > lowercaseB) {
return 1;
}
return asc(a, b);
}
/**
* Natural sort in ascending order.
*/
Function ascNatural
✓ Was called
function ascNatural(a, b) {···
return naturalSort(a, b);
}
function ascNatural(a, b) {
return naturalSort(a, b);
}
/**
* Native sort in descending order.
*/
Function desc
✓ Was called
function desc(a, b) {···
return asc(a, b) * -1;
}
function desc(a, b) {
return asc(a, b) * -1;
}
/**
* Sort in descending order (case-insensitive).
*/
Function descInsensitive
✓ Was called
function descInsensitive(a, b) {···
return ascInsensitive(a, b) * -1;
}
function descInsensitive(a, b) {
return ascInsensitive(a, b) * -1;
}
/**
* Native sort in descending order.
*/
Function descNatural
✓ Was called
function descNatural(a, b) {···
return naturalSort(a, b) * -1;
}
function descNatural(a, b) {
return naturalSort(a, b) * -1;
}
/**
* Available sort methods.
*/
var methods = {
asc: asc,
'asc-insensitive': ascInsensitive,
'asc-natural': ascNatural,
desc: desc,
'desc-insensitive': descInsensitive,
'desc-natural': descNatural
};
Function (anonymous_1332)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1333)
✓ Was called
configure: function(options) {···
assert(
options === true || Object.keys(methods).indexOf(options) !== -1,
this.getOptionName() + ' option requires a true value or should be removed'
);

this._sort = methods[options] || methods.asc;
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
options === true || Object.keys(methods).indexOf(options) !== -1,
✗ Was not returned
options === true || Object.keys(methods).indexOf(options) !== -1,
options === true || Object.keys(methods).indexOf(options) !== -1,
this.getOptionName() + ' option requires a true value or should be removed'
);
Branch LogicalExpression
✗ Was not returned
this._sort = methods[options] || methods.asc;
✓ Was returned
this._sort = methods[options] || methods.asc;
this._sort = methods[options] || methods.asc;
},
Function (anonymous_1334)
✓ Was called
getOptionName: function() {···
return 'validateOrderInObjectKeys';
},
getOptionName: function() {
return 'validateOrderInObjectKeys';
},
Function (anonymous_1335)
✓ Was called
check: function(file, errors) {···
var sort = this._sort;

file.iterateNodesByType('ObjectExpression', function(node) {
var keys = node.properties.map(function(property) {
return (property.key.name || property.key.value);
});

var sorted = keys.slice(0).sort(sort);
var unsorted;

for (var i = 0; i < keys.length; i++) {
if (keys[i] !== sorted[i]) {
unsorted = i;

break;
}
}

if (undefined !== unsorted) {
errors.add(
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
node.properties[unsorted]
);
}
});
}
check: function(file, errors) {
var sort = this._sort;
Function (anonymous_1336)
✓ Was called
file.iterateNodesByType('ObjectExpression', function(node) {···
var keys = node.properties.map(function(property) {
return (property.key.name || property.key.value);
});

var sorted = keys.slice(0).sort(sort);
var unsorted;

for (var i = 0; i < keys.length; i++) {
if (keys[i] !== sorted[i]) {
unsorted = i;

break;
}
}

if (undefined !== unsorted) {
errors.add(
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
node.properties[unsorted]
);
}
});
file.iterateNodesByType('ObjectExpression', function(node) {
Function (anonymous_1337)
✓ Was called
var keys = node.properties.map(function(property) {···
return (property.key.name || property.key.value);
});
var keys = node.properties.map(function(property) {
Branch LogicalExpression
✓ Was returned
return (property.key.name || property.key.value);
✓ Was returned
return (property.key.name || property.key.value);
return (property.key.name || property.key.value);
});
var sorted = keys.slice(0).sort(sort);
var unsorted;
for (var i = 0; i < keys.length; i++) {
Branch IfStatement
✓ Positive was executed (if)
if (keys[i] !== sorted[i]) {···
unsorted = i;

break;
}
✓ Negative was executed (else)
}···
}
if (keys[i] !== sorted[i]) {
unsorted = i;
break;
}
}
Branch IfStatement
✓ Positive was executed (if)
if (undefined !== unsorted) {···
errors.add(
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
node.properties[unsorted]
);
}
✓ Negative was executed (else)
}···
});
if (undefined !== unsorted) {
errors.add(
Branch ConditionalExpression
✓ Positive was returned (? ...)
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
✓ Negative was returned (: ...)
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
'Object keys must be in ' + (/asc/.test(sort.name) ? 'ascending' : 'descending') + ' order',
node.properties[unsorted]
);
}
});
}
};
validate-parameter-separator.js
/**
* Enable validation of separators between function parameters. Will ignore newlines.
*
* Type: `String`
*
* Values:
*
* - `","`: function parameters are immediately followed by a comma
* - `", "`: function parameters are immediately followed by a comma and then a space
* - `" ,"`: function parameters are immediately followed by a space and then a comma
* - `" , "`: function parameters are immediately followed by a space, a comma, and then a space
*
* #### Example
*
* ```js
* "validateParameterSeparator": ", "
* ```
*
* ##### Valid
*
* ```js
* function a(b, c) {}
* ```
*
* ##### Invalid
*
* ```js
* function a(b , c) {}
* ```
*/
var assert = require('assert');
Function (anonymous_1338)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1339)
✓ Was called
configure: function(options) {···
assert(
typeof options === 'string' && /^[ ]?,[ ]?$/.test(options),
this.getOptionName() + ' option requires string value containing only a comma and optional spaces'
);

this._separator = options;
},
configure: function(options) {
assert(
Branch LogicalExpression
✓ Was returned
typeof options === 'string' && /^[ ]?,[ ]?$/.test(options),
✓ Was returned
typeof options === 'string' && /^[ ]?,[ ]?$/.test(options),
typeof options === 'string' && /^[ ]?,[ ]?$/.test(options),
this.getOptionName() + ' option requires string value containing only a comma and optional spaces'
);
this._separator = options;
},
Function (anonymous_1340)
✓ Was called
getOptionName: function() {···
return 'validateParameterSeparator';
},
getOptionName: function() {
return 'validateParameterSeparator';
},
Function (anonymous_1341)
✓ Was called
check: function(file, errors) {···

var separators = this._separator.split(',');
var whitespaceBeforeComma = Boolean(separators.shift());
var whitespaceAfterComma = Boolean(separators.pop());

file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {

node.params.forEach(function(paramNode) {

var prevParamToken = file.getFirstNodeToken(paramNode);
var punctuatorToken = file.getNextToken(prevParamToken);

if (punctuatorToken.value === ',') {

if (whitespaceBeforeComma) {
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}

var nextParamToken = file.getNextToken(punctuatorToken);

if (whitespaceAfterComma) {
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
}
});
});
}
check: function(file, errors) {
var separators = this._separator.split(',');
var whitespaceBeforeComma = Boolean(separators.shift());
var whitespaceAfterComma = Boolean(separators.pop());
Function (anonymous_1342)
✓ Was called
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {···

node.params.forEach(function(paramNode) {

var prevParamToken = file.getFirstNodeToken(paramNode);
var punctuatorToken = file.getNextToken(prevParamToken);

if (punctuatorToken.value === ',') {

if (whitespaceBeforeComma) {
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}

var nextParamToken = file.getNextToken(punctuatorToken);

if (whitespaceAfterComma) {
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
}
});
});
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
Function (anonymous_1343)
✓ Was called
node.params.forEach(function(paramNode) {···

var prevParamToken = file.getFirstNodeToken(paramNode);
var punctuatorToken = file.getNextToken(prevParamToken);

if (punctuatorToken.value === ',') {

if (whitespaceBeforeComma) {
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}

var nextParamToken = file.getNextToken(punctuatorToken);

if (whitespaceAfterComma) {
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
}
});
node.params.forEach(function(paramNode) {
var prevParamToken = file.getFirstNodeToken(paramNode);
var punctuatorToken = file.getNextToken(prevParamToken);
Branch IfStatement
✓ Positive was executed (if)
if (punctuatorToken.value === ',') {···

if (whitespaceBeforeComma) {
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}

var nextParamToken = file.getNextToken(punctuatorToken);

if (whitespaceAfterComma) {
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
}
✓ Negative was executed (else)
}···
});
if (punctuatorToken.value === ',') {
Branch IfStatement
✓ Positive was executed (if)
if (whitespaceBeforeComma) {···
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
✓ Negative was executed (else)
} else {···
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}
if (whitespaceBeforeComma) {
errors.assert.spacesBetween({
token: prevParamToken,
nextToken: punctuatorToken,
exactly: 1,
message: 'One space required after function parameter \'' + prevParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: prevParamToken,
nextToken: punctuatorToken,
message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
});
}
var nextParamToken = file.getNextToken(punctuatorToken);
Branch IfStatement
✓ Positive was executed (if)
if (whitespaceAfterComma) {···
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
✓ Negative was executed (else)
} else {···
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
if (whitespaceAfterComma) {
errors.assert.spacesBetween({
token: punctuatorToken,
nextToken: nextParamToken,
exactly: 1,
message: 'One space required before function parameter \'' + nextParamToken.value + '\''
});
} else {
errors.assert.noWhitespaceBetween({
token: punctuatorToken,
nextToken: nextParamToken,
message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
});
}
}
});
});
}
};
validate-quote-marks.js
/**
* Requires all quote marks to be either the supplied value, or consistent if `true`
*
* Types: `Boolean`, `String` or `Object`
*
* Values:
* - `"\""`: all strings require double quotes
* - `"'"`: all strings require single quotes
* - `true`: all strings require the quote mark first encountered in the source code
* - `Object`:
* - `escape`: allow the "other" quote mark to be used, but only to avoid having to escape
* - `mark`: the same effect as the non-object values
* - `ignoreJSX`: ignore JSX nodes
*
* JSHint: [`quotmark`](http://jshint.com/docs/options/#quotmark)
*
* #### Example
*
* ```js
* "validateQuoteMarks": "\""
* ```
* ```js
* "validateQuoteMarks": { "mark": "\"", "escape": true }
* ```
*
* ##### Valid example for mode `{ "mark": "\"", "escape": true }`
*
* ```js
* var x = "x";
* var y = '"x"';
* ```
*
* ##### Invalid example for mode `{ "mark": "\"", "escape": true }`
*
* ```js
* var x = "x";
* var y = 'x';
* ```
*
* ##### Valid example for mode `{ "mark": "'", "escape": true, "ignoreJSX": true }`
*
* ```js
* <div className="flex-card__header">{this.props.children}</div>;
* ```
*
* ##### Valid example for mode `"\""` or mode `true`
*
* ```js
* var x = "x";
* ```
*
* ##### Valid example for mode `"'"` or mode `true`
*
* ```js
* var x = 'x';
* ```
*
* ##### Invalid example for mode `true`
*
* ```js
* var x = "x", y = 'y';
* ```
*/
var assert = require('assert');
var cst = require('cst');
Function (anonymous_1344)
✓ Was called
module.exports = function() {};
module.exports = function() {};
module.exports.prototype = {
Function (anonymous_1345)
✓ Was called
configure: function(quoteMark) {···
this._allowEscape = false;
this._ignoreJSX = false;

if (typeof quoteMark === 'object') {
assert(
typeof quoteMark.escape === 'boolean' && quoteMark.mark !== undefined,
this.getOptionName() + ' option requires the "escape" and "mark" property to be defined'
);
this._allowEscape = quoteMark.escape;

if (quoteMark.ignoreJSX) {
this._ignoreJSX = quoteMark.ignoreJSX;
}

quoteMark = quoteMark.mark;
}

assert(
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
this.getOptionName() + ' option requires \'"\', "\'", or boolean true'
);

assert(
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
this.getOptionName() + ' option requires \'"\', "\'", or boolean true'
);

this._quoteMark = quoteMark;
},
configure: function(quoteMark) {
this._allowEscape = false;
this._ignoreJSX = false;
Branch IfStatement
✓ Positive was executed (if)
if (typeof quoteMark === 'object') {···
assert(
typeof quoteMark.escape === 'boolean' && quoteMark.mark !== undefined,
this.getOptionName() + ' option requires the "escape" and "mark" property to be defined'
);
this._allowEscape = quoteMark.escape;

if (quoteMark.ignoreJSX) {
this._ignoreJSX = quoteMark.ignoreJSX;
}

quoteMark = quoteMark.mark;
}
✓ Negative was executed (else)
}···

assert(
if (typeof quoteMark === 'object') {
assert(
Branch LogicalExpression
✓ Was returned
typeof quoteMark.escape === 'boolean' && quoteMark.mark !== undefined,
✓ Was returned
typeof quoteMark.escape === 'boolean' && quoteMark.mark !== undefined,
typeof quoteMark.escape === 'boolean' && quoteMark.mark !== undefined,
this.getOptionName() + ' option requires the "escape" and "mark" property to be defined'
);
this._allowEscape = quoteMark.escape;
Branch IfStatement
✓ Positive was executed (if)
if (quoteMark.ignoreJSX) {···
this._ignoreJSX = quoteMark.ignoreJSX;
}
✓ Negative was executed (else)
}···

quoteMark = quoteMark.mark;
if (quoteMark.ignoreJSX) {
this._ignoreJSX = quoteMark.ignoreJSX;
}
quoteMark = quoteMark.mark;
}
assert(
Branch LogicalExpression
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
Branch LogicalExpression
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
this.getOptionName() + ' option requires \'"\', "\'", or boolean true'
);
assert(
Branch LogicalExpression
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
Branch LogicalExpression
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
✓ Was returned
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
quoteMark === '"' || quoteMark === '\'' || quoteMark === true,
this.getOptionName() + ' option requires \'"\', "\'", or boolean true'
);
this._quoteMark = quoteMark;
},
Function (anonymous_1346)
✓ Was called
getOptionName: function() {···
return 'validateQuoteMarks';
},
getOptionName: function() {
return 'validateQuoteMarks';
},
Function (anonymous_1347)
✓ Was called
check: function(file, errors) {···
var quoteMark = this._quoteMark;
var allowEscape = this._allowEscape;
var ignoreJSX = this._ignoreJSX;

var opposite = {
'"': '\'',
'\'': '"'
};
file.iterateTokensByType('String', function(token) {
if (
ignoreJSX &&
token.parentElement.type === 'StringLiteral' &&
token.parentElement.parentElement.type === 'JSXAttribute'
) {
return;
}

var str = token.getSourceCode();
var mark = str[0];
var stripped = str.substring(1, str.length - 1);

if (quoteMark === true) {
quoteMark = mark;
}

if (mark !== quoteMark) {
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
return;
}

errors.cast({
message: 'Invalid quote mark found',
element: token,
additional: token
});
}
});
},
check: function(file, errors) {
var quoteMark = this._quoteMark;
var allowEscape = this._allowEscape;
var ignoreJSX = this._ignoreJSX;
var opposite = {
'"': '\'',
'\'': '"'
};
Function (anonymous_1348)
✓ Was called
file.iterateTokensByType('String', function(token) {···
if (
ignoreJSX &&
token.parentElement.type === 'StringLiteral' &&
token.parentElement.parentElement.type === 'JSXAttribute'
) {
return;
}

var str = token.getSourceCode();
var mark = str[0];
var stripped = str.substring(1, str.length - 1);

if (quoteMark === true) {
quoteMark = mark;
}

if (mark !== quoteMark) {
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
return;
}

errors.cast({
message: 'Invalid quote mark found',
element: token,
additional: token
});
}
});
file.iterateTokensByType('String', function(token) {
Branch IfStatement
✓ Positive was executed (if)
) {···
return;
}
✓ Negative was executed (else)
}···

var str = token.getSourceCode();
if (
Branch LogicalExpression
✓ Was returned
token.parentElement.parentElement.type === 'JSXAttribute'
✓ Was returned
ignoreJSX &&···
token.parentElement.type === 'StringLiteral' &&
Branch LogicalExpression
✓ Was returned
token.parentElement.type === 'StringLiteral' &&
✓ Was returned
ignoreJSX &&
ignoreJSX &&
token.parentElement.type === 'StringLiteral' &&
token.parentElement.parentElement.type === 'JSXAttribute'
) {
return;
}
var str = token.getSourceCode();
var mark = str[0];
var stripped = str.substring(1, str.length - 1);
Branch IfStatement
✓ Positive was executed (if)
if (quoteMark === true) {···
quoteMark = mark;
}
✓ Negative was executed (else)
}···

if (mark !== quoteMark) {
if (quoteMark === true) {
quoteMark = mark;
}
Branch IfStatement
✓ Positive was executed (if)
if (mark !== quoteMark) {···
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
return;
}

errors.cast({
message: 'Invalid quote mark found',
element: token,
additional: token
});
}
✓ Negative was executed (else)
}···
});
if (mark !== quoteMark) {
Branch IfStatement
✓ Positive was executed (if)
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {···
return;
}
✓ Negative was executed (else)
}···

errors.cast({
Branch LogicalExpression
✓ Was returned
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
✓ Was returned
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
if (allowEscape && stripped.indexOf(opposite[mark]) > -1) {
return;
}
errors.cast({
message: 'Invalid quote mark found',
element: token,
additional: token
});
}
});
},
Function (anonymous_1349)
✓ Was called
_fix: function(file, error) {···
var token = error.additional;

var fixer = require(this._quoteMark === '"' ? 'to-double-quotes' : 'to-single-quotes');
var newToken = cst.Token.createFromToken({
type: 'String',
value: token.value,
sourceCode: fixer(token.getSourceCode())
});

token.parentElement.replaceChild(newToken, token);
}
_fix: function(file, error) {
var token = error.additional;
Branch ConditionalExpression
✓ Positive was returned (? ...)
var fixer = require(this._quoteMark === '"' ? 'to-double-quotes' : 'to-single-quotes');
✓ Negative was returned (: ...)
var fixer = require(this._quoteMark === '"' ? 'to-double-quotes' : 'to-single-quotes');
var fixer = require(this._quoteMark === '"' ? 'to-double-quotes' : 'to-single-quotes');
var newToken = cst.Token.createFromToken({
type: 'String',
value: token.value,
sourceCode: fixer(token.getSourceCode())
});
token.parentElement.replaceChild(newToken, token);
}
};
summary.js
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_1350)
✓ Was called
module.exports = function(errorsCollection) {···
var Table = require('cli-table');
var hasError = false;

var errorsByRule = {};
var style = {
'padding-left': 0,
'padding-right': 0,
'head': ['yellow'],
'border': ['red'],
'compact': false
};

var errorsByFileTable = new Table({
'head': ['Path', 'Total Errors'],
'colAligns': [
'middle',
'middle',
'middle'
],
'colWidths': [62, 18],
'style': style
});

var errorsByRuleTable = new Table({
'head': ['Rule', 'Total Errors', 'Files With Errors'],
'colAligns': [
'middle',
'middle',
'middle'
],
'colWidths': [49, 12, 18],
'style': style
});

errorsCollection.forEach(function(errors) {
var fileName = errors.getFilename();
if (!errors.isEmpty()) {
hasError = true;
errorsByFileTable.push([fileName, errors.getErrorCount()]);
errors.getErrorList().forEach(function(error) {
if (error.rule in errorsByRule) {
errorsByRule[error.rule] .count += 1;
} else {
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
errorsByRule[error.rule].files[fileName] = 1;
});
}
});

var totalErrors = 0;
var totalFilesWithErrors = 0;
Object.getOwnPropertyNames(errorsByRule).forEach(function(ruleName) {
var fileCount = Object.getOwnPropertyNames(errorsByRule[ruleName].files).length;
errorsByRuleTable.push([ruleName, errorsByRule[ruleName].count, fileCount]);
totalErrors += errorsByRule[ruleName].count;
totalFilesWithErrors += fileCount;
});
errorsByRuleTable.push(['All', totalErrors, totalFilesWithErrors]);

if (hasError === false) {
console.log('No code style errors found.');
} else {
console.log(errorsByFileTable.toString());
console.log(errorsByRuleTable.toString());
}
};
module.exports = function(errorsCollection) {
var Table = require('cli-table');
var hasError = false;
var errorsByRule = {};
var style = {
'padding-left': 0,
'padding-right': 0,
'head': ['yellow'],
'border': ['red'],
'compact': false
};
var errorsByFileTable = new Table({
'head': ['Path', 'Total Errors'],
'colAligns': [
'middle',
'middle',
'middle'
],
'colWidths': [62, 18],
'style': style
});
var errorsByRuleTable = new Table({
'head': ['Rule', 'Total Errors', 'Files With Errors'],
'colAligns': [
'middle',
'middle',
'middle'
],
'colWidths': [49, 12, 18],
'style': style
});
Function (anonymous_1351)
✓ Was called
errorsCollection.forEach(function(errors) {···
var fileName = errors.getFilename();
if (!errors.isEmpty()) {
hasError = true;
errorsByFileTable.push([fileName, errors.getErrorCount()]);
errors.getErrorList().forEach(function(error) {
if (error.rule in errorsByRule) {
errorsByRule[error.rule] .count += 1;
} else {
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
errorsByRule[error.rule].files[fileName] = 1;
});
}
});
errorsCollection.forEach(function(errors) {
var fileName = errors.getFilename();
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
hasError = true;
errorsByFileTable.push([fileName, errors.getErrorCount()]);
errors.getErrorList().forEach(function(error) {
if (error.rule in errorsByRule) {
errorsByRule[error.rule] .count += 1;
} else {
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
errorsByRule[error.rule].files[fileName] = 1;
});
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
hasError = true;
errorsByFileTable.push([fileName, errors.getErrorCount()]);
Function (anonymous_1352)
✓ Was called
errors.getErrorList().forEach(function(error) {···
if (error.rule in errorsByRule) {
errorsByRule[error.rule] .count += 1;
} else {
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
errorsByRule[error.rule].files[fileName] = 1;
});
errors.getErrorList().forEach(function(error) {
Branch IfStatement
✓ Positive was executed (if)
if (error.rule in errorsByRule) {···
errorsByRule[error.rule] .count += 1;
} else {
✓ Negative was executed (else)
} else {···
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
if (error.rule in errorsByRule) {
errorsByRule[error.rule] .count += 1;
} else {
errorsByRule[error.rule] = {
count: 1,
files: {}
};
}
errorsByRule[error.rule].files[fileName] = 1;
});
}
});
var totalErrors = 0;
var totalFilesWithErrors = 0;
Function (anonymous_1353)
✓ Was called
Object.getOwnPropertyNames(errorsByRule).forEach(function(ruleName) {···
var fileCount = Object.getOwnPropertyNames(errorsByRule[ruleName].files).length;
errorsByRuleTable.push([ruleName, errorsByRule[ruleName].count, fileCount]);
totalErrors += errorsByRule[ruleName].count;
totalFilesWithErrors += fileCount;
});
Object.getOwnPropertyNames(errorsByRule).forEach(function(ruleName) {
var fileCount = Object.getOwnPropertyNames(errorsByRule[ruleName].files).length;
errorsByRuleTable.push([ruleName, errorsByRule[ruleName].count, fileCount]);
totalErrors += errorsByRule[ruleName].count;
totalFilesWithErrors += fileCount;
});
errorsByRuleTable.push(['All', totalErrors, totalFilesWithErrors]);
Branch IfStatement
✓ Positive was executed (if)
if (hasError === false) {···
console.log('No code style errors found.');
} else {
✓ Negative was executed (else)
} else {···
console.log(errorsByFileTable.toString());
console.log(errorsByRuleTable.toString());
}
if (hasError === false) {
console.log('No code style errors found.');
} else {
console.log(errorsByFileTable.toString());
console.log(errorsByRuleTable.toString());
}
};
text.js
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_1354)
✓ Was called
module.exports = function(errorsCollection) {···
var errorCount = 0;
/**
* Formatting every error set.
*/
errorsCollection.forEach(function(errors) {
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error) + '\n');
});
}
});
if (errorCount) {
/**
* Printing summary.
*/
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
};
module.exports = function(errorsCollection) {
var errorCount = 0;
/**
* Formatting every error set.
*/
Function (anonymous_1355)
✓ Was called
errorsCollection.forEach(function(errors) {···
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error) + '\n');
});
}
});
errorsCollection.forEach(function(errors) {
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
/**
* Formatting every single error.
*/
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error) + '\n');
});
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
/**
* Formatting every single error.
*/
Function (anonymous_1356)
✓ Was called
errors.getErrorList().forEach(function(error) {···
errorCount++;
console.log(errors.explainError(error) + '\n');
});
errors.getErrorList().forEach(function(error) {
errorCount++;
console.log(errors.explainError(error) + '\n');
});
}
});
Branch IfStatement
✓ Positive was executed (if)
if (errorCount) {···
/**
* Printing summary.
*/
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
✓ Negative was executed (else)
}···
};
if (errorCount) {
/**
* Printing summary.
*/
Branch ConditionalExpression
✓ Positive was returned (? ...)
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
✓ Negative was returned (: ...)
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
console.log('\n' + errorCount + ' code style ' + (errorCount === 1 ? 'error' : 'errors') + ' found.');
}
};
unix.js
var util = require('util');
/**
* @param {Errors[]} errorsCollection
*/
Function (anonymous_1357)
✓ Was called
module.exports = function(errorsCollection) {···
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
if (!errors.isEmpty()) {
errors.getErrorList().forEach(function(error) {
console.log(util.format('%s:%d:%d: %s', file, error.line, error.column, error.message));
});
}
});
};
module.exports = function(errorsCollection) {
Function (anonymous_1358)
✓ Was called
errorsCollection.forEach(function(errors) {···
var file = errors.getFilename();
if (!errors.isEmpty()) {
errors.getErrorList().forEach(function(error) {
console.log(util.format('%s:%d:%d: %s', file, error.line, error.column, error.message));
});
}
});
errorsCollection.forEach(function(errors) {
var file = errors.getFilename();
Branch IfStatement
✓ Positive was executed (if)
if (!errors.isEmpty()) {···
errors.getErrorList().forEach(function(error) {
console.log(util.format('%s:%d:%d: %s', file, error.line, error.column, error.message));
});
}
✓ Negative was executed (else)
}···
});
if (!errors.isEmpty()) {
Function (anonymous_1359)
✓ Was called
errors.getErrorList().forEach(function(error) {···
console.log(util.format('%s:%d:%d: %s', file, error.line, error.column, error.message));
});
errors.getErrorList().forEach(function(error) {
console.log(util.format('%s:%d:%d: %s', file, error.line, error.column, error.message));
});
}
});
};
get-cli.js
var resolve = require('resolve');
var cli;
try {
cli = require(
resolve.sync('jscs/lib/cli', { basedir: process.cwd() })
);
} catch (e) {
cli = require('./cli');
}
module.exports = cli;