|
| 1 | +'use strict'; |
| 2 | +const {isStringLiteral, isDirective} = require('./ast/index.js'); |
| 3 | +const {fixSpaceAroundKeyword} = require('./fix/index.js'); |
| 4 | + |
| 5 | +const MESSAGE_ID = 'prefer-string-raw'; |
| 6 | +const messages = { |
| 7 | + [MESSAGE_ID]: '`String.raw` should be used to avoid escaping `\\`.', |
| 8 | +}; |
| 9 | + |
| 10 | +const BACKSLASH = '\\'; |
| 11 | + |
| 12 | +function unescapeBackslash(raw) { |
| 13 | + const quote = raw.charAt(0); |
| 14 | + |
| 15 | + raw = raw.slice(1, -1); |
| 16 | + |
| 17 | + let result = ''; |
| 18 | + for (let position = 0; position < raw.length; position++) { |
| 19 | + const character = raw[position]; |
| 20 | + if (character === BACKSLASH) { |
| 21 | + const nextCharacter = raw[position + 1]; |
| 22 | + if (nextCharacter === BACKSLASH || nextCharacter === quote) { |
| 23 | + result += nextCharacter; |
| 24 | + position++; |
| 25 | + continue; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + result += character; |
| 30 | + } |
| 31 | + |
| 32 | + return result; |
| 33 | +} |
| 34 | + |
| 35 | +/** @param {import('eslint').Rule.RuleContext} context */ |
| 36 | +const create = context => { |
| 37 | + context.on('Literal', node => { |
| 38 | + if ( |
| 39 | + !isStringLiteral(node) |
| 40 | + || isDirective(node.parent) |
| 41 | + || ( |
| 42 | + ( |
| 43 | + node.parent.type === 'ImportDeclaration' |
| 44 | + || node.parent.type === 'ExportNamedDeclaration' |
| 45 | + || node.parent.type === 'ExportAllDeclaration' |
| 46 | + ) && node.parent.source === node |
| 47 | + ) |
| 48 | + || (node.parent.type === 'Property' && !node.parent.computed && node.parent.key === node) |
| 49 | + || (node.parent.type === 'JSXAttribute' && node.parent.value === node) |
| 50 | + ) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + const {raw} = node; |
| 55 | + if ( |
| 56 | + raw.at(-2) === BACKSLASH |
| 57 | + || !raw.includes(BACKSLASH + BACKSLASH) |
| 58 | + || raw.includes('`') |
| 59 | + || raw.includes('${') |
| 60 | + || node.loc.start.line !== node.loc.end.line |
| 61 | + ) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + const unescaped = unescapeBackslash(raw); |
| 66 | + if (unescaped !== node.value) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + return { |
| 71 | + node, |
| 72 | + messageId: MESSAGE_ID, |
| 73 | + * fix(fixer) { |
| 74 | + yield fixer.replaceText(node, `String.raw\`${unescaped}\``); |
| 75 | + yield * fixSpaceAroundKeyword(fixer, node, context.sourceCode); |
| 76 | + }, |
| 77 | + }; |
| 78 | + }); |
| 79 | +}; |
| 80 | + |
| 81 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 82 | +module.exports = { |
| 83 | + create, |
| 84 | + meta: { |
| 85 | + type: 'suggestion', |
| 86 | + docs: { |
| 87 | + description: 'Prefer using the `String.raw` tag to avoid escaping `\\`.', |
| 88 | + recommended: true, |
| 89 | + }, |
| 90 | + fixable: 'code', |
| 91 | + messages, |
| 92 | + }, |
| 93 | +}; |
0 commit comments