]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-control-regex.js
2 * @fileoverview Rule to forbid control characters from regular expressions.
3 * @author Nicholas C. Zakas
8 const RegExpValidator
= require("regexpp").RegExpValidator
;
9 const collector
= new (class {
12 this._controlChars
= [];
13 this._validator
= new RegExpValidator(this);
17 this._controlChars
= [];
20 onCharacter(start
, end
, cp
) {
24 this._source
.codePointAt(start
) === cp
||
25 this._source
.slice(start
, end
).startsWith("\\x") ||
26 this._source
.slice(start
, end
).startsWith("\\u")
29 this._controlChars
.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`);
33 collectControlChars(regexpStr, flags) {
34 const uFlag = typeof flags === "string" && flags.includes("u");
37 this._source = regexpStr;
38 this._validator.validatePattern(regexpStr, void 0, void 0, uFlag); // Call onCharacter hook
41 // Ignore syntax errors in RegExp.
43 return this._controlChars;
47 //------------------------------------------------------------------------------
49 //------------------------------------------------------------------------------
51 /** @type {import('../shared/types').Rule} */
57 description: "Disallow control characters in regular expressions",
59 url: "https://eslint.org/docs/rules/no-control-regex"
65 unexpected: "Unexpected control character(s) in regular expression: {{controlChars}}."
72 * Get the regex expression
73 * @param {ASTNode} node `Literal
` node to evaluate
74 * @returns {{ pattern: string, flags: string | null } | null} Regex if found (the given node is either a regex literal
75 * or a string literal that is the pattern argument of a RegExp constructor call). Otherwise `null`. If flags cannot be determined,
76 * the `flags
` property will be `null`.
79 function getRegExp(node) {
83 if (typeof node.value === "string" &&
84 (node.parent.type === "NewExpression" || node.parent.type === "CallExpression") &&
85 node.parent.callee.type === "Identifier" &&
86 node.parent.callee.name === "RegExp" &&
87 node.parent.arguments[0] === node
89 const pattern = node.value;
91 node.parent.arguments.length > 1 &&
92 node.parent.arguments[1].type === "Literal" &&
93 typeof node.parent.arguments[1].value === "string"
94 ? node.parent.arguments[1].value
97 return { pattern, flags };
105 const regExp = getRegExp(node);
108 const { pattern, flags } = regExp;
109 const controlCharacters = collector.collectControlChars(pattern, flags);
111 if (controlCharacters.length > 0) {
114 messageId: "unexpected",
116 controlChars: controlCharacters.join(", ")