no-restricted-call-after-await.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const fs = require('fs')
  7. const path = require('path')
  8. const { ReferenceTracker } = require('eslint-utils')
  9. const utils = require('../utils')
  10. /**
  11. * @typedef {import('eslint-utils').TYPES.TraceMap} TraceMap
  12. * @typedef {import('eslint-utils').TYPES.TraceKind} TraceKind
  13. */
  14. module.exports = {
  15. meta: {
  16. type: 'suggestion',
  17. docs: {
  18. description: 'disallow asynchronously called restricted methods',
  19. categories: undefined,
  20. url: 'https://eslint.vuejs.org/rules/no-restricted-call-after-await.html'
  21. },
  22. fixable: null,
  23. schema: {
  24. type: 'array',
  25. items: {
  26. type: 'object',
  27. properties: {
  28. module: { type: 'string' },
  29. path: {
  30. anyOf: [
  31. { type: 'string' },
  32. {
  33. type: 'array',
  34. items: {
  35. type: 'string'
  36. }
  37. }
  38. ]
  39. },
  40. message: { type: 'string', minLength: 1 }
  41. },
  42. required: ['module'],
  43. additionalProperties: false
  44. },
  45. uniqueItems: true,
  46. minItems: 0
  47. },
  48. messages: {
  49. // eslint-disable-next-line eslint-plugin/report-message-format
  50. restricted: '{{message}}'
  51. }
  52. },
  53. /** @param {RuleContext} context */
  54. create(context) {
  55. /**
  56. * @typedef {object} SetupScopeData
  57. * @property {boolean} afterAwait
  58. * @property {[number,number]} range
  59. */
  60. /** @type {Map<ESNode, string>} */
  61. const restrictedCallNodes = new Map()
  62. /** @type {Map<FunctionExpression | ArrowFunctionExpression | FunctionDeclaration, SetupScopeData>} */
  63. const setupScopes = new Map()
  64. /**x
  65. * @typedef {object} ScopeStack
  66. * @property {ScopeStack | null} upper
  67. * @property {FunctionExpression | ArrowFunctionExpression | FunctionDeclaration} scopeNode
  68. */
  69. /** @type {ScopeStack | null} */
  70. let scopeStack = null
  71. /** @type {Record<string, string[]> | null} */
  72. let allLocalImports = null
  73. /**
  74. * @param {string} id
  75. */
  76. function safeRequireResolve(id) {
  77. try {
  78. if (fs.statSync(id).isDirectory()) {
  79. return require.resolve(id)
  80. }
  81. } catch (_e) {
  82. // ignore
  83. }
  84. return id
  85. }
  86. /**
  87. * @param {Program} ast
  88. */
  89. function getAllLocalImports(ast) {
  90. if (!allLocalImports) {
  91. allLocalImports = {}
  92. const dir = path.dirname(context.getFilename())
  93. for (const body of ast.body) {
  94. if (body.type !== 'ImportDeclaration') {
  95. continue
  96. }
  97. const source = String(body.source.value)
  98. if (!source.startsWith('.')) {
  99. continue
  100. }
  101. const modulePath = safeRequireResolve(path.join(dir, source))
  102. const list =
  103. allLocalImports[modulePath] || (allLocalImports[modulePath] = [])
  104. list.push(source)
  105. }
  106. }
  107. return allLocalImports
  108. }
  109. function getCwd() {
  110. if (context.getCwd) {
  111. return context.getCwd()
  112. }
  113. return path.resolve('')
  114. }
  115. /**
  116. * @param {string} moduleName
  117. * @param {Program} ast
  118. * @returns {string[]}
  119. */
  120. function normalizeModules(moduleName, ast) {
  121. /** @type {string} */
  122. let modulePath
  123. if (moduleName.startsWith('.')) {
  124. modulePath = safeRequireResolve(path.join(getCwd(), moduleName))
  125. } else if (path.isAbsolute(moduleName)) {
  126. modulePath = safeRequireResolve(moduleName)
  127. } else {
  128. return [moduleName]
  129. }
  130. return getAllLocalImports(ast)[modulePath] || []
  131. }
  132. return utils.compositingVisitors(
  133. {
  134. /** @param {Program} node */
  135. Program(node) {
  136. const tracker = new ReferenceTracker(context.getScope())
  137. for (const option of context.options) {
  138. const modules = normalizeModules(option.module, node)
  139. for (const module of modules) {
  140. /** @type {TraceMap} */
  141. const traceMap = {
  142. [module]: {
  143. [ReferenceTracker.ESM]: true
  144. }
  145. }
  146. /** @type {TraceKind & TraceMap} */
  147. const mod = traceMap[module]
  148. let local = mod
  149. const paths = Array.isArray(option.path)
  150. ? option.path
  151. : [option.path || 'default']
  152. for (const path of paths) {
  153. local = local[path] || (local[path] = {})
  154. }
  155. local[ReferenceTracker.CALL] = true
  156. const message =
  157. option.message ||
  158. `The \`${[`import("${module}")`, ...paths].join(
  159. '.'
  160. )}\` after \`await\` expression are forbidden.`
  161. for (const { node } of tracker.iterateEsmReferences(traceMap)) {
  162. restrictedCallNodes.set(node, message)
  163. }
  164. }
  165. }
  166. }
  167. },
  168. utils.defineVueVisitor(context, {
  169. onSetupFunctionEnter(node) {
  170. setupScopes.set(node, {
  171. afterAwait: false,
  172. range: node.range
  173. })
  174. },
  175. /** @param {FunctionExpression | ArrowFunctionExpression | FunctionDeclaration} node */
  176. ':function'(node) {
  177. scopeStack = {
  178. upper: scopeStack,
  179. scopeNode: node
  180. }
  181. },
  182. ':function:exit'() {
  183. scopeStack = scopeStack && scopeStack.upper
  184. },
  185. /** @param {AwaitExpression} node */
  186. AwaitExpression(node) {
  187. if (!scopeStack) {
  188. return
  189. }
  190. const setupScope = setupScopes.get(scopeStack.scopeNode)
  191. if (!setupScope || !utils.inRange(setupScope.range, node)) {
  192. return
  193. }
  194. setupScope.afterAwait = true
  195. },
  196. /** @param {CallExpression} node */
  197. CallExpression(node) {
  198. if (!scopeStack) {
  199. return
  200. }
  201. const setupScope = setupScopes.get(scopeStack.scopeNode)
  202. if (
  203. !setupScope ||
  204. !setupScope.afterAwait ||
  205. !utils.inRange(setupScope.range, node)
  206. ) {
  207. return
  208. }
  209. const message = restrictedCallNodes.get(node)
  210. if (message) {
  211. context.report({
  212. node,
  213. messageId: 'restricted',
  214. data: { message }
  215. })
  216. }
  217. },
  218. onSetupFunctionExit(node) {
  219. setupScopes.delete(node)
  220. }
  221. })
  222. )
  223. }
  224. }