eslint-plugin-react-hooks.development.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  1. /** @license React v4.2.0
  2. * eslint-plugin-react-hooks.development.js
  3. *
  4. * Copyright (c) Facebook, Inc. and its affiliates.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE file in the root directory of this source tree.
  8. */
  9. 'use strict';
  10. if (process.env.NODE_ENV !== "production") {
  11. (function() {
  12. 'use strict';
  13. function _unsupportedIterableToArray(o, minLen) {
  14. if (!o) return;
  15. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  16. var n = Object.prototype.toString.call(o).slice(8, -1);
  17. if (n === "Object" && o.constructor) n = o.constructor.name;
  18. if (n === "Map" || n === "Set") return Array.from(o);
  19. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  20. }
  21. function _arrayLikeToArray(arr, len) {
  22. if (len == null || len > arr.length) len = arr.length;
  23. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  24. return arr2;
  25. }
  26. function _createForOfIteratorHelper(o, allowArrayLike) {
  27. var it;
  28. if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
  29. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  30. if (it) o = it;
  31. var i = 0;
  32. var F = function () {};
  33. return {
  34. s: F,
  35. n: function () {
  36. if (i >= o.length) return {
  37. done: true
  38. };
  39. return {
  40. done: false,
  41. value: o[i++]
  42. };
  43. },
  44. e: function (e) {
  45. throw e;
  46. },
  47. f: F
  48. };
  49. }
  50. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  51. }
  52. var normalCompletion = true,
  53. didErr = false,
  54. err;
  55. return {
  56. s: function () {
  57. it = o[Symbol.iterator]();
  58. },
  59. n: function () {
  60. var step = it.next();
  61. normalCompletion = step.done;
  62. return step;
  63. },
  64. e: function (e) {
  65. didErr = true;
  66. err = e;
  67. },
  68. f: function () {
  69. try {
  70. if (!normalCompletion && it.return != null) it.return();
  71. } finally {
  72. if (didErr) throw err;
  73. }
  74. }
  75. };
  76. }
  77. /* eslint-disable no-for-of-loops/no-for-of-loops */
  78. function isHookName(s) {
  79. return /^use[A-Z0-9].*$/.test(s);
  80. }
  81. /**
  82. * We consider hooks to be a hook name identifier or a member expression
  83. * containing a hook name.
  84. */
  85. function isHook(node) {
  86. if (node.type === 'Identifier') {
  87. return isHookName(node.name);
  88. } else if (node.type === 'MemberExpression' && !node.computed && isHook(node.property)) {
  89. var obj = node.object;
  90. var isPascalCaseNameSpace = /^[A-Z].*/;
  91. return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name);
  92. } else {
  93. return false;
  94. }
  95. }
  96. /**
  97. * Checks if the node is a React component name. React component names must
  98. * always start with a non-lowercase letter. So `MyComponent` or `_MyComponent`
  99. * are valid component names for instance.
  100. */
  101. function isComponentName(node) {
  102. if (node.type === 'Identifier') {
  103. return !/^[a-z]/.test(node.name);
  104. } else {
  105. return false;
  106. }
  107. }
  108. function isReactFunction(node, functionName) {
  109. return node.name === functionName || node.type === 'MemberExpression' && node.object.name === 'React' && node.property.name === functionName;
  110. }
  111. /**
  112. * Checks if the node is a callback argument of forwardRef. This render function
  113. * should follow the rules of hooks.
  114. */
  115. function isForwardRefCallback(node) {
  116. return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'forwardRef'));
  117. }
  118. /**
  119. * Checks if the node is a callback argument of React.memo. This anonymous
  120. * functional component should follow the rules of hooks.
  121. */
  122. function isMemoCallback(node) {
  123. return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'memo'));
  124. }
  125. function isInsideComponentOrHook(node) {
  126. while (node) {
  127. var functionName = getFunctionName(node);
  128. if (functionName) {
  129. if (isComponentName(functionName) || isHook(functionName)) {
  130. return true;
  131. }
  132. }
  133. if (isForwardRefCallback(node) || isMemoCallback(node)) {
  134. return true;
  135. }
  136. node = node.parent;
  137. }
  138. return false;
  139. }
  140. var RulesOfHooks = {
  141. meta: {
  142. type: 'problem',
  143. docs: {
  144. description: 'enforces the Rules of Hooks',
  145. category: 'Possible Errors',
  146. recommended: true,
  147. url: 'https://reactjs.org/docs/hooks-rules.html'
  148. }
  149. },
  150. create: function (context) {
  151. var codePathReactHooksMapStack = [];
  152. var codePathSegmentStack = [];
  153. return {
  154. // Maintain code segment path stack as we traverse.
  155. onCodePathSegmentStart: function (segment) {
  156. return codePathSegmentStack.push(segment);
  157. },
  158. onCodePathSegmentEnd: function () {
  159. return codePathSegmentStack.pop();
  160. },
  161. // Maintain code path stack as we traverse.
  162. onCodePathStart: function () {
  163. return codePathReactHooksMapStack.push(new Map());
  164. },
  165. // Process our code path.
  166. //
  167. // Everything is ok if all React Hooks are both reachable from the initial
  168. // segment and reachable from every final segment.
  169. onCodePathEnd: function (codePath, codePathNode) {
  170. var reactHooksMap = codePathReactHooksMapStack.pop();
  171. if (reactHooksMap.size === 0) {
  172. return;
  173. } // All of the segments which are cyclic are recorded in this set.
  174. var cyclic = new Set();
  175. /**
  176. * Count the number of code paths from the start of the function to this
  177. * segment. For example:
  178. *
  179. * ```js
  180. * function MyComponent() {
  181. * if (condition) {
  182. * // Segment 1
  183. * } else {
  184. * // Segment 2
  185. * }
  186. * // Segment 3
  187. * }
  188. * ```
  189. *
  190. * Segments 1 and 2 have one path to the beginning of `MyComponent` and
  191. * segment 3 has two paths to the beginning of `MyComponent` since we
  192. * could have either taken the path of segment 1 or segment 2.
  193. *
  194. * Populates `cyclic` with cyclic segments.
  195. */
  196. function countPathsFromStart(segment, pathHistory) {
  197. var cache = countPathsFromStart.cache;
  198. var paths = cache.get(segment.id);
  199. var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
  200. // We need to fill `cyclic` with all segments inside cycle
  201. if (pathList.has(segment.id)) {
  202. var pathArray = [].concat(pathList);
  203. var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
  204. var _iterator = _createForOfIteratorHelper(cyclicSegments),
  205. _step;
  206. try {
  207. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  208. var cyclicSegment = _step.value;
  209. cyclic.add(cyclicSegment);
  210. }
  211. } catch (err) {
  212. _iterator.e(err);
  213. } finally {
  214. _iterator.f();
  215. }
  216. return 0;
  217. } // add the current segment to pathList
  218. pathList.add(segment.id); // We have a cached `paths`. Return it.
  219. if (paths !== undefined) {
  220. return paths;
  221. }
  222. if (codePath.thrownSegments.includes(segment)) {
  223. paths = 0;
  224. } else if (segment.prevSegments.length === 0) {
  225. paths = 1;
  226. } else {
  227. paths = 0;
  228. var _iterator2 = _createForOfIteratorHelper(segment.prevSegments),
  229. _step2;
  230. try {
  231. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  232. var prevSegment = _step2.value;
  233. paths += countPathsFromStart(prevSegment, pathList);
  234. }
  235. } catch (err) {
  236. _iterator2.e(err);
  237. } finally {
  238. _iterator2.f();
  239. }
  240. } // If our segment is reachable then there should be at least one path
  241. // to it from the start of our code path.
  242. if (segment.reachable && paths === 0) {
  243. cache.delete(segment.id);
  244. } else {
  245. cache.set(segment.id, paths);
  246. }
  247. return paths;
  248. }
  249. /**
  250. * Count the number of code paths from this segment to the end of the
  251. * function. For example:
  252. *
  253. * ```js
  254. * function MyComponent() {
  255. * // Segment 1
  256. * if (condition) {
  257. * // Segment 2
  258. * } else {
  259. * // Segment 3
  260. * }
  261. * }
  262. * ```
  263. *
  264. * Segments 2 and 3 have one path to the end of `MyComponent` and
  265. * segment 1 has two paths to the end of `MyComponent` since we could
  266. * either take the path of segment 1 or segment 2.
  267. *
  268. * Populates `cyclic` with cyclic segments.
  269. */
  270. function countPathsToEnd(segment, pathHistory) {
  271. var cache = countPathsToEnd.cache;
  272. var paths = cache.get(segment.id);
  273. var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
  274. // We need to fill `cyclic` with all segments inside cycle
  275. if (pathList.has(segment.id)) {
  276. var pathArray = Array.from(pathList);
  277. var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
  278. var _iterator3 = _createForOfIteratorHelper(cyclicSegments),
  279. _step3;
  280. try {
  281. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  282. var cyclicSegment = _step3.value;
  283. cyclic.add(cyclicSegment);
  284. }
  285. } catch (err) {
  286. _iterator3.e(err);
  287. } finally {
  288. _iterator3.f();
  289. }
  290. return 0;
  291. } // add the current segment to pathList
  292. pathList.add(segment.id); // We have a cached `paths`. Return it.
  293. if (paths !== undefined) {
  294. return paths;
  295. }
  296. if (codePath.thrownSegments.includes(segment)) {
  297. paths = 0;
  298. } else if (segment.nextSegments.length === 0) {
  299. paths = 1;
  300. } else {
  301. paths = 0;
  302. var _iterator4 = _createForOfIteratorHelper(segment.nextSegments),
  303. _step4;
  304. try {
  305. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  306. var nextSegment = _step4.value;
  307. paths += countPathsToEnd(nextSegment, pathList);
  308. }
  309. } catch (err) {
  310. _iterator4.e(err);
  311. } finally {
  312. _iterator4.f();
  313. }
  314. }
  315. cache.set(segment.id, paths);
  316. return paths;
  317. }
  318. /**
  319. * Gets the shortest path length to the start of a code path.
  320. * For example:
  321. *
  322. * ```js
  323. * function MyComponent() {
  324. * if (condition) {
  325. * // Segment 1
  326. * }
  327. * // Segment 2
  328. * }
  329. * ```
  330. *
  331. * There is only one path from segment 1 to the code path start. Its
  332. * length is one so that is the shortest path.
  333. *
  334. * There are two paths from segment 2 to the code path start. One
  335. * through segment 1 with a length of two and another directly to the
  336. * start with a length of one. The shortest path has a length of one
  337. * so we would return that.
  338. */
  339. function shortestPathLengthToStart(segment) {
  340. var cache = shortestPathLengthToStart.cache;
  341. var length = cache.get(segment.id); // If `length` is null then we found a cycle! Return infinity since
  342. // the shortest path is definitely not the one where we looped.
  343. if (length === null) {
  344. return Infinity;
  345. } // We have a cached `length`. Return it.
  346. if (length !== undefined) {
  347. return length;
  348. } // Compute `length` and cache it. Guarding against cycles.
  349. cache.set(segment.id, null);
  350. if (segment.prevSegments.length === 0) {
  351. length = 1;
  352. } else {
  353. length = Infinity;
  354. var _iterator5 = _createForOfIteratorHelper(segment.prevSegments),
  355. _step5;
  356. try {
  357. for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
  358. var prevSegment = _step5.value;
  359. var prevLength = shortestPathLengthToStart(prevSegment);
  360. if (prevLength < length) {
  361. length = prevLength;
  362. }
  363. }
  364. } catch (err) {
  365. _iterator5.e(err);
  366. } finally {
  367. _iterator5.f();
  368. }
  369. length += 1;
  370. }
  371. cache.set(segment.id, length);
  372. return length;
  373. }
  374. countPathsFromStart.cache = new Map();
  375. countPathsToEnd.cache = new Map();
  376. shortestPathLengthToStart.cache = new Map(); // Count all code paths to the end of our component/hook. Also primes
  377. // the `countPathsToEnd` cache.
  378. var allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); // Gets the function name for our code path. If the function name is
  379. // `undefined` then we know either that we have an anonymous function
  380. // expression or our code path is not in a function. In both cases we
  381. // will want to error since neither are React function components or
  382. // hook functions - unless it is an anonymous function argument to
  383. // forwardRef or memo.
  384. var codePathFunctionName = getFunctionName(codePathNode); // This is a valid code path for React hooks if we are directly in a React
  385. // function component or we are in a hook function.
  386. var isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode);
  387. var isDirectlyInsideComponentOrHook = codePathFunctionName ? isComponentName(codePathFunctionName) || isHook(codePathFunctionName) : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); // Compute the earliest finalizer level using information from the
  388. // cache. We expect all reachable final segments to have a cache entry
  389. // after calling `visitSegment()`.
  390. var shortestFinalPathLength = Infinity;
  391. var _iterator6 = _createForOfIteratorHelper(codePath.finalSegments),
  392. _step6;
  393. try {
  394. for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
  395. var finalSegment = _step6.value;
  396. if (!finalSegment.reachable) {
  397. continue;
  398. }
  399. var length = shortestPathLengthToStart(finalSegment);
  400. if (length < shortestFinalPathLength) {
  401. shortestFinalPathLength = length;
  402. }
  403. } // Make sure all React Hooks pass our lint invariants. Log warnings
  404. // if not.
  405. } catch (err) {
  406. _iterator6.e(err);
  407. } finally {
  408. _iterator6.f();
  409. }
  410. var _iterator7 = _createForOfIteratorHelper(reactHooksMap),
  411. _step7;
  412. try {
  413. for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
  414. var _step7$value = _step7.value,
  415. segment = _step7$value[0],
  416. reactHooks = _step7$value[1];
  417. // NOTE: We could report here that the hook is not reachable, but
  418. // that would be redundant with more general "no unreachable"
  419. // lint rules.
  420. if (!segment.reachable) {
  421. continue;
  422. } // If there are any final segments with a shorter path to start then
  423. // we possibly have an early return.
  424. //
  425. // If our segment is a final segment itself then siblings could
  426. // possibly be early returns.
  427. var possiblyHasEarlyReturn = segment.nextSegments.length === 0 ? shortestFinalPathLength <= shortestPathLengthToStart(segment) : shortestFinalPathLength < shortestPathLengthToStart(segment); // Count all the paths from the start of our code path to the end of
  428. // our code path that go _through_ this segment. The critical piece
  429. // of this is _through_. If we just call `countPathsToEnd(segment)`
  430. // then we neglect that we may have gone through multiple paths to get
  431. // to this point! Consider:
  432. //
  433. // ```js
  434. // function MyComponent() {
  435. // if (a) {
  436. // // Segment 1
  437. // } else {
  438. // // Segment 2
  439. // }
  440. // // Segment 3
  441. // if (b) {
  442. // // Segment 4
  443. // } else {
  444. // // Segment 5
  445. // }
  446. // }
  447. // ```
  448. //
  449. // In this component we have four code paths:
  450. //
  451. // 1. `a = true; b = true`
  452. // 2. `a = true; b = false`
  453. // 3. `a = false; b = true`
  454. // 4. `a = false; b = false`
  455. //
  456. // From segment 3 there are two code paths to the end through segment
  457. // 4 and segment 5. However, we took two paths to get here through
  458. // segment 1 and segment 2.
  459. //
  460. // If we multiply the paths from start (two) by the paths to end (two)
  461. // for segment 3 we get four. Which is our desired count.
  462. var pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); // Is this hook a part of a cyclic segment?
  463. var cycled = cyclic.has(segment.id);
  464. var _iterator8 = _createForOfIteratorHelper(reactHooks),
  465. _step8;
  466. try {
  467. for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
  468. var hook = _step8.value;
  469. // Report an error if a hook may be called more then once.
  470. if (cycled) {
  471. context.report({
  472. node: hook,
  473. message: "React Hook \"" + context.getSource(hook) + "\" may be executed " + 'more than once. Possibly because it is called in a loop. ' + 'React Hooks must be called in the exact same order in ' + 'every component render.'
  474. });
  475. } // If this is not a valid code path for React hooks then we need to
  476. // log a warning for every hook in this code path.
  477. //
  478. // Pick a special message depending on the scope this hook was
  479. // called in.
  480. if (isDirectlyInsideComponentOrHook) {
  481. // Report an error if a hook does not reach all finalizing code
  482. // path segments.
  483. //
  484. // Special case when we think there might be an early return.
  485. if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd) {
  486. var message = "React Hook \"" + context.getSource(hook) + "\" is called " + 'conditionally. React Hooks must be called in the exact ' + 'same order in every component render.' + (possiblyHasEarlyReturn ? ' Did you accidentally call a React Hook after an' + ' early return?' : '');
  487. context.report({
  488. node: hook,
  489. message: message
  490. });
  491. }
  492. } else if (codePathNode.parent && (codePathNode.parent.type === 'MethodDefinition' || codePathNode.parent.type === 'ClassProperty') && codePathNode.parent.value === codePathNode) {
  493. // Custom message for hooks inside a class
  494. var _message = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'in a class component. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
  495. context.report({
  496. node: hook,
  497. message: _message
  498. });
  499. } else if (codePathFunctionName) {
  500. // Custom message if we found an invalid function name.
  501. var _message2 = "React Hook \"" + context.getSource(hook) + "\" is called in " + ("function \"" + context.getSource(codePathFunctionName) + "\" ") + 'that is neither a React function component nor a custom ' + 'React Hook function.' + ' React component names must start with an uppercase letter.';
  502. context.report({
  503. node: hook,
  504. message: _message2
  505. });
  506. } else if (codePathNode.type === 'Program') {
  507. // These are dangerous if you have inline requires enabled.
  508. var _message3 = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'at the top level. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
  509. context.report({
  510. node: hook,
  511. message: _message3
  512. });
  513. } else {
  514. // Assume in all other cases the user called a hook in some
  515. // random function callback. This should usually be true for
  516. // anonymous function expressions. Hopefully this is clarifying
  517. // enough in the common case that the incorrect message in
  518. // uncommon cases doesn't matter.
  519. if (isSomewhereInsideComponentOrHook) {
  520. var _message4 = "React Hook \"" + context.getSource(hook) + "\" cannot be called " + 'inside a callback. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
  521. context.report({
  522. node: hook,
  523. message: _message4
  524. });
  525. }
  526. }
  527. }
  528. } catch (err) {
  529. _iterator8.e(err);
  530. } finally {
  531. _iterator8.f();
  532. }
  533. }
  534. } catch (err) {
  535. _iterator7.e(err);
  536. } finally {
  537. _iterator7.f();
  538. }
  539. },
  540. // Missed opportunity...We could visit all `Identifier`s instead of all
  541. // `CallExpression`s and check that _every use_ of a hook name is valid.
  542. // But that gets complicated and enters type-system territory, so we're
  543. // only being strict about hook calls for now.
  544. CallExpression: function (node) {
  545. if (isHook(node.callee)) {
  546. // Add the hook node to a map keyed by the code path segment. We will
  547. // do full code path analysis at the end of our code path.
  548. var reactHooksMap = last(codePathReactHooksMapStack);
  549. var codePathSegment = last(codePathSegmentStack);
  550. var reactHooks = reactHooksMap.get(codePathSegment);
  551. if (!reactHooks) {
  552. reactHooks = [];
  553. reactHooksMap.set(codePathSegment, reactHooks);
  554. }
  555. reactHooks.push(node.callee);
  556. }
  557. }
  558. };
  559. }
  560. };
  561. /**
  562. * Gets the static name of a function AST node. For function declarations it is
  563. * easy. For anonymous function expressions it is much harder. If you search for
  564. * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places
  565. * where JS gives anonymous function expressions names. We roughly detect the
  566. * same AST nodes with some exceptions to better fit our use case.
  567. */
  568. function getFunctionName(node) {
  569. if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' && node.id) {
  570. // function useHook() {}
  571. // const whatever = function useHook() {};
  572. //
  573. // Function declaration or function expression names win over any
  574. // assignment statements or other renames.
  575. return node.id;
  576. } else if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
  577. if (node.parent.type === 'VariableDeclarator' && node.parent.init === node) {
  578. // const useHook = () => {};
  579. return node.parent.id;
  580. } else if (node.parent.type === 'AssignmentExpression' && node.parent.right === node && node.parent.operator === '=') {
  581. // useHook = () => {};
  582. return node.parent.left;
  583. } else if (node.parent.type === 'Property' && node.parent.value === node && !node.parent.computed) {
  584. // {useHook: () => {}}
  585. // {useHook() {}}
  586. return node.parent.key; // NOTE: We could also support `ClassProperty` and `MethodDefinition`
  587. // here to be pedantic. However, hooks in a class are an anti-pattern. So
  588. // we don't allow it to error early.
  589. //
  590. // class {useHook = () => {}}
  591. // class {useHook() {}}
  592. } else if (node.parent.type === 'AssignmentPattern' && node.parent.right === node && !node.parent.computed) {
  593. // const {useHook = () => {}} = {};
  594. // ({useHook = () => {}} = {});
  595. //
  596. // Kinda clowny, but we'd said we'd follow spec convention for
  597. // `IsAnonymousFunctionDefinition()` usage.
  598. return node.parent.left;
  599. } else {
  600. return undefined;
  601. }
  602. } else {
  603. return undefined;
  604. }
  605. }
  606. /**
  607. * Convenience function for peeking the last item in a stack.
  608. */
  609. function last(array) {
  610. return array[array.length - 1];
  611. }
  612. /* eslint-disable no-for-of-loops/no-for-of-loops */
  613. var ExhaustiveDeps = {
  614. meta: {
  615. type: 'suggestion',
  616. docs: {
  617. description: 'verifies the list of dependencies for Hooks like useEffect and similar',
  618. category: 'Best Practices',
  619. recommended: true,
  620. url: 'https://github.com/facebook/react/issues/14920'
  621. },
  622. fixable: 'code',
  623. schema: [{
  624. type: 'object',
  625. additionalProperties: false,
  626. enableDangerousAutofixThisMayCauseInfiniteLoops: false,
  627. properties: {
  628. additionalHooks: {
  629. type: 'string'
  630. },
  631. enableDangerousAutofixThisMayCauseInfiniteLoops: {
  632. type: 'boolean'
  633. }
  634. }
  635. }]
  636. },
  637. create: function (context) {
  638. // Parse the `additionalHooks` regex.
  639. var additionalHooks = context.options && context.options[0] && context.options[0].additionalHooks ? new RegExp(context.options[0].additionalHooks) : undefined;
  640. var enableDangerousAutofixThisMayCauseInfiniteLoops = context.options && context.options[0] && context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops || false;
  641. var options = {
  642. additionalHooks: additionalHooks,
  643. enableDangerousAutofixThisMayCauseInfiniteLoops: enableDangerousAutofixThisMayCauseInfiniteLoops
  644. };
  645. function reportProblem(problem) {
  646. if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
  647. // Used to enable legacy behavior. Dangerous.
  648. // Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension).
  649. if (Array.isArray(problem.suggest) && problem.suggest.length > 0) {
  650. problem.fix = problem.suggest[0].fix;
  651. }
  652. }
  653. context.report(problem);
  654. }
  655. var scopeManager = context.getSourceCode().scopeManager; // Should be shared between visitors.
  656. var setStateCallSites = new WeakMap();
  657. var stateVariables = new WeakSet();
  658. var stableKnownValueCache = new WeakMap();
  659. var functionWithoutCapturedValueCache = new WeakMap();
  660. function memoizeWithWeakMap(fn, map) {
  661. return function (arg) {
  662. if (map.has(arg)) {
  663. // to verify cache hits:
  664. // console.log(arg.name)
  665. return map.get(arg);
  666. }
  667. var result = fn(arg);
  668. map.set(arg, result);
  669. return result;
  670. };
  671. }
  672. /**
  673. * Visitor for both function expressions and arrow function expressions.
  674. */
  675. function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect) {
  676. if (isEffect && node.async) {
  677. reportProblem({
  678. node: node,
  679. message: "Effect callbacks are synchronous to prevent race conditions. " + "Put the async function inside:\n\n" + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'
  680. });
  681. } // Get the current scope.
  682. var scope = scopeManager.acquire(node); // Find all our "pure scopes". On every re-render of a component these
  683. // pure scopes may have changes to the variables declared within. So all
  684. // variables used in our reactive hook callback but declared in a pure
  685. // scope need to be listed as dependencies of our reactive hook callback.
  686. //
  687. // According to the rules of React you can't read a mutable value in pure
  688. // scope. We can't enforce this in a lint so we trust that all variables
  689. // declared outside of pure scope are indeed frozen.
  690. var pureScopes = new Set();
  691. var componentScope = null;
  692. {
  693. var currentScope = scope.upper;
  694. while (currentScope) {
  695. pureScopes.add(currentScope);
  696. if (currentScope.type === 'function') {
  697. break;
  698. }
  699. currentScope = currentScope.upper;
  700. } // If there is no parent function scope then there are no pure scopes.
  701. // The ones we've collected so far are incorrect. So don't continue with
  702. // the lint.
  703. if (!currentScope) {
  704. return;
  705. }
  706. componentScope = currentScope;
  707. } // Next we'll define a few helpers that helps us
  708. // tell if some values don't have to be declared as deps.
  709. // Some are known to be stable based on Hook calls.
  710. // const [state, setState] = useState() / React.useState()
  711. // ^^^ true for this reference
  712. // const [state, dispatch] = useReducer() / React.useReducer()
  713. // ^^^ true for this reference
  714. // const ref = useRef()
  715. // ^^^ true for this reference
  716. // False for everything else.
  717. function isStableKnownHookValue(resolved) {
  718. if (!Array.isArray(resolved.defs)) {
  719. return false;
  720. }
  721. var def = resolved.defs[0];
  722. if (def == null) {
  723. return false;
  724. } // Look for `let stuff = ...`
  725. if (def.node.type !== 'VariableDeclarator') {
  726. return false;
  727. }
  728. var init = def.node.init;
  729. if (init == null) {
  730. return false;
  731. }
  732. while (init.type === 'TSAsExpression') {
  733. init = init.expression;
  734. } // Detect primitive constants
  735. // const foo = 42
  736. var declaration = def.node.parent;
  737. if (declaration == null) {
  738. // This might happen if variable is declared after the callback.
  739. // In that case ESLint won't set up .parent refs.
  740. // So we'll set them up manually.
  741. fastFindReferenceWithParent(componentScope.block, def.node.id);
  742. declaration = def.node.parent;
  743. if (declaration == null) {
  744. return false;
  745. }
  746. }
  747. if (declaration.kind === 'const' && init.type === 'Literal' && (typeof init.value === 'string' || typeof init.value === 'number' || init.value === null)) {
  748. // Definitely stable
  749. return true;
  750. } // Detect known Hook calls
  751. // const [_, setState] = useState()
  752. if (init.type !== 'CallExpression') {
  753. return false;
  754. }
  755. var callee = init.callee; // Step into `= React.something` initializer.
  756. if (callee.type === 'MemberExpression' && callee.object.name === 'React' && callee.property != null && !callee.computed) {
  757. callee = callee.property;
  758. }
  759. if (callee.type !== 'Identifier') {
  760. return false;
  761. }
  762. var id = def.node.id;
  763. var _callee = callee,
  764. name = _callee.name;
  765. if (name === 'useRef' && id.type === 'Identifier') {
  766. // useRef() return value is stable.
  767. return true;
  768. } else if (name === 'useState' || name === 'useReducer') {
  769. // Only consider second value in initializing tuple stable.
  770. if (id.type === 'ArrayPattern' && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
  771. // Is second tuple value the same reference we're checking?
  772. if (id.elements[1] === resolved.identifiers[0]) {
  773. if (name === 'useState') {
  774. var references = resolved.references;
  775. for (var i = 0; i < references.length; i++) {
  776. setStateCallSites.set(references[i].identifier, id.elements[0]);
  777. }
  778. } // Setter is stable.
  779. return true;
  780. } else if (id.elements[0] === resolved.identifiers[0]) {
  781. if (name === 'useState') {
  782. var _references = resolved.references;
  783. for (var _i = 0; _i < _references.length; _i++) {
  784. stateVariables.add(_references[_i].identifier);
  785. }
  786. } // State variable itself is dynamic.
  787. return false;
  788. }
  789. }
  790. } else if (name === 'useTransition') {
  791. if (id.type === 'ArrayPattern' && Array.isArray(resolved.identifiers)) {
  792. // Is first tuple value the same reference we're checking?
  793. if (id.elements[0] === resolved.identifiers[0]) {
  794. // Setter is stable.
  795. return true;
  796. }
  797. }
  798. } // By default assume it's dynamic.
  799. return false;
  800. } // Some are just functions that don't reference anything dynamic.
  801. function isFunctionWithoutCapturedValues(resolved) {
  802. if (!Array.isArray(resolved.defs)) {
  803. return false;
  804. }
  805. var def = resolved.defs[0];
  806. if (def == null) {
  807. return false;
  808. }
  809. if (def.node == null || def.node.id == null) {
  810. return false;
  811. } // Search the direct component subscopes for
  812. // top-level function definitions matching this reference.
  813. var fnNode = def.node;
  814. var childScopes = componentScope.childScopes;
  815. var fnScope = null;
  816. var i;
  817. for (i = 0; i < childScopes.length; i++) {
  818. var childScope = childScopes[i];
  819. var childScopeBlock = childScope.block;
  820. if ( // function handleChange() {}
  821. fnNode.type === 'FunctionDeclaration' && childScopeBlock === fnNode || // const handleChange = () => {}
  822. // const handleChange = function() {}
  823. fnNode.type === 'VariableDeclarator' && childScopeBlock.parent === fnNode) {
  824. // Found it!
  825. fnScope = childScope;
  826. break;
  827. }
  828. }
  829. if (fnScope == null) {
  830. return false;
  831. } // Does this function capture any values
  832. // that are in pure scopes (aka render)?
  833. for (i = 0; i < fnScope.through.length; i++) {
  834. var ref = fnScope.through[i];
  835. if (ref.resolved == null) {
  836. continue;
  837. }
  838. if (pureScopes.has(ref.resolved.scope) && // Stable values are fine though,
  839. // although we won't check functions deeper.
  840. !memoizedIsStablecKnownHookValue(ref.resolved)) {
  841. return false;
  842. }
  843. } // If we got here, this function doesn't capture anything
  844. // from render--or everything it captures is known stable.
  845. return true;
  846. } // Remember such values. Avoid re-running extra checks on them.
  847. var memoizedIsStablecKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache);
  848. var memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); // These are usually mistaken. Collect them.
  849. var currentRefsInEffectCleanup = new Map(); // Is this reference inside a cleanup function for this effect node?
  850. // We can check by traversing scopes upwards from the reference, and checking
  851. // if the last "return () => " we encounter is located directly inside the effect.
  852. function isInsideEffectCleanup(reference) {
  853. var curScope = reference.from;
  854. var isInReturnedFunction = false;
  855. while (curScope.block !== node) {
  856. if (curScope.type === 'function') {
  857. isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === 'ReturnStatement';
  858. }
  859. curScope = curScope.upper;
  860. }
  861. return isInReturnedFunction;
  862. } // Get dependencies from all our resolved references in pure scopes.
  863. // Key is dependency string, value is whether it's stable.
  864. var dependencies = new Map();
  865. var optionalChains = new Map();
  866. gatherDependenciesRecursively(scope);
  867. function gatherDependenciesRecursively(currentScope) {
  868. var _iterator = _createForOfIteratorHelper(currentScope.references),
  869. _step;
  870. try {
  871. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  872. var reference = _step.value;
  873. // If this reference is not resolved or it is not declared in a pure
  874. // scope then we don't care about this reference.
  875. if (!reference.resolved) {
  876. continue;
  877. }
  878. if (!pureScopes.has(reference.resolved.scope)) {
  879. continue;
  880. } // Narrow the scope of a dependency if it is, say, a member expression.
  881. // Then normalize the narrowed dependency.
  882. var referenceNode = fastFindReferenceWithParent(node, reference.identifier);
  883. var dependencyNode = getDependency(referenceNode);
  884. var dependency = analyzePropertyChain(dependencyNode, optionalChains); // Accessing ref.current inside effect cleanup is bad.
  885. if ( // We're in an effect...
  886. isEffect && // ... and this look like accessing .current...
  887. dependencyNode.type === 'Identifier' && (dependencyNode.parent.type === 'MemberExpression' || dependencyNode.parent.type === 'OptionalMemberExpression') && !dependencyNode.parent.computed && dependencyNode.parent.property.type === 'Identifier' && dependencyNode.parent.property.name === 'current' && // ...in a cleanup function or below...
  888. isInsideEffectCleanup(reference)) {
  889. currentRefsInEffectCleanup.set(dependency, {
  890. reference: reference,
  891. dependencyNode: dependencyNode
  892. });
  893. }
  894. if (dependencyNode.parent.type === 'TSTypeQuery' || dependencyNode.parent.type === 'TSTypeReference') {
  895. continue;
  896. }
  897. var def = reference.resolved.defs[0];
  898. if (def == null) {
  899. continue;
  900. } // Ignore references to the function itself as it's not defined yet.
  901. if (def.node != null && def.node.init === node.parent) {
  902. continue;
  903. } // Ignore Flow type parameters
  904. if (def.type === 'TypeParameter') {
  905. continue;
  906. } // Add the dependency to a map so we can make sure it is referenced
  907. // again in our dependencies array. Remember whether it's stable.
  908. if (!dependencies.has(dependency)) {
  909. var resolved = reference.resolved;
  910. var isStable = memoizedIsStablecKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
  911. dependencies.set(dependency, {
  912. isStable: isStable,
  913. references: [reference]
  914. });
  915. } else {
  916. dependencies.get(dependency).references.push(reference);
  917. }
  918. }
  919. } catch (err) {
  920. _iterator.e(err);
  921. } finally {
  922. _iterator.f();
  923. }
  924. var _iterator2 = _createForOfIteratorHelper(currentScope.childScopes),
  925. _step2;
  926. try {
  927. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  928. var childScope = _step2.value;
  929. gatherDependenciesRecursively(childScope);
  930. }
  931. } catch (err) {
  932. _iterator2.e(err);
  933. } finally {
  934. _iterator2.f();
  935. }
  936. } // Warn about accessing .current in cleanup effects.
  937. currentRefsInEffectCleanup.forEach(function (_ref, dependency) {
  938. var reference = _ref.reference,
  939. dependencyNode = _ref.dependencyNode;
  940. var references = reference.resolved.references; // Is React managing this ref or us?
  941. // Let's see if we can find a .current assignment.
  942. var foundCurrentAssignment = false;
  943. for (var i = 0; i < references.length; i++) {
  944. var identifier = references[i].identifier;
  945. var parent = identifier.parent;
  946. if (parent != null && // ref.current
  947. // Note: no need to handle OptionalMemberExpression because it can't be LHS.
  948. parent.type === 'MemberExpression' && !parent.computed && parent.property.type === 'Identifier' && parent.property.name === 'current' && // ref.current = <something>
  949. parent.parent.type === 'AssignmentExpression' && parent.parent.left === parent) {
  950. foundCurrentAssignment = true;
  951. break;
  952. }
  953. } // We only want to warn about React-managed refs.
  954. if (foundCurrentAssignment) {
  955. return;
  956. }
  957. reportProblem({
  958. node: dependencyNode.parent.property,
  959. message: "The ref value '" + dependency + ".current' will likely have " + "changed by the time this effect cleanup function runs. If " + "this ref points to a node rendered by React, copy " + ("'" + dependency + ".current' to a variable inside the effect, and ") + "use that variable in the cleanup function."
  960. });
  961. }); // Warn about assigning to variables in the outer scope.
  962. // Those are usually bugs.
  963. var staleAssignments = new Set();
  964. function reportStaleAssignment(writeExpr, key) {
  965. if (staleAssignments.has(key)) {
  966. return;
  967. }
  968. staleAssignments.add(key);
  969. reportProblem({
  970. node: writeExpr,
  971. message: "Assignments to the '" + key + "' variable from inside React Hook " + (context.getSource(reactiveHook) + " will be lost after each ") + "render. To preserve the value over time, store it in a useRef " + "Hook and keep the mutable value in the '.current' property. " + "Otherwise, you can move this variable directly inside " + (context.getSource(reactiveHook) + ".")
  972. });
  973. } // Remember which deps are stable and report bad usage first.
  974. var stableDependencies = new Set();
  975. dependencies.forEach(function (_ref2, key) {
  976. var isStable = _ref2.isStable,
  977. references = _ref2.references;
  978. if (isStable) {
  979. stableDependencies.add(key);
  980. }
  981. references.forEach(function (reference) {
  982. if (reference.writeExpr) {
  983. reportStaleAssignment(reference.writeExpr, key);
  984. }
  985. });
  986. });
  987. if (staleAssignments.size > 0) {
  988. // The intent isn't clear so we'll wait until you fix those first.
  989. return;
  990. }
  991. if (!declaredDependenciesNode) {
  992. // Check if there are any top-level setState() calls.
  993. // Those tend to lead to infinite loops.
  994. var setStateInsideEffectWithoutDeps = null;
  995. dependencies.forEach(function (_ref3, key) {
  996. var isStable = _ref3.isStable,
  997. references = _ref3.references;
  998. if (setStateInsideEffectWithoutDeps) {
  999. return;
  1000. }
  1001. references.forEach(function (reference) {
  1002. if (setStateInsideEffectWithoutDeps) {
  1003. return;
  1004. }
  1005. var id = reference.identifier;
  1006. var isSetState = setStateCallSites.has(id);
  1007. if (!isSetState) {
  1008. return;
  1009. }
  1010. var fnScope = reference.from;
  1011. while (fnScope.type !== 'function') {
  1012. fnScope = fnScope.upper;
  1013. }
  1014. var isDirectlyInsideEffect = fnScope.block === node;
  1015. if (isDirectlyInsideEffect) {
  1016. // TODO: we could potentially ignore early returns.
  1017. setStateInsideEffectWithoutDeps = key;
  1018. }
  1019. });
  1020. });
  1021. if (setStateInsideEffectWithoutDeps) {
  1022. var _collectRecommendatio = collectRecommendations({
  1023. dependencies: dependencies,
  1024. declaredDependencies: [],
  1025. stableDependencies: stableDependencies,
  1026. externalDependencies: new Set(),
  1027. isEffect: true
  1028. }),
  1029. _suggestedDependencies = _collectRecommendatio.suggestedDependencies;
  1030. reportProblem({
  1031. node: reactiveHook,
  1032. message: "React Hook " + reactiveHookName + " contains a call to '" + setStateInsideEffectWithoutDeps + "'. " + "Without a list of dependencies, this can lead to an infinite chain of updates. " + "To fix this, pass [" + _suggestedDependencies.join(', ') + ("] as a second argument to the " + reactiveHookName + " Hook."),
  1033. suggest: [{
  1034. desc: "Add dependencies array: [" + _suggestedDependencies.join(', ') + "]",
  1035. fix: function (fixer) {
  1036. return fixer.insertTextAfter(node, ", [" + _suggestedDependencies.join(', ') + "]");
  1037. }
  1038. }]
  1039. });
  1040. }
  1041. return;
  1042. }
  1043. var declaredDependencies = [];
  1044. var externalDependencies = new Set();
  1045. if (declaredDependenciesNode.type !== 'ArrayExpression') {
  1046. // If the declared dependencies are not an array expression then we
  1047. // can't verify that the user provided the correct dependencies. Tell
  1048. // the user this in an error.
  1049. reportProblem({
  1050. node: declaredDependenciesNode,
  1051. message: "React Hook " + context.getSource(reactiveHook) + " was passed a " + 'dependency list that is not an array literal. This means we ' + "can't statically verify whether you've passed the correct " + 'dependencies.'
  1052. });
  1053. } else {
  1054. declaredDependenciesNode.elements.forEach(function (declaredDependencyNode) {
  1055. // Skip elided elements.
  1056. if (declaredDependencyNode === null) {
  1057. return;
  1058. } // If we see a spread element then add a special warning.
  1059. if (declaredDependencyNode.type === 'SpreadElement') {
  1060. reportProblem({
  1061. node: declaredDependencyNode,
  1062. message: "React Hook " + context.getSource(reactiveHook) + " has a spread " + "element in its dependency array. This means we can't " + "statically verify whether you've passed the " + 'correct dependencies.'
  1063. });
  1064. return;
  1065. } // Try to normalize the declared dependency. If we can't then an error
  1066. // will be thrown. We will catch that error and report an error.
  1067. var declaredDependency;
  1068. try {
  1069. declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
  1070. } catch (error) {
  1071. if (/Unsupported node type/.test(error.message)) {
  1072. if (declaredDependencyNode.type === 'Literal') {
  1073. if (dependencies.has(declaredDependencyNode.value)) {
  1074. reportProblem({
  1075. node: declaredDependencyNode,
  1076. message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + "because it never changes. " + ("Did you mean to include " + declaredDependencyNode.value + " in the array instead?")
  1077. });
  1078. } else {
  1079. reportProblem({
  1080. node: declaredDependencyNode,
  1081. message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + 'because it never changes. You can safely remove it.'
  1082. });
  1083. }
  1084. } else {
  1085. reportProblem({
  1086. node: declaredDependencyNode,
  1087. message: "React Hook " + context.getSource(reactiveHook) + " has a " + "complex expression in the dependency array. " + 'Extract it to a separate variable so it can be statically checked.'
  1088. });
  1089. }
  1090. return;
  1091. } else {
  1092. throw error;
  1093. }
  1094. }
  1095. var maybeID = declaredDependencyNode;
  1096. while (maybeID.type === 'MemberExpression' || maybeID.type === 'OptionalMemberExpression' || maybeID.type === 'ChainExpression') {
  1097. maybeID = maybeID.object || maybeID.expression.object;
  1098. }
  1099. var isDeclaredInComponent = !componentScope.through.some(function (ref) {
  1100. return ref.identifier === maybeID;
  1101. }); // Add the dependency to our declared dependency map.
  1102. declaredDependencies.push({
  1103. key: declaredDependency,
  1104. node: declaredDependencyNode
  1105. });
  1106. if (!isDeclaredInComponent) {
  1107. externalDependencies.add(declaredDependency);
  1108. }
  1109. });
  1110. }
  1111. var _collectRecommendatio2 = collectRecommendations({
  1112. dependencies: dependencies,
  1113. declaredDependencies: declaredDependencies,
  1114. stableDependencies: stableDependencies,
  1115. externalDependencies: externalDependencies,
  1116. isEffect: isEffect
  1117. }),
  1118. suggestedDependencies = _collectRecommendatio2.suggestedDependencies,
  1119. unnecessaryDependencies = _collectRecommendatio2.unnecessaryDependencies,
  1120. missingDependencies = _collectRecommendatio2.missingDependencies,
  1121. duplicateDependencies = _collectRecommendatio2.duplicateDependencies;
  1122. var suggestedDeps = suggestedDependencies;
  1123. var problemCount = duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size;
  1124. if (problemCount === 0) {
  1125. // If nothing else to report, check if some dependencies would
  1126. // invalidate on every render.
  1127. var constructions = scanForConstructions({
  1128. declaredDependencies: declaredDependencies,
  1129. declaredDependenciesNode: declaredDependenciesNode,
  1130. componentScope: componentScope,
  1131. scope: scope
  1132. });
  1133. constructions.forEach(function (_ref4) {
  1134. var construction = _ref4.construction,
  1135. isUsedOutsideOfHook = _ref4.isUsedOutsideOfHook,
  1136. depType = _ref4.depType;
  1137. var wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo';
  1138. var constructionType = depType === 'function' ? 'definition' : 'initialization';
  1139. var defaultAdvice = "wrap the " + constructionType + " of '" + construction.name.name + "' in its own " + wrapperHook + "() Hook.";
  1140. var advice = isUsedOutsideOfHook ? "To fix this, " + defaultAdvice : "Move it inside the " + reactiveHookName + " callback. Alternatively, " + defaultAdvice;
  1141. var causation = depType === 'conditional' || depType === 'logical expression' ? 'could make' : 'makes';
  1142. var message = "The '" + construction.name.name + "' " + depType + " " + causation + " the dependencies of " + (reactiveHookName + " Hook (at line " + declaredDependenciesNode.loc.start.line + ") ") + ("change on every render. " + advice);
  1143. var suggest; // Only handle the simple case of variable assignments.
  1144. // Wrapping function declarations can mess up hoisting.
  1145. if (isUsedOutsideOfHook && construction.type === 'Variable' && // Objects may be mutated ater construction, which would make this
  1146. // fix unsafe. Functions _probably_ won't be mutated, so we'll
  1147. // allow this fix for them.
  1148. depType === 'function') {
  1149. suggest = [{
  1150. desc: "Wrap the " + constructionType + " of '" + construction.name.name + "' in its own " + wrapperHook + "() Hook.",
  1151. fix: function (fixer) {
  1152. var _ref5 = wrapperHook === 'useMemo' ? ["useMemo(() => { return ", '; })'] : ['useCallback(', ')'],
  1153. before = _ref5[0],
  1154. after = _ref5[1];
  1155. return [// TODO: also add an import?
  1156. fixer.insertTextBefore(construction.node.init, before), // TODO: ideally we'd gather deps here but it would require
  1157. // restructuring the rule code. This will cause a new lint
  1158. // error to appear immediately for useCallback. Note we're
  1159. // not adding [] because would that changes semantics.
  1160. fixer.insertTextAfter(construction.node.init, after)];
  1161. }
  1162. }];
  1163. } // TODO: What if the function needs to change on every render anyway?
  1164. // Should we suggest removing effect deps as an appropriate fix too?
  1165. reportProblem({
  1166. // TODO: Why not report this at the dependency site?
  1167. node: construction.node,
  1168. message: message,
  1169. suggest: suggest
  1170. });
  1171. });
  1172. return;
  1173. } // If we're going to report a missing dependency,
  1174. // we might as well recalculate the list ignoring
  1175. // the currently specified deps. This can result
  1176. // in some extra deduplication. We can't do this
  1177. // for effects though because those have legit
  1178. // use cases for over-specifying deps.
  1179. if (!isEffect && missingDependencies.size > 0) {
  1180. suggestedDeps = collectRecommendations({
  1181. dependencies: dependencies,
  1182. declaredDependencies: [],
  1183. // Pretend we don't know
  1184. stableDependencies: stableDependencies,
  1185. externalDependencies: externalDependencies,
  1186. isEffect: isEffect
  1187. }).suggestedDependencies;
  1188. } // Alphabetize the suggestions, but only if deps were already alphabetized.
  1189. function areDeclaredDepsAlphabetized() {
  1190. if (declaredDependencies.length === 0) {
  1191. return true;
  1192. }
  1193. var declaredDepKeys = declaredDependencies.map(function (dep) {
  1194. return dep.key;
  1195. });
  1196. var sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
  1197. return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(',');
  1198. }
  1199. if (areDeclaredDepsAlphabetized()) {
  1200. suggestedDeps.sort();
  1201. } // Most of our algorithm deals with dependency paths with optional chaining stripped.
  1202. // This function is the last step before printing a dependency, so now is a good time to
  1203. // check whether any members in our path are always used as optional-only. In that case,
  1204. // we will use ?. instead of . to concatenate those parts of the path.
  1205. function formatDependency(path) {
  1206. var members = path.split('.');
  1207. var finalPath = '';
  1208. for (var i = 0; i < members.length; i++) {
  1209. if (i !== 0) {
  1210. var pathSoFar = members.slice(0, i + 1).join('.');
  1211. var isOptional = optionalChains.get(pathSoFar) === true;
  1212. finalPath += isOptional ? '?.' : '.';
  1213. }
  1214. finalPath += members[i];
  1215. }
  1216. return finalPath;
  1217. }
  1218. function getWarningMessage(deps, singlePrefix, label, fixVerb) {
  1219. if (deps.size === 0) {
  1220. return null;
  1221. }
  1222. return (deps.size > 1 ? '' : singlePrefix + ' ') + label + ' ' + (deps.size > 1 ? 'dependencies' : 'dependency') + ': ' + joinEnglish(Array.from(deps).sort().map(function (name) {
  1223. return "'" + formatDependency(name) + "'";
  1224. })) + (". Either " + fixVerb + " " + (deps.size > 1 ? 'them' : 'it') + " or remove the dependency array.");
  1225. }
  1226. var extraWarning = '';
  1227. if (unnecessaryDependencies.size > 0) {
  1228. var badRef = null;
  1229. Array.from(unnecessaryDependencies.keys()).forEach(function (key) {
  1230. if (badRef !== null) {
  1231. return;
  1232. }
  1233. if (key.endsWith('.current')) {
  1234. badRef = key;
  1235. }
  1236. });
  1237. if (badRef !== null) {
  1238. extraWarning = " Mutable values like '" + badRef + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
  1239. } else if (externalDependencies.size > 0) {
  1240. var dep = Array.from(externalDependencies)[0]; // Don't show this warning for things that likely just got moved *inside* the callback
  1241. // because in that case they're clearly not referring to globals.
  1242. if (!scope.set.has(dep)) {
  1243. extraWarning = " Outer scope values like '" + dep + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
  1244. }
  1245. }
  1246. } // `props.foo()` marks `props` as a dependency because it has
  1247. // a `this` value. This warning can be confusing.
  1248. // So if we're going to show it, append a clarification.
  1249. if (!extraWarning && missingDependencies.has('props')) {
  1250. var propDep = dependencies.get('props');
  1251. if (propDep == null) {
  1252. return;
  1253. }
  1254. var refs = propDep.references;
  1255. if (!Array.isArray(refs)) {
  1256. return;
  1257. }
  1258. var isPropsOnlyUsedInMembers = true;
  1259. for (var i = 0; i < refs.length; i++) {
  1260. var ref = refs[i];
  1261. var id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
  1262. if (!id) {
  1263. isPropsOnlyUsedInMembers = false;
  1264. break;
  1265. }
  1266. var parent = id.parent;
  1267. if (parent == null) {
  1268. isPropsOnlyUsedInMembers = false;
  1269. break;
  1270. }
  1271. if (parent.type !== 'MemberExpression' && parent.type !== 'OptionalMemberExpression') {
  1272. isPropsOnlyUsedInMembers = false;
  1273. break;
  1274. }
  1275. }
  1276. if (isPropsOnlyUsedInMembers) {
  1277. extraWarning = " However, 'props' will change when *any* prop changes, so the " + "preferred fix is to destructure the 'props' object outside of " + ("the " + reactiveHookName + " call and refer to those specific props ") + ("inside " + context.getSource(reactiveHook) + ".");
  1278. }
  1279. }
  1280. if (!extraWarning && missingDependencies.size > 0) {
  1281. // See if the user is trying to avoid specifying a callable prop.
  1282. // This usually means they're unaware of useCallback.
  1283. var missingCallbackDep = null;
  1284. missingDependencies.forEach(function (missingDep) {
  1285. if (missingCallbackDep) {
  1286. return;
  1287. } // Is this a variable from top scope?
  1288. var topScopeRef = componentScope.set.get(missingDep);
  1289. var usedDep = dependencies.get(missingDep);
  1290. if (usedDep.references[0].resolved !== topScopeRef) {
  1291. return;
  1292. } // Is this a destructured prop?
  1293. var def = topScopeRef.defs[0];
  1294. if (def == null || def.name == null || def.type !== 'Parameter') {
  1295. return;
  1296. } // Was it called in at least one case? Then it's a function.
  1297. var isFunctionCall = false;
  1298. var id;
  1299. for (var _i2 = 0; _i2 < usedDep.references.length; _i2++) {
  1300. id = usedDep.references[_i2].identifier;
  1301. if (id != null && id.parent != null && (id.parent.type === 'CallExpression' || id.parent.type === 'OptionalCallExpression') && id.parent.callee === id) {
  1302. isFunctionCall = true;
  1303. break;
  1304. }
  1305. }
  1306. if (!isFunctionCall) {
  1307. return;
  1308. } // If it's missing (i.e. in component scope) *and* it's a parameter
  1309. // then it is definitely coming from props destructuring.
  1310. // (It could also be props itself but we wouldn't be calling it then.)
  1311. missingCallbackDep = missingDep;
  1312. });
  1313. if (missingCallbackDep !== null) {
  1314. extraWarning = " If '" + missingCallbackDep + "' changes too often, " + "find the parent component that defines it " + "and wrap that definition in useCallback.";
  1315. }
  1316. }
  1317. if (!extraWarning && missingDependencies.size > 0) {
  1318. var setStateRecommendation = null;
  1319. missingDependencies.forEach(function (missingDep) {
  1320. if (setStateRecommendation !== null) {
  1321. return;
  1322. }
  1323. var usedDep = dependencies.get(missingDep);
  1324. var references = usedDep.references;
  1325. var id;
  1326. var maybeCall;
  1327. for (var _i3 = 0; _i3 < references.length; _i3++) {
  1328. id = references[_i3].identifier;
  1329. maybeCall = id.parent; // Try to see if we have setState(someExpr(missingDep)).
  1330. while (maybeCall != null && maybeCall !== componentScope.block) {
  1331. if (maybeCall.type === 'CallExpression') {
  1332. var correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
  1333. if (correspondingStateVariable != null) {
  1334. if (correspondingStateVariable.name === missingDep) {
  1335. // setCount(count + 1)
  1336. setStateRecommendation = {
  1337. missingDep: missingDep,
  1338. setter: maybeCall.callee.name,
  1339. form: 'updater'
  1340. };
  1341. } else if (stateVariables.has(id)) {
  1342. // setCount(count + increment)
  1343. setStateRecommendation = {
  1344. missingDep: missingDep,
  1345. setter: maybeCall.callee.name,
  1346. form: 'reducer'
  1347. };
  1348. } else {
  1349. var resolved = references[_i3].resolved;
  1350. if (resolved != null) {
  1351. // If it's a parameter *and* a missing dep,
  1352. // it must be a prop or something inside a prop.
  1353. // Therefore, recommend an inline reducer.
  1354. var def = resolved.defs[0];
  1355. if (def != null && def.type === 'Parameter') {
  1356. setStateRecommendation = {
  1357. missingDep: missingDep,
  1358. setter: maybeCall.callee.name,
  1359. form: 'inlineReducer'
  1360. };
  1361. }
  1362. }
  1363. }
  1364. break;
  1365. }
  1366. }
  1367. maybeCall = maybeCall.parent;
  1368. }
  1369. if (setStateRecommendation !== null) {
  1370. break;
  1371. }
  1372. }
  1373. });
  1374. if (setStateRecommendation !== null) {
  1375. switch (setStateRecommendation.form) {
  1376. case 'reducer':
  1377. extraWarning = " You can also replace multiple useState variables with useReducer " + ("if '" + setStateRecommendation.setter + "' needs the ") + ("current value of '" + setStateRecommendation.missingDep + "'.");
  1378. break;
  1379. case 'inlineReducer':
  1380. extraWarning = " If '" + setStateRecommendation.setter + "' needs the " + ("current value of '" + setStateRecommendation.missingDep + "', ") + "you can also switch to useReducer instead of useState and " + ("read '" + setStateRecommendation.missingDep + "' in the reducer.");
  1381. break;
  1382. case 'updater':
  1383. extraWarning = " You can also do a functional update '" + setStateRecommendation.setter + "(" + setStateRecommendation.missingDep.substring(0, 1) + " => ...)' if you only need '" + setStateRecommendation.missingDep + "'" + (" in the '" + setStateRecommendation.setter + "' call.");
  1384. break;
  1385. default:
  1386. throw new Error('Unknown case.');
  1387. }
  1388. }
  1389. }
  1390. reportProblem({
  1391. node: declaredDependenciesNode,
  1392. message: "React Hook " + context.getSource(reactiveHook) + " has " + ( // To avoid a long message, show the next actionable item.
  1393. getWarningMessage(missingDependencies, 'a', 'missing', 'include') || getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + extraWarning,
  1394. suggest: [{
  1395. desc: "Update the dependencies array to be: [" + suggestedDeps.map(formatDependency).join(', ') + "]",
  1396. fix: function (fixer) {
  1397. // TODO: consider preserving the comments or formatting?
  1398. return fixer.replaceText(declaredDependenciesNode, "[" + suggestedDeps.map(formatDependency).join(', ') + "]");
  1399. }
  1400. }]
  1401. });
  1402. }
  1403. function visitCallExpression(node) {
  1404. var callbackIndex = getReactiveHookCallbackIndex(node.callee, options);
  1405. if (callbackIndex === -1) {
  1406. // Not a React Hook call that needs deps.
  1407. return;
  1408. }
  1409. var callback = node.arguments[callbackIndex];
  1410. var reactiveHook = node.callee;
  1411. var reactiveHookName = getNodeWithoutReactNamespace(reactiveHook).name;
  1412. var declaredDependenciesNode = node.arguments[callbackIndex + 1];
  1413. var isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); // Check the declared dependencies for this reactive hook. If there is no
  1414. // second argument then the reactive callback will re-run on every render.
  1415. // So no need to check for dependency inclusion.
  1416. if (!declaredDependenciesNode && !isEffect) {
  1417. // These are only used for optimization.
  1418. if (reactiveHookName === 'useMemo' || reactiveHookName === 'useCallback') {
  1419. // TODO: Can this have a suggestion?
  1420. reportProblem({
  1421. node: reactiveHook,
  1422. message: "React Hook " + reactiveHookName + " does nothing when called with " + "only one argument. Did you forget to pass an array of " + "dependencies?"
  1423. });
  1424. }
  1425. return;
  1426. }
  1427. switch (callback.type) {
  1428. case 'FunctionExpression':
  1429. case 'ArrowFunctionExpression':
  1430. visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
  1431. return;
  1432. // Handled
  1433. case 'Identifier':
  1434. if (!declaredDependenciesNode) {
  1435. // No deps, no problems.
  1436. return; // Handled
  1437. } // The function passed as a callback is not written inline.
  1438. // But perhaps it's in the dependencies array?
  1439. if (declaredDependenciesNode.elements && declaredDependenciesNode.elements.some(function (el) {
  1440. return el && el.type === 'Identifier' && el.name === callback.name;
  1441. })) {
  1442. // If it's already in the list of deps, we don't care because
  1443. // this is valid regardless.
  1444. return; // Handled
  1445. } // We'll do our best effort to find it, complain otherwise.
  1446. var variable = context.getScope().set.get(callback.name);
  1447. if (variable == null || variable.defs == null) {
  1448. // If it's not in scope, we don't care.
  1449. return; // Handled
  1450. } // The function passed as a callback is not written inline.
  1451. // But it's defined somewhere in the render scope.
  1452. // We'll do our best effort to find and check it, complain otherwise.
  1453. var def = variable.defs[0];
  1454. if (!def || !def.node) {
  1455. break; // Unhandled
  1456. }
  1457. if (def.type !== 'Variable' && def.type !== 'FunctionName') {
  1458. // Parameter or an unusual pattern. Bail out.
  1459. break; // Unhandled
  1460. }
  1461. switch (def.node.type) {
  1462. case 'FunctionDeclaration':
  1463. // useEffect(() => { ... }, []);
  1464. visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
  1465. return;
  1466. // Handled
  1467. case 'VariableDeclarator':
  1468. var init = def.node.init;
  1469. if (!init) {
  1470. break; // Unhandled
  1471. }
  1472. switch (init.type) {
  1473. // const effectBody = () => {...};
  1474. // useEffect(effectBody, []);
  1475. case 'ArrowFunctionExpression':
  1476. case 'FunctionExpression':
  1477. // We can inspect this function as if it were inline.
  1478. visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
  1479. return;
  1480. // Handled
  1481. }
  1482. break;
  1483. // Unhandled
  1484. }
  1485. break;
  1486. // Unhandled
  1487. default:
  1488. // useEffect(generateEffectBody(), []);
  1489. reportProblem({
  1490. node: reactiveHook,
  1491. message: "React Hook " + reactiveHookName + " received a function whose dependencies " + "are unknown. Pass an inline function instead."
  1492. });
  1493. return;
  1494. // Handled
  1495. } // Something unusual. Fall back to suggesting to add the body itself as a dep.
  1496. reportProblem({
  1497. node: reactiveHook,
  1498. message: "React Hook " + reactiveHookName + " has a missing dependency: '" + callback.name + "'. " + "Either include it or remove the dependency array.",
  1499. suggest: [{
  1500. desc: "Update the dependencies array to be: [" + callback.name + "]",
  1501. fix: function (fixer) {
  1502. return fixer.replaceText(declaredDependenciesNode, "[" + callback.name + "]");
  1503. }
  1504. }]
  1505. });
  1506. }
  1507. return {
  1508. CallExpression: visitCallExpression
  1509. };
  1510. }
  1511. }; // The meat of the logic.
  1512. function collectRecommendations(_ref6) {
  1513. var dependencies = _ref6.dependencies,
  1514. declaredDependencies = _ref6.declaredDependencies,
  1515. stableDependencies = _ref6.stableDependencies,
  1516. externalDependencies = _ref6.externalDependencies,
  1517. isEffect = _ref6.isEffect;
  1518. // Our primary data structure.
  1519. // It is a logical representation of property chains:
  1520. // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz`
  1521. // -> `props.lol`
  1522. // -> `props.huh` -> `props.huh.okay`
  1523. // -> `props.wow`
  1524. // We'll use it to mark nodes that are *used* by the programmer,
  1525. // and the nodes that were *declared* as deps. Then we will
  1526. // traverse it to learn which deps are missing or unnecessary.
  1527. var depTree = createDepTree();
  1528. function createDepTree() {
  1529. return {
  1530. isUsed: false,
  1531. // True if used in code
  1532. isSatisfiedRecursively: false,
  1533. // True if specified in deps
  1534. isSubtreeUsed: false,
  1535. // True if something deeper is used by code
  1536. children: new Map() // Nodes for properties
  1537. };
  1538. } // Mark all required nodes first.
  1539. // Imagine exclamation marks next to each used deep property.
  1540. dependencies.forEach(function (_, key) {
  1541. var node = getOrCreateNodeByPath(depTree, key);
  1542. node.isUsed = true;
  1543. markAllParentsByPath(depTree, key, function (parent) {
  1544. parent.isSubtreeUsed = true;
  1545. });
  1546. }); // Mark all satisfied nodes.
  1547. // Imagine checkmarks next to each declared dependency.
  1548. declaredDependencies.forEach(function (_ref7) {
  1549. var key = _ref7.key;
  1550. var node = getOrCreateNodeByPath(depTree, key);
  1551. node.isSatisfiedRecursively = true;
  1552. });
  1553. stableDependencies.forEach(function (key) {
  1554. var node = getOrCreateNodeByPath(depTree, key);
  1555. node.isSatisfiedRecursively = true;
  1556. }); // Tree manipulation helpers.
  1557. function getOrCreateNodeByPath(rootNode, path) {
  1558. var keys = path.split('.');
  1559. var node = rootNode;
  1560. var _iterator3 = _createForOfIteratorHelper(keys),
  1561. _step3;
  1562. try {
  1563. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  1564. var key = _step3.value;
  1565. var child = node.children.get(key);
  1566. if (!child) {
  1567. child = createDepTree();
  1568. node.children.set(key, child);
  1569. }
  1570. node = child;
  1571. }
  1572. } catch (err) {
  1573. _iterator3.e(err);
  1574. } finally {
  1575. _iterator3.f();
  1576. }
  1577. return node;
  1578. }
  1579. function markAllParentsByPath(rootNode, path, fn) {
  1580. var keys = path.split('.');
  1581. var node = rootNode;
  1582. var _iterator4 = _createForOfIteratorHelper(keys),
  1583. _step4;
  1584. try {
  1585. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  1586. var key = _step4.value;
  1587. var child = node.children.get(key);
  1588. if (!child) {
  1589. return;
  1590. }
  1591. fn(child);
  1592. node = child;
  1593. }
  1594. } catch (err) {
  1595. _iterator4.e(err);
  1596. } finally {
  1597. _iterator4.f();
  1598. }
  1599. } // Now we can learn which dependencies are missing or necessary.
  1600. var missingDependencies = new Set();
  1601. var satisfyingDependencies = new Set();
  1602. scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, function (key) {
  1603. return key;
  1604. });
  1605. function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
  1606. node.children.forEach(function (child, key) {
  1607. var path = keyToPath(key);
  1608. if (child.isSatisfiedRecursively) {
  1609. if (child.isSubtreeUsed) {
  1610. // Remember this dep actually satisfied something.
  1611. satisfyingPaths.add(path);
  1612. } // It doesn't matter if there's something deeper.
  1613. // It would be transitively satisfied since we assume immutability.
  1614. // `props.foo` is enough if you read `props.foo.id`.
  1615. return;
  1616. }
  1617. if (child.isUsed) {
  1618. // Remember that no declared deps satisfied this node.
  1619. missingPaths.add(path); // If we got here, nothing in its subtree was satisfied.
  1620. // No need to search further.
  1621. return;
  1622. }
  1623. scanTreeRecursively(child, missingPaths, satisfyingPaths, function (childKey) {
  1624. return path + '.' + childKey;
  1625. });
  1626. });
  1627. } // Collect suggestions in the order they were originally specified.
  1628. var suggestedDependencies = [];
  1629. var unnecessaryDependencies = new Set();
  1630. var duplicateDependencies = new Set();
  1631. declaredDependencies.forEach(function (_ref8) {
  1632. var key = _ref8.key;
  1633. // Does this declared dep satisfy a real need?
  1634. if (satisfyingDependencies.has(key)) {
  1635. if (suggestedDependencies.indexOf(key) === -1) {
  1636. // Good one.
  1637. suggestedDependencies.push(key);
  1638. } else {
  1639. // Duplicate.
  1640. duplicateDependencies.add(key);
  1641. }
  1642. } else {
  1643. if (isEffect && !key.endsWith('.current') && !externalDependencies.has(key)) {
  1644. // Effects are allowed extra "unnecessary" deps.
  1645. // Such as resetting scroll when ID changes.
  1646. // Consider them legit.
  1647. // The exception is ref.current which is always wrong.
  1648. if (suggestedDependencies.indexOf(key) === -1) {
  1649. suggestedDependencies.push(key);
  1650. }
  1651. } else {
  1652. // It's definitely not needed.
  1653. unnecessaryDependencies.add(key);
  1654. }
  1655. }
  1656. }); // Then add the missing ones at the end.
  1657. missingDependencies.forEach(function (key) {
  1658. suggestedDependencies.push(key);
  1659. });
  1660. return {
  1661. suggestedDependencies: suggestedDependencies,
  1662. unnecessaryDependencies: unnecessaryDependencies,
  1663. duplicateDependencies: duplicateDependencies,
  1664. missingDependencies: missingDependencies
  1665. };
  1666. } // If the node will result in constructing a referentially unique value, return
  1667. // its human readable type name, else return null.
  1668. function getConstructionExpressionType(node) {
  1669. switch (node.type) {
  1670. case 'ObjectExpression':
  1671. return 'object';
  1672. case 'ArrayExpression':
  1673. return 'array';
  1674. case 'ArrowFunctionExpression':
  1675. case 'FunctionExpression':
  1676. return 'function';
  1677. case 'ClassExpression':
  1678. return 'class';
  1679. case 'ConditionalExpression':
  1680. if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) {
  1681. return 'conditional';
  1682. }
  1683. return null;
  1684. case 'LogicalExpression':
  1685. if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) {
  1686. return 'logical expression';
  1687. }
  1688. return null;
  1689. case 'JSXFragment':
  1690. return 'JSX fragment';
  1691. case 'JSXElement':
  1692. return 'JSX element';
  1693. case 'AssignmentExpression':
  1694. if (getConstructionExpressionType(node.right) != null) {
  1695. return 'assignment expression';
  1696. }
  1697. return null;
  1698. case 'NewExpression':
  1699. return 'object construction';
  1700. case 'Literal':
  1701. if (node.value instanceof RegExp) {
  1702. return 'regular expression';
  1703. }
  1704. return null;
  1705. case 'TypeCastExpression':
  1706. return getConstructionExpressionType(node.expression);
  1707. case 'TSAsExpression':
  1708. return getConstructionExpressionType(node.expression);
  1709. }
  1710. return null;
  1711. } // Finds variables declared as dependencies
  1712. // that would invalidate on every render.
  1713. function scanForConstructions(_ref9) {
  1714. var declaredDependencies = _ref9.declaredDependencies,
  1715. declaredDependenciesNode = _ref9.declaredDependenciesNode,
  1716. componentScope = _ref9.componentScope,
  1717. scope = _ref9.scope;
  1718. var constructions = declaredDependencies.map(function (_ref10) {
  1719. var key = _ref10.key;
  1720. var ref = componentScope.variables.find(function (v) {
  1721. return v.name === key;
  1722. });
  1723. if (ref == null) {
  1724. return null;
  1725. }
  1726. var node = ref.defs[0];
  1727. if (node == null) {
  1728. return null;
  1729. } // const handleChange = function () {}
  1730. // const handleChange = () => {}
  1731. // const foo = {}
  1732. // const foo = []
  1733. // etc.
  1734. if (node.type === 'Variable' && node.node.type === 'VariableDeclarator' && node.node.id.type === 'Identifier' && // Ensure this is not destructed assignment
  1735. node.node.init != null) {
  1736. var constantExpressionType = getConstructionExpressionType(node.node.init);
  1737. if (constantExpressionType != null) {
  1738. return [ref, constantExpressionType];
  1739. }
  1740. } // function handleChange() {}
  1741. if (node.type === 'FunctionName' && node.node.type === 'FunctionDeclaration') {
  1742. return [ref, 'function'];
  1743. } // class Foo {}
  1744. if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') {
  1745. return [ref, 'class'];
  1746. }
  1747. return null;
  1748. }).filter(Boolean);
  1749. function isUsedOutsideOfHook(ref) {
  1750. var foundWriteExpr = false;
  1751. for (var i = 0; i < ref.references.length; i++) {
  1752. var reference = ref.references[i];
  1753. if (reference.writeExpr) {
  1754. if (foundWriteExpr) {
  1755. // Two writes to the same function.
  1756. return true;
  1757. } else {
  1758. // Ignore first write as it's not usage.
  1759. foundWriteExpr = true;
  1760. continue;
  1761. }
  1762. }
  1763. var currentScope = reference.from;
  1764. while (currentScope !== scope && currentScope != null) {
  1765. currentScope = currentScope.upper;
  1766. }
  1767. if (currentScope !== scope) {
  1768. // This reference is outside the Hook callback.
  1769. // It can only be legit if it's the deps array.
  1770. if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) {
  1771. return true;
  1772. }
  1773. }
  1774. }
  1775. return false;
  1776. }
  1777. return constructions.map(function (_ref11) {
  1778. var ref = _ref11[0],
  1779. depType = _ref11[1];
  1780. return {
  1781. construction: ref.defs[0],
  1782. depType: depType,
  1783. isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
  1784. };
  1785. });
  1786. }
  1787. /**
  1788. * Assuming () means the passed/returned node:
  1789. * (props) => (props)
  1790. * props.(foo) => (props.foo)
  1791. * props.foo.(bar) => (props).foo.bar
  1792. * props.foo.bar.(baz) => (props).foo.bar.baz
  1793. */
  1794. function getDependency(node) {
  1795. if ((node.parent.type === 'MemberExpression' || node.parent.type === 'OptionalMemberExpression') && node.parent.object === node && node.parent.property.name !== 'current' && !node.parent.computed && !(node.parent.parent != null && (node.parent.parent.type === 'CallExpression' || node.parent.parent.type === 'OptionalCallExpression') && node.parent.parent.callee === node.parent)) {
  1796. return getDependency(node.parent);
  1797. } else if ( // Note: we don't check OptionalMemberExpression because it can't be LHS.
  1798. node.type === 'MemberExpression' && node.parent && node.parent.type === 'AssignmentExpression' && node.parent.left === node) {
  1799. return node.object;
  1800. } else {
  1801. return node;
  1802. }
  1803. }
  1804. /**
  1805. * Mark a node as either optional or required.
  1806. * Note: If the node argument is an OptionalMemberExpression, it doesn't necessarily mean it is optional.
  1807. * It just means there is an optional member somewhere inside.
  1808. * This particular node might still represent a required member, so check .optional field.
  1809. */
  1810. function markNode(node, optionalChains, result) {
  1811. if (optionalChains) {
  1812. if (node.optional) {
  1813. // We only want to consider it optional if *all* usages were optional.
  1814. if (!optionalChains.has(result)) {
  1815. // Mark as (maybe) optional. If there's a required usage, this will be overridden.
  1816. optionalChains.set(result, true);
  1817. }
  1818. } else {
  1819. // Mark as required.
  1820. optionalChains.set(result, false);
  1821. }
  1822. }
  1823. }
  1824. /**
  1825. * Assuming () means the passed node.
  1826. * (foo) -> 'foo'
  1827. * foo(.)bar -> 'foo.bar'
  1828. * foo.bar(.)baz -> 'foo.bar.baz'
  1829. * Otherwise throw.
  1830. */
  1831. function analyzePropertyChain(node, optionalChains) {
  1832. if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
  1833. var result = node.name;
  1834. if (optionalChains) {
  1835. // Mark as required.
  1836. optionalChains.set(result, false);
  1837. }
  1838. return result;
  1839. } else if (node.type === 'MemberExpression' && !node.computed) {
  1840. var object = analyzePropertyChain(node.object, optionalChains);
  1841. var property = analyzePropertyChain(node.property, null);
  1842. var _result = object + "." + property;
  1843. markNode(node, optionalChains, _result);
  1844. return _result;
  1845. } else if (node.type === 'OptionalMemberExpression' && !node.computed) {
  1846. var _object = analyzePropertyChain(node.object, optionalChains);
  1847. var _property = analyzePropertyChain(node.property, null);
  1848. var _result2 = _object + "." + _property;
  1849. markNode(node, optionalChains, _result2);
  1850. return _result2;
  1851. } else if (node.type === 'ChainExpression' && !node.computed) {
  1852. var expression = node.expression;
  1853. var _object2 = analyzePropertyChain(expression.object, optionalChains);
  1854. var _property2 = analyzePropertyChain(expression.property, null);
  1855. var _result3 = _object2 + "." + _property2;
  1856. markNode(expression, optionalChains, _result3);
  1857. return _result3;
  1858. } else {
  1859. throw new Error("Unsupported node type: " + node.type);
  1860. }
  1861. }
  1862. function getNodeWithoutReactNamespace(node, options) {
  1863. if (node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'React' && node.property.type === 'Identifier' && !node.computed) {
  1864. return node.property;
  1865. }
  1866. return node;
  1867. } // What's the index of callback that needs to be analyzed for a given Hook?
  1868. // -1 if it's not a Hook we care about (e.g. useState).
  1869. // 0 for useEffect/useMemo/useCallback(fn).
  1870. // 1 for useImperativeHandle(ref, fn).
  1871. // For additionally configured Hooks, assume that they're like useEffect (0).
  1872. function getReactiveHookCallbackIndex(calleeNode, options) {
  1873. var node = getNodeWithoutReactNamespace(calleeNode);
  1874. if (node.type !== 'Identifier') {
  1875. return -1;
  1876. }
  1877. switch (node.name) {
  1878. case 'useEffect':
  1879. case 'useLayoutEffect':
  1880. case 'useCallback':
  1881. case 'useMemo':
  1882. // useEffect(fn)
  1883. return 0;
  1884. case 'useImperativeHandle':
  1885. // useImperativeHandle(ref, fn)
  1886. return 1;
  1887. default:
  1888. if (node === calleeNode && options && options.additionalHooks) {
  1889. // Allow the user to provide a regular expression which enables the lint to
  1890. // target custom reactive hooks.
  1891. var name;
  1892. try {
  1893. name = analyzePropertyChain(node, null);
  1894. } catch (error) {
  1895. if (/Unsupported node type/.test(error.message)) {
  1896. return 0;
  1897. } else {
  1898. throw error;
  1899. }
  1900. }
  1901. return options.additionalHooks.test(name) ? 0 : -1;
  1902. } else {
  1903. return -1;
  1904. }
  1905. }
  1906. }
  1907. /**
  1908. * ESLint won't assign node.parent to references from context.getScope()
  1909. *
  1910. * So instead we search for the node from an ancestor assigning node.parent
  1911. * as we go. This mutates the AST.
  1912. *
  1913. * This traversal is:
  1914. * - optimized by only searching nodes with a range surrounding our target node
  1915. * - agnostic to AST node types, it looks for `{ type: string, ... }`
  1916. */
  1917. function fastFindReferenceWithParent(start, target) {
  1918. var queue = [start];
  1919. var item = null;
  1920. while (queue.length) {
  1921. item = queue.shift();
  1922. if (isSameIdentifier(item, target)) {
  1923. return item;
  1924. }
  1925. if (!isAncestorNodeOf(item, target)) {
  1926. continue;
  1927. }
  1928. for (var _i4 = 0, _Object$entries = Object.entries(item); _i4 < _Object$entries.length; _i4++) {
  1929. var _Object$entries$_i = _Object$entries[_i4],
  1930. key = _Object$entries$_i[0],
  1931. value = _Object$entries$_i[1];
  1932. if (key === 'parent') {
  1933. continue;
  1934. }
  1935. if (isNodeLike(value)) {
  1936. value.parent = item;
  1937. queue.push(value);
  1938. } else if (Array.isArray(value)) {
  1939. value.forEach(function (val) {
  1940. if (isNodeLike(val)) {
  1941. val.parent = item;
  1942. queue.push(val);
  1943. }
  1944. });
  1945. }
  1946. }
  1947. }
  1948. return null;
  1949. }
  1950. function joinEnglish(arr) {
  1951. var s = '';
  1952. for (var i = 0; i < arr.length; i++) {
  1953. s += arr[i];
  1954. if (i === 0 && arr.length === 2) {
  1955. s += ' and ';
  1956. } else if (i === arr.length - 2 && arr.length > 2) {
  1957. s += ', and ';
  1958. } else if (i < arr.length - 1) {
  1959. s += ', ';
  1960. }
  1961. }
  1962. return s;
  1963. }
  1964. function isNodeLike(val) {
  1965. return typeof val === 'object' && val !== null && !Array.isArray(val) && typeof val.type === 'string';
  1966. }
  1967. function isSameIdentifier(a, b) {
  1968. return (a.type === 'Identifier' || a.type === 'JSXIdentifier') && a.type === b.type && a.name === b.name && a.range[0] === b.range[0] && a.range[1] === b.range[1];
  1969. }
  1970. function isAncestorNodeOf(a, b) {
  1971. return a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
  1972. }
  1973. var configs = {
  1974. recommended: {
  1975. plugins: ['react-hooks'],
  1976. rules: {
  1977. 'react-hooks/rules-of-hooks': 'error',
  1978. 'react-hooks/exhaustive-deps': 'warn'
  1979. }
  1980. }
  1981. };
  1982. var rules = {
  1983. 'rules-of-hooks': RulesOfHooks,
  1984. 'exhaustive-deps': ExhaustiveDeps
  1985. };
  1986. exports.configs = configs;
  1987. exports.rules = rules;
  1988. })();
  1989. }