no-async-in-computed-properties.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /**
  2. * @fileoverview Check if there are no asynchronous actions inside computed properties.
  3. * @author Armano
  4. */
  5. 'use strict'
  6. const { ReferenceTracker } = require('@eslint-community/eslint-utils')
  7. const utils = require('../utils')
  8. /**
  9. * @typedef {import('../utils').VueObjectData} VueObjectData
  10. * @typedef {import('../utils').VueVisitor} VueVisitor
  11. * @typedef {import('../utils').ComponentComputedProperty} ComponentComputedProperty
  12. */
  13. const PROMISE_FUNCTIONS = new Set(['then', 'catch', 'finally'])
  14. const PROMISE_METHODS = new Set(['all', 'race', 'reject', 'resolve'])
  15. const TIMED_FUNCTIONS = new Set([
  16. 'setTimeout',
  17. 'setInterval',
  18. 'setImmediate',
  19. 'requestAnimationFrame'
  20. ])
  21. /**
  22. * @param {CallExpression} node
  23. */
  24. function isTimedFunction(node) {
  25. const callee = utils.skipChainExpression(node.callee)
  26. return (
  27. ((callee.type === 'Identifier' && TIMED_FUNCTIONS.has(callee.name)) ||
  28. (callee.type === 'MemberExpression' &&
  29. callee.object.type === 'Identifier' &&
  30. callee.object.name === 'window' &&
  31. TIMED_FUNCTIONS.has(utils.getStaticPropertyName(callee) || ''))) &&
  32. node.arguments.length > 0
  33. )
  34. }
  35. /**
  36. * @param {CallExpression} node
  37. */
  38. function isPromise(node) {
  39. const callee = utils.skipChainExpression(node.callee)
  40. if (callee.type === 'MemberExpression') {
  41. const name = utils.getStaticPropertyName(callee)
  42. return (
  43. name &&
  44. // hello.PROMISE_FUNCTION()
  45. (PROMISE_FUNCTIONS.has(name) ||
  46. // Promise.PROMISE_METHOD()
  47. (callee.object.type === 'Identifier' &&
  48. callee.object.name === 'Promise' &&
  49. PROMISE_METHODS.has(name)))
  50. )
  51. }
  52. return false
  53. }
  54. /**
  55. * @param {CallExpression} node
  56. * @param {RuleContext} context
  57. */
  58. function isNextTick(node, context) {
  59. const callee = utils.skipChainExpression(node.callee)
  60. if (callee.type === 'MemberExpression') {
  61. const name = utils.getStaticPropertyName(callee)
  62. return (
  63. (utils.isThis(callee.object, context) && name === '$nextTick') ||
  64. (callee.object.type === 'Identifier' &&
  65. callee.object.name === 'Vue' &&
  66. name === 'nextTick')
  67. )
  68. }
  69. return false
  70. }
  71. module.exports = {
  72. meta: {
  73. type: 'problem',
  74. docs: {
  75. description: 'disallow asynchronous actions in computed properties',
  76. categories: ['vue3-essential', 'vue2-essential'],
  77. url: 'https://eslint.vuejs.org/rules/no-async-in-computed-properties.html'
  78. },
  79. fixable: null,
  80. schema: [],
  81. messages: {
  82. unexpectedInFunction:
  83. 'Unexpected {{expressionName}} in computed function.',
  84. unexpectedInProperty:
  85. 'Unexpected {{expressionName}} in "{{propertyName}}" computed property.'
  86. }
  87. },
  88. /** @param {RuleContext} context */
  89. create(context) {
  90. /** @type {Map<ObjectExpression, ComponentComputedProperty[]>} */
  91. const computedPropertiesMap = new Map()
  92. /** @type {(FunctionExpression | ArrowFunctionExpression)[]} */
  93. const computedFunctionNodes = []
  94. /**
  95. * @typedef {object} ScopeStack
  96. * @property {ScopeStack | null} upper
  97. * @property {BlockStatement | Expression} body
  98. */
  99. /** @type {ScopeStack | null} */
  100. let scopeStack = null
  101. const expressionTypes = {
  102. promise: 'asynchronous action',
  103. nextTick: 'asynchronous action',
  104. await: 'await operator',
  105. async: 'async function declaration',
  106. new: 'Promise object',
  107. timed: 'timed function'
  108. }
  109. /**
  110. * @param {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} node
  111. * @param {VueObjectData|undefined} [info]
  112. */
  113. function onFunctionEnter(node, info) {
  114. if (node.async) {
  115. verify(
  116. node,
  117. node.body,
  118. 'async',
  119. info ? computedPropertiesMap.get(info.node) : null
  120. )
  121. }
  122. scopeStack = {
  123. upper: scopeStack,
  124. body: node.body
  125. }
  126. }
  127. function onFunctionExit() {
  128. scopeStack = scopeStack && scopeStack.upper
  129. }
  130. /**
  131. * @param {ESNode} node
  132. * @param {BlockStatement | Expression} targetBody
  133. * @param {keyof expressionTypes} type
  134. * @param {ComponentComputedProperty[]|undefined|null} computedProperties
  135. */
  136. function verify(node, targetBody, type, computedProperties) {
  137. for (const cp of computedProperties || []) {
  138. if (
  139. cp.value &&
  140. node.loc.start.line >= cp.value.loc.start.line &&
  141. node.loc.end.line <= cp.value.loc.end.line &&
  142. targetBody === cp.value
  143. ) {
  144. context.report({
  145. node,
  146. messageId: 'unexpectedInProperty',
  147. data: {
  148. expressionName: expressionTypes[type],
  149. propertyName: cp.key || 'unknown'
  150. }
  151. })
  152. return
  153. }
  154. }
  155. for (const cf of computedFunctionNodes) {
  156. if (
  157. node.loc.start.line >= cf.body.loc.start.line &&
  158. node.loc.end.line <= cf.body.loc.end.line &&
  159. targetBody === cf.body
  160. ) {
  161. context.report({
  162. node,
  163. messageId: 'unexpectedInFunction',
  164. data: {
  165. expressionName: expressionTypes[type]
  166. }
  167. })
  168. return
  169. }
  170. }
  171. }
  172. const nodeVisitor = {
  173. ':function': onFunctionEnter,
  174. ':function:exit': onFunctionExit,
  175. /**
  176. * @param {NewExpression} node
  177. * @param {VueObjectData|undefined} [info]
  178. */
  179. NewExpression(node, info) {
  180. if (!scopeStack) {
  181. return
  182. }
  183. if (
  184. node.callee.type === 'Identifier' &&
  185. node.callee.name === 'Promise'
  186. ) {
  187. verify(
  188. node,
  189. scopeStack.body,
  190. 'new',
  191. info ? computedPropertiesMap.get(info.node) : null
  192. )
  193. }
  194. },
  195. /**
  196. * @param {CallExpression} node
  197. * @param {VueObjectData|undefined} [info]
  198. */
  199. CallExpression(node, info) {
  200. if (!scopeStack) {
  201. return
  202. }
  203. if (isPromise(node)) {
  204. verify(
  205. node,
  206. scopeStack.body,
  207. 'promise',
  208. info ? computedPropertiesMap.get(info.node) : null
  209. )
  210. } else if (isTimedFunction(node)) {
  211. verify(
  212. node,
  213. scopeStack.body,
  214. 'timed',
  215. info ? computedPropertiesMap.get(info.node) : null
  216. )
  217. } else if (isNextTick(node, context)) {
  218. verify(
  219. node,
  220. scopeStack.body,
  221. 'nextTick',
  222. info ? computedPropertiesMap.get(info.node) : null
  223. )
  224. }
  225. },
  226. /**
  227. * @param {AwaitExpression} node
  228. * @param {VueObjectData|undefined} [info]
  229. */
  230. AwaitExpression(node, info) {
  231. if (!scopeStack) {
  232. return
  233. }
  234. verify(
  235. node,
  236. scopeStack.body,
  237. 'await',
  238. info ? computedPropertiesMap.get(info.node) : null
  239. )
  240. }
  241. }
  242. return utils.compositingVisitors(
  243. {
  244. /** @param {Program} program */
  245. Program(program) {
  246. const tracker = new ReferenceTracker(utils.getScope(context, program))
  247. for (const { node } of utils.iterateReferencesTraceMap(tracker, {
  248. computed: {
  249. [ReferenceTracker.CALL]: true
  250. }
  251. })) {
  252. if (node.type !== 'CallExpression') {
  253. continue
  254. }
  255. const getter = utils.getGetterBodyFromComputedFunction(node)
  256. if (getter) {
  257. computedFunctionNodes.push(getter)
  258. }
  259. }
  260. }
  261. },
  262. utils.isScriptSetup(context)
  263. ? utils.defineScriptSetupVisitor(context, nodeVisitor)
  264. : utils.defineVueVisitor(context, {
  265. onVueObjectEnter(node) {
  266. computedPropertiesMap.set(node, utils.getComputedProperties(node))
  267. },
  268. ...nodeVisitor
  269. })
  270. )
  271. }
  272. }