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

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