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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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', 'essential'],
  77. url: 'https://eslint.vuejs.org/rules/no-async-in-computed-properties.html'
  78. },
  79. fixable: null,
  80. schema: []
  81. },
  82. /** @param {RuleContext} context */
  83. create(context) {
  84. /** @type {Map<ObjectExpression, ComponentComputedProperty[]>} */
  85. const computedPropertiesMap = new Map()
  86. /** @type {(FunctionExpression | ArrowFunctionExpression)[]} */
  87. const computedFunctionNodes = []
  88. /**
  89. * @typedef {object} ScopeStack
  90. * @property {ScopeStack | null} upper
  91. * @property {BlockStatement | Expression} body
  92. */
  93. /** @type {ScopeStack | null} */
  94. let scopeStack = null
  95. const expressionTypes = {
  96. promise: 'asynchronous action',
  97. nextTick: 'asynchronous action',
  98. await: 'await operator',
  99. async: 'async function declaration',
  100. new: 'Promise object',
  101. timed: 'timed function'
  102. }
  103. /**
  104. * @param {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} node
  105. * @param {VueObjectData|undefined} [info]
  106. */
  107. function onFunctionEnter(node, info) {
  108. if (node.async) {
  109. verify(
  110. node,
  111. node.body,
  112. 'async',
  113. info ? computedPropertiesMap.get(info.node) : null
  114. )
  115. }
  116. scopeStack = {
  117. upper: scopeStack,
  118. body: node.body
  119. }
  120. }
  121. function onFunctionExit() {
  122. scopeStack = scopeStack && scopeStack.upper
  123. }
  124. /**
  125. * @param {ESNode} node
  126. * @param {BlockStatement | Expression} targetBody
  127. * @param {keyof expressionTypes} type
  128. * @param {ComponentComputedProperty[]|undefined|null} computedProperties
  129. */
  130. function verify(node, targetBody, type, computedProperties) {
  131. for (const cp of computedProperties || []) {
  132. if (
  133. cp.value &&
  134. node.loc.start.line >= cp.value.loc.start.line &&
  135. node.loc.end.line <= cp.value.loc.end.line &&
  136. targetBody === cp.value
  137. ) {
  138. context.report({
  139. node,
  140. message:
  141. 'Unexpected {{expressionName}} in "{{propertyName}}" computed property.',
  142. data: {
  143. expressionName: expressionTypes[type],
  144. propertyName: cp.key || 'unknown'
  145. }
  146. })
  147. return
  148. }
  149. }
  150. for (const cf of computedFunctionNodes) {
  151. if (
  152. node.loc.start.line >= cf.body.loc.start.line &&
  153. node.loc.end.line <= cf.body.loc.end.line &&
  154. targetBody === cf.body
  155. ) {
  156. context.report({
  157. node,
  158. message: 'Unexpected {{expressionName}} in computed function.',
  159. data: {
  160. expressionName: expressionTypes[type]
  161. }
  162. })
  163. return
  164. }
  165. }
  166. }
  167. const nodeVisitor = {
  168. ':function': onFunctionEnter,
  169. ':function:exit': onFunctionExit,
  170. /**
  171. * @param {NewExpression} node
  172. * @param {VueObjectData|undefined} [info]
  173. */
  174. NewExpression(node, info) {
  175. if (!scopeStack) {
  176. return
  177. }
  178. if (
  179. node.callee.type === 'Identifier' &&
  180. node.callee.name === 'Promise'
  181. ) {
  182. verify(
  183. node,
  184. scopeStack.body,
  185. 'new',
  186. info ? computedPropertiesMap.get(info.node) : null
  187. )
  188. }
  189. },
  190. /**
  191. * @param {CallExpression} node
  192. * @param {VueObjectData|undefined} [info]
  193. */
  194. CallExpression(node, info) {
  195. if (!scopeStack) {
  196. return
  197. }
  198. if (isPromise(node)) {
  199. verify(
  200. node,
  201. scopeStack.body,
  202. 'promise',
  203. info ? computedPropertiesMap.get(info.node) : null
  204. )
  205. } else if (isTimedFunction(node)) {
  206. verify(
  207. node,
  208. scopeStack.body,
  209. 'timed',
  210. info ? computedPropertiesMap.get(info.node) : null
  211. )
  212. } else if (isNextTick(node, context)) {
  213. verify(
  214. node,
  215. scopeStack.body,
  216. 'nextTick',
  217. info ? computedPropertiesMap.get(info.node) : null
  218. )
  219. }
  220. },
  221. /**
  222. * @param {AwaitExpression} node
  223. * @param {VueObjectData|undefined} [info]
  224. */
  225. AwaitExpression(node, info) {
  226. if (!scopeStack) {
  227. return
  228. }
  229. verify(
  230. node,
  231. scopeStack.body,
  232. 'await',
  233. info ? computedPropertiesMap.get(info.node) : null
  234. )
  235. }
  236. }
  237. return utils.compositingVisitors(
  238. {
  239. Program() {
  240. const tracker = new ReferenceTracker(context.getScope())
  241. const traceMap = utils.createCompositionApiTraceMap({
  242. [ReferenceTracker.ESM]: true,
  243. computed: {
  244. [ReferenceTracker.CALL]: true
  245. }
  246. })
  247. for (const { node } of tracker.iterateEsmReferences(traceMap)) {
  248. if (node.type !== 'CallExpression') {
  249. continue
  250. }
  251. const getter = utils.getGetterBodyFromComputedFunction(node)
  252. if (getter) {
  253. computedFunctionNodes.push(getter)
  254. }
  255. }
  256. }
  257. },
  258. utils.isScriptSetup(context)
  259. ? utils.defineScriptSetupVisitor(context, nodeVisitor)
  260. : utils.defineVueVisitor(context, {
  261. onVueObjectEnter(node) {
  262. computedPropertiesMap.set(node, utils.getComputedProperties(node))
  263. },
  264. ...nodeVisitor
  265. })
  266. )
  267. }
  268. }