|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// This rule makes sure that no Globals are going to be used in /lib. |
| 4 | +// That could otherwise result in problems with the repl. |
| 5 | + |
| 6 | +module.exports = function(context) { |
| 7 | + |
| 8 | + function flagIt(msg, fix) { |
| 9 | + return (reference) => { |
| 10 | + context.report({ |
| 11 | + node: reference.identifier, |
| 12 | + message: msg, |
| 13 | + fix: (fixer) => { |
| 14 | + const sourceCode = context.getSourceCode(); |
| 15 | + |
| 16 | + const useStrict = /'use strict';\n\n?/g; |
| 17 | + const hasUseStrict = !!useStrict.exec(sourceCode.text); |
| 18 | + const firstLOC = sourceCode.ast.range[0]; |
| 19 | + const rangeNeedle = hasUseStrict ? useStrict.lastIndex : firstLOC; |
| 20 | + |
| 21 | + return fixer.insertTextBeforeRange([rangeNeedle], `${fix}\n`); |
| 22 | + } |
| 23 | + }); |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + return { |
| 28 | + 'Program:exit': function() { |
| 29 | + const globalScope = context.getScope(); |
| 30 | + let variable = globalScope.set.get('Buffer'); |
| 31 | + if (variable) { |
| 32 | + const fix = "const { Buffer } = require('buffer');"; |
| 33 | + const msg = `Use ${fix} at the beginning of this file`; |
| 34 | + variable.references.forEach(flagIt(msg, fix)); |
| 35 | + } |
| 36 | + variable = globalScope.set.get('URL'); |
| 37 | + if (variable) { |
| 38 | + const fix = "const { URL } = require('url');"; |
| 39 | + const msg = `Use ${fix} at the beginning of this file`; |
| 40 | + variable.references.forEach(flagIt(msg, fix)); |
| 41 | + } |
| 42 | + variable = globalScope.set.get('URLSearchParams'); |
| 43 | + if (variable) { |
| 44 | + const fix = "const { URLSearchParams } = require('url');"; |
| 45 | + const msg = `Use ${fix} at the beginning of this file`; |
| 46 | + variable.references.forEach(flagIt(msg, fix)); |
| 47 | + } |
| 48 | + } |
| 49 | + }; |
| 50 | +}; |
0 commit comments