UNPKG

2.1 kBJavaScriptView Raw
1/**
2 * Ensures that the callback pattern is followed properly
3 * with an Error object (or undefined or null) in the first position.
4 */
5
6'use strict'
7
8// ------------------------------------------------------------------------------
9// Helpers
10// ------------------------------------------------------------------------------
11
12/**
13 * Determine if a node has a possiblity to be an Error object
14 * @param {ASTNode} node ASTNode to check
15 * @returns {boolean} True if there is a chance it contains an Error obj
16 */
17function couldBeError (node) {
18 switch (node.type) {
19 case 'Identifier':
20 case 'CallExpression':
21 case 'NewExpression':
22 case 'MemberExpression':
23 case 'TaggedTemplateExpression':
24 case 'YieldExpression':
25 return true // possibly an error object.
26
27 case 'AssignmentExpression':
28 return couldBeError(node.right)
29
30 case 'SequenceExpression':
31 var exprs = node.expressions
32 return exprs.length !== 0 && couldBeError(exprs[exprs.length - 1])
33
34 case 'LogicalExpression':
35 return couldBeError(node.left) || couldBeError(node.right)
36
37 case 'ConditionalExpression':
38 return couldBeError(node.consequent) || couldBeError(node.alternate)
39
40 default:
41 return node.value === null
42 }
43}
44
45// ------------------------------------------------------------------------------
46// Rule Definition
47// ------------------------------------------------------------------------------
48
49module.exports = {
50 meta: {
51 docs: {
52 url: 'https://github.com/standard/eslint-plugin-standard#rules-explanations'
53 }
54 },
55
56 create: function (context) {
57 var callbackNames = context.options[0] || ['callback', 'cb']
58
59 function isCallback (name) {
60 return callbackNames.indexOf(name) > -1
61 }
62
63 return {
64
65 CallExpression: function (node) {
66 var errorArg = node.arguments[0]
67 var calleeName = node.callee.name
68
69 if (errorArg && !couldBeError(errorArg) && isCallback(calleeName)) {
70 context.report(node, 'Unexpected literal in error position of callback.')
71 }
72 }
73 }
74 }
75}