forked from sindresorhus/eslint-plugin-unicorn
/
no-unsafe-regex.js
71 lines (64 loc) · 1.41 KB
/
no-unsafe-regex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
const safeRegex = require('safe-regex');
const {newExpressionSelector} = require('./selectors/index.js');
const MESSAGE_ID = 'no-unsafe-regex';
const messages = {
[MESSAGE_ID]: 'Unsafe regular expression.',
};
const newRegExpSelector = [
newExpressionSelector('RegExp'),
'[arguments.0.type="Literal"]',
].join('');
const create = () => ({
'Literal[regex]': node => {
// Handle regex literal inside RegExp constructor in the other handler
if (
node.parent.type === 'NewExpression'
&& node.parent.callee.name === 'RegExp'
) {
return;
}
if (!safeRegex(node.value)) {
return {
node,
messageId: MESSAGE_ID,
};
}
},
[newRegExpSelector]: node => {
const arguments_ = node.arguments;
const hasRegExp = arguments_[0].regex;
let pattern;
let flags;
if (hasRegExp) {
({pattern} = arguments_[0].regex);
flags = arguments_[1] && arguments_[1].type === 'Literal'
? arguments_[1].value
: arguments_[0].regex.flags;
} else {
pattern = arguments_[0].value;
flags = arguments_[1] && arguments_[1].type === 'Literal'
? arguments_[1].value
: '';
}
if (!safeRegex(`/${pattern}/${flags}`)) {
return {
node,
messageId: MESSAGE_ID,
};
}
},
});
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'problem',
docs: {
description: 'Disallow unsafe regular expressions.',
},
messages,
},
};