no-bare-strings-in-template.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const utils = require('../utils')
  10. const regexp = require('../utils/regexp')
  11. const casing = require('../utils/casing')
  12. /**
  13. * @typedef { { names: { [tagName in string]: Set<string> }, regexps: { name: RegExp, attrs: Set<string> }[], cache: { [tagName in string]: Set<string> } } } TargetAttrs
  14. */
  15. // ------------------------------------------------------------------------------
  16. // Constants
  17. // ------------------------------------------------------------------------------
  18. // https://dev.w3.org/html5/html-author/charref
  19. const DEFAULT_ALLOWLIST = [
  20. '(',
  21. ')',
  22. ',',
  23. '.',
  24. '&',
  25. '+',
  26. '-',
  27. '=',
  28. '*',
  29. '/',
  30. '#',
  31. '%',
  32. '!',
  33. '?',
  34. ':',
  35. '[',
  36. ']',
  37. '{',
  38. '}',
  39. '<',
  40. '>',
  41. '\u00b7', // "·"
  42. '\u2022', // "•"
  43. '\u2010', // "‐"
  44. '\u2013', // "–"
  45. '\u2014', // "—"
  46. '\u2212', // "−"
  47. '|'
  48. ]
  49. const DEFAULT_ATTRIBUTES = {
  50. '/.+/': [
  51. 'title',
  52. 'aria-label',
  53. 'aria-placeholder',
  54. 'aria-roledescription',
  55. 'aria-valuetext'
  56. ],
  57. input: ['placeholder'],
  58. img: ['alt']
  59. }
  60. const DEFAULT_DIRECTIVES = ['v-text']
  61. // --------------------------------------------------------------------------
  62. // Helpers
  63. // --------------------------------------------------------------------------
  64. /**
  65. * Parse attributes option
  66. * @param {any} options
  67. * @returns {TargetAttrs}
  68. */
  69. function parseTargetAttrs(options) {
  70. /** @type {TargetAttrs} */
  71. const result = { names: {}, regexps: [], cache: {} }
  72. for (const tagName of Object.keys(options)) {
  73. /** @type { Set<string> } */
  74. const attrs = new Set(options[tagName])
  75. if (regexp.isRegExp(tagName)) {
  76. result.regexps.push({
  77. name: regexp.toRegExp(tagName),
  78. attrs
  79. })
  80. } else {
  81. result.names[tagName] = attrs
  82. }
  83. }
  84. return result
  85. }
  86. /**
  87. * Get a string from given expression container node
  88. * @param {VExpressionContainer} value
  89. * @returns { string | null }
  90. */
  91. function getStringValue(value) {
  92. const expression = value.expression
  93. if (!expression) {
  94. return null
  95. }
  96. if (expression.type !== 'Literal') {
  97. return null
  98. }
  99. if (typeof expression.value === 'string') {
  100. return expression.value
  101. }
  102. return null
  103. }
  104. // ------------------------------------------------------------------------------
  105. // Rule Definition
  106. // ------------------------------------------------------------------------------
  107. module.exports = {
  108. meta: {
  109. type: 'suggestion',
  110. docs: {
  111. description: 'disallow the use of bare strings in `<template>`',
  112. categories: undefined,
  113. url: 'https://eslint.vuejs.org/rules/no-bare-strings-in-template.html'
  114. },
  115. schema: [
  116. {
  117. type: 'object',
  118. properties: {
  119. allowlist: {
  120. type: 'array',
  121. items: { type: 'string' },
  122. uniqueItems: true
  123. },
  124. attributes: {
  125. type: 'object',
  126. patternProperties: {
  127. '^(?:\\S+|/.*/[a-z]*)$': {
  128. type: 'array',
  129. items: { type: 'string' },
  130. uniqueItems: true
  131. }
  132. },
  133. additionalProperties: false
  134. },
  135. directives: {
  136. type: 'array',
  137. items: { type: 'string', pattern: '^v-' },
  138. uniqueItems: true
  139. }
  140. }
  141. }
  142. ],
  143. messages: {
  144. unexpected: 'Unexpected non-translated string used.',
  145. unexpectedInAttr: 'Unexpected non-translated string used in `{{attr}}`.'
  146. }
  147. },
  148. /** @param {RuleContext} context */
  149. create(context) {
  150. /**
  151. * @typedef { { upper: ElementStack | null, name: string, attrs: Set<string> } } ElementStack
  152. */
  153. const opts = context.options[0] || {}
  154. /** @type {string[]} */
  155. const allowlist = opts.allowlist || DEFAULT_ALLOWLIST
  156. const attributes = parseTargetAttrs(opts.attributes || DEFAULT_ATTRIBUTES)
  157. const directives = opts.directives || DEFAULT_DIRECTIVES
  158. const allowlistRe = new RegExp(
  159. allowlist.map((w) => regexp.escape(w)).join('|'),
  160. 'gu'
  161. )
  162. /** @type {ElementStack | null} */
  163. let elementStack = null
  164. /**
  165. * Gets the bare string from given string
  166. * @param {string} str
  167. */
  168. function getBareString(str) {
  169. return str.trim().replace(allowlistRe, '').trim()
  170. }
  171. /**
  172. * Get the attribute to be verified from the element name.
  173. * @param {string} tagName
  174. * @returns {Set<string>}
  175. */
  176. function getTargetAttrs(tagName) {
  177. if (attributes.cache[tagName]) {
  178. return attributes.cache[tagName]
  179. }
  180. /** @type {string[]} */
  181. const result = []
  182. if (attributes.names[tagName]) {
  183. result.push(...attributes.names[tagName])
  184. }
  185. for (const { name, attrs } of attributes.regexps) {
  186. name.lastIndex = 0
  187. if (name.test(tagName)) {
  188. result.push(...attrs)
  189. }
  190. }
  191. if (casing.isKebabCase(tagName)) {
  192. result.push(...getTargetAttrs(casing.pascalCase(tagName)))
  193. }
  194. return (attributes.cache[tagName] = new Set(result))
  195. }
  196. return utils.defineTemplateBodyVisitor(context, {
  197. /** @param {VText} node */
  198. VText(node) {
  199. if (getBareString(node.value)) {
  200. context.report({
  201. node,
  202. messageId: 'unexpected'
  203. })
  204. }
  205. },
  206. /**
  207. * @param {VElement} node
  208. */
  209. VElement(node) {
  210. elementStack = {
  211. upper: elementStack,
  212. name: node.rawName,
  213. attrs: getTargetAttrs(node.rawName)
  214. }
  215. },
  216. 'VElement:exit'() {
  217. elementStack = elementStack && elementStack.upper
  218. },
  219. /** @param {VAttribute|VDirective} node */
  220. VAttribute(node) {
  221. if (!node.value || !elementStack) {
  222. return
  223. }
  224. if (node.directive === false) {
  225. const attrs = elementStack.attrs
  226. if (!attrs.has(node.key.rawName)) {
  227. return
  228. }
  229. if (getBareString(node.value.value)) {
  230. context.report({
  231. node: node.value,
  232. messageId: 'unexpectedInAttr',
  233. data: {
  234. attr: node.key.rawName
  235. }
  236. })
  237. }
  238. } else {
  239. const directive = `v-${node.key.name.name}`
  240. if (!directives.includes(directive)) {
  241. return
  242. }
  243. const str = getStringValue(node.value)
  244. if (str && getBareString(str)) {
  245. context.report({
  246. node: node.value,
  247. messageId: 'unexpectedInAttr',
  248. data: {
  249. attr: directive
  250. }
  251. })
  252. }
  253. }
  254. }
  255. })
  256. }
  257. }