Blame view
node_modules/eslint/lib/rules/no-invalid-regexp.js
3.05 KB
f7563de62
|
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
/** * @fileoverview Validate strings passed to the RegExp constructor * @author Michael Ficarra */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const espree = require("espree"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow invalid regular expression strings in `RegExp` constructors", category: "Possible Errors", recommended: true }, schema: [{ type: "object", properties: { allowConstructorFlags: { type: "array", items: { type: "string" } } }, additionalProperties: false }] }, create(context) { const options = context.options[0]; let allowedFlags = ""; if (options && options.allowConstructorFlags) { allowedFlags = options.allowConstructorFlags.join(""); } /** * Check if node is a string * @param {ASTNode} node node to evaluate * @returns {boolean} True if its a string * @private */ function isString(node) { return node && node.type === "Literal" && typeof node.value === "string"; } /** * Validate strings passed to the RegExp constructor * @param {ASTNode} node node to evaluate * @returns {void} * @private */ function check(node) { if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0])) { let flags = isString(node.arguments[1]) ? node.arguments[1].value : ""; if (allowedFlags) { flags = flags.replace(new RegExp(`[${allowedFlags}]`, "gi"), ""); } try { void new RegExp(node.arguments[0].value); } catch (e) { context.report({ node, message: "{{message}}.", data: e }); } if (flags) { try { espree.parse(`/./${flags}`, context.parserOptions); } catch (ex) { context.report({ node, message: "Invalid flags supplied to RegExp constructor '{{flags}}'.", data: { flags } }); } } } } return { CallExpression: check, NewExpression: check }; } }; |