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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. additionalProperties: false
  142. }
  143. ],
  144. messages: {
  145. unexpected: 'Unexpected non-translated string used.',
  146. unexpectedInAttr: 'Unexpected non-translated string used in `{{attr}}`.'
  147. }
  148. },
  149. /** @param {RuleContext} context */
  150. create(context) {
  151. /**
  152. * @typedef { { upper: ElementStack | null, name: string, attrs: Set<string> } } ElementStack
  153. */
  154. const opts = context.options[0] || {}
  155. /** @type {string[]} */
  156. const allowlist = opts.allowlist || DEFAULT_ALLOWLIST
  157. const attributes = parseTargetAttrs(opts.attributes || DEFAULT_ATTRIBUTES)
  158. const directives = opts.directives || DEFAULT_DIRECTIVES
  159. const allowlistRe = new RegExp(
  160. allowlist.map((w) => regexp.escape(w)).join('|'),
  161. 'gu'
  162. )
  163. /** @type {ElementStack | null} */
  164. let elementStack = null
  165. /**
  166. * Gets the bare string from given string
  167. * @param {string} str
  168. */
  169. function getBareString(str) {
  170. return str.trim().replace(allowlistRe, '').trim()
  171. }
  172. /**
  173. * Get the attribute to be verified from the element name.
  174. * @param {string} tagName
  175. * @returns {Set<string>}
  176. */
  177. function getTargetAttrs(tagName) {
  178. if (attributes.cache[tagName]) {
  179. return attributes.cache[tagName]
  180. }
  181. /** @type {string[]} */
  182. const result = []
  183. if (attributes.names[tagName]) {
  184. result.push(...attributes.names[tagName])
  185. }
  186. for (const { name, attrs } of attributes.regexps) {
  187. name.lastIndex = 0
  188. if (name.test(tagName)) {
  189. result.push(...attrs)
  190. }
  191. }
  192. if (casing.isKebabCase(tagName)) {
  193. result.push(...getTargetAttrs(casing.pascalCase(tagName)))
  194. }
  195. return (attributes.cache[tagName] = new Set(result))
  196. }
  197. return utils.defineTemplateBodyVisitor(context, {
  198. /** @param {VText} node */
  199. VText(node) {
  200. if (getBareString(node.value)) {
  201. context.report({
  202. node,
  203. messageId: 'unexpected'
  204. })
  205. }
  206. },
  207. /**
  208. * @param {VElement} node
  209. */
  210. VElement(node) {
  211. elementStack = {
  212. upper: elementStack,
  213. name: node.rawName,
  214. attrs: getTargetAttrs(node.rawName)
  215. }
  216. },
  217. 'VElement:exit'() {
  218. elementStack = elementStack && elementStack.upper
  219. },
  220. /** @param {VAttribute|VDirective} node */
  221. VAttribute(node) {
  222. if (!node.value || !elementStack) {
  223. return
  224. }
  225. if (node.directive === false) {
  226. const attrs = elementStack.attrs
  227. if (!attrs.has(node.key.rawName)) {
  228. return
  229. }
  230. if (getBareString(node.value.value)) {
  231. context.report({
  232. node: node.value,
  233. messageId: 'unexpectedInAttr',
  234. data: {
  235. attr: node.key.rawName
  236. }
  237. })
  238. }
  239. } else {
  240. const directive = `v-${node.key.name.name}`
  241. if (!directives.includes(directive)) {
  242. return
  243. }
  244. const str = getStringValue(node.value)
  245. if (str && getBareString(str)) {
  246. context.report({
  247. node: node.value,
  248. messageId: 'unexpectedInAttr',
  249. data: {
  250. attr: directive
  251. }
  252. })
  253. }
  254. }
  255. }
  256. })
  257. }
  258. }