index.mjs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579
  1. import { getKeys, KEYS } from 'eslint-visitor-keys';
  2. /** @typedef {import("eslint").Scope.Scope} Scope */
  3. /** @typedef {import("estree").Node} Node */
  4. /**
  5. * Get the innermost scope which contains a given location.
  6. * @param {Scope} initialScope The initial scope to search.
  7. * @param {Node} node The location to search.
  8. * @returns {Scope} The innermost scope.
  9. */
  10. function getInnermostScope(initialScope, node) {
  11. const location = /** @type {[number, number]} */ (node.range)[0];
  12. let scope = initialScope;
  13. let found = false;
  14. do {
  15. found = false;
  16. for (const childScope of scope.childScopes) {
  17. const range = /** @type {[number, number]} */ (
  18. childScope.block.range
  19. );
  20. if (range[0] <= location && location < range[1]) {
  21. scope = childScope;
  22. found = true;
  23. break
  24. }
  25. }
  26. } while (found)
  27. return scope
  28. }
  29. /** @typedef {import("eslint").Scope.Scope} Scope */
  30. /** @typedef {import("eslint").Scope.Variable} Variable */
  31. /** @typedef {import("estree").Identifier} Identifier */
  32. /**
  33. * Find the variable of a given name.
  34. * @param {Scope} initialScope The scope to start finding.
  35. * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  36. * @returns {Variable|null} The found variable or null.
  37. */
  38. function findVariable(initialScope, nameOrNode) {
  39. let name = "";
  40. /** @type {Scope|null} */
  41. let scope = initialScope;
  42. if (typeof nameOrNode === "string") {
  43. name = nameOrNode;
  44. } else {
  45. name = nameOrNode.name;
  46. scope = getInnermostScope(scope, nameOrNode);
  47. }
  48. while (scope != null) {
  49. const variable = scope.set.get(name);
  50. if (variable != null) {
  51. return variable
  52. }
  53. scope = scope.upper;
  54. }
  55. return null
  56. }
  57. /** @typedef {import("eslint").AST.Token} Token */
  58. /** @typedef {import("estree").Comment} Comment */
  59. /** @typedef {import("./types.mjs").ArrowToken} ArrowToken */
  60. /** @typedef {import("./types.mjs").CommaToken} CommaToken */
  61. /** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */
  62. /** @typedef {import("./types.mjs").ColonToken} ColonToken */
  63. /** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */
  64. /** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */
  65. /** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */
  66. /** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */
  67. /** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */
  68. /** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */
  69. /**
  70. * @template {string} Value
  71. * @typedef {import("./types.mjs").PunctuatorToken<Value>} PunctuatorToken
  72. */
  73. /** @typedef {Comment | Token} CommentOrToken */
  74. /**
  75. * Creates the negate function of the given function.
  76. * @param {function(CommentOrToken):boolean} f - The function to negate.
  77. * @returns {function(CommentOrToken):boolean} Negated function.
  78. */
  79. function negate(f) {
  80. return (token) => !f(token)
  81. }
  82. /**
  83. * Checks if the given token is a PunctuatorToken with the given value
  84. * @template {string} Value
  85. * @param {CommentOrToken} token - The token to check.
  86. * @param {Value} value - The value to check.
  87. * @returns {token is PunctuatorToken<Value>} `true` if the token is a PunctuatorToken with the given value.
  88. */
  89. function isPunctuatorTokenWithValue(token, value) {
  90. return token.type === "Punctuator" && token.value === value
  91. }
  92. /**
  93. * Checks if the given token is an arrow token or not.
  94. * @param {CommentOrToken} token - The token to check.
  95. * @returns {token is ArrowToken} `true` if the token is an arrow token.
  96. */
  97. function isArrowToken(token) {
  98. return isPunctuatorTokenWithValue(token, "=>")
  99. }
  100. /**
  101. * Checks if the given token is a comma token or not.
  102. * @param {CommentOrToken} token - The token to check.
  103. * @returns {token is CommaToken} `true` if the token is a comma token.
  104. */
  105. function isCommaToken(token) {
  106. return isPunctuatorTokenWithValue(token, ",")
  107. }
  108. /**
  109. * Checks if the given token is a semicolon token or not.
  110. * @param {CommentOrToken} token - The token to check.
  111. * @returns {token is SemicolonToken} `true` if the token is a semicolon token.
  112. */
  113. function isSemicolonToken(token) {
  114. return isPunctuatorTokenWithValue(token, ";")
  115. }
  116. /**
  117. * Checks if the given token is a colon token or not.
  118. * @param {CommentOrToken} token - The token to check.
  119. * @returns {token is ColonToken} `true` if the token is a colon token.
  120. */
  121. function isColonToken(token) {
  122. return isPunctuatorTokenWithValue(token, ":")
  123. }
  124. /**
  125. * Checks if the given token is an opening parenthesis token or not.
  126. * @param {CommentOrToken} token - The token to check.
  127. * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.
  128. */
  129. function isOpeningParenToken(token) {
  130. return isPunctuatorTokenWithValue(token, "(")
  131. }
  132. /**
  133. * Checks if the given token is a closing parenthesis token or not.
  134. * @param {CommentOrToken} token - The token to check.
  135. * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.
  136. */
  137. function isClosingParenToken(token) {
  138. return isPunctuatorTokenWithValue(token, ")")
  139. }
  140. /**
  141. * Checks if the given token is an opening square bracket token or not.
  142. * @param {CommentOrToken} token - The token to check.
  143. * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.
  144. */
  145. function isOpeningBracketToken(token) {
  146. return isPunctuatorTokenWithValue(token, "[")
  147. }
  148. /**
  149. * Checks if the given token is a closing square bracket token or not.
  150. * @param {CommentOrToken} token - The token to check.
  151. * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.
  152. */
  153. function isClosingBracketToken(token) {
  154. return isPunctuatorTokenWithValue(token, "]")
  155. }
  156. /**
  157. * Checks if the given token is an opening brace token or not.
  158. * @param {CommentOrToken} token - The token to check.
  159. * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.
  160. */
  161. function isOpeningBraceToken(token) {
  162. return isPunctuatorTokenWithValue(token, "{")
  163. }
  164. /**
  165. * Checks if the given token is a closing brace token or not.
  166. * @param {CommentOrToken} token - The token to check.
  167. * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.
  168. */
  169. function isClosingBraceToken(token) {
  170. return isPunctuatorTokenWithValue(token, "}")
  171. }
  172. /**
  173. * Checks if the given token is a comment token or not.
  174. * @param {CommentOrToken} token - The token to check.
  175. * @returns {token is Comment} `true` if the token is a comment token.
  176. */
  177. function isCommentToken(token) {
  178. return ["Block", "Line", "Shebang"].includes(token.type)
  179. }
  180. const isNotArrowToken = negate(isArrowToken);
  181. const isNotCommaToken = negate(isCommaToken);
  182. const isNotSemicolonToken = negate(isSemicolonToken);
  183. const isNotColonToken = negate(isColonToken);
  184. const isNotOpeningParenToken = negate(isOpeningParenToken);
  185. const isNotClosingParenToken = negate(isClosingParenToken);
  186. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  187. const isNotClosingBracketToken = negate(isClosingBracketToken);
  188. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  189. const isNotClosingBraceToken = negate(isClosingBraceToken);
  190. const isNotCommentToken = negate(isCommentToken);
  191. /** @typedef {import("eslint").Rule.Node} RuleNode */
  192. /** @typedef {import("eslint").SourceCode} SourceCode */
  193. /** @typedef {import("eslint").AST.Token} Token */
  194. /** @typedef {import("estree").Function} FunctionNode */
  195. /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
  196. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  197. /** @typedef {import("estree").SourceLocation} SourceLocation */
  198. /** @typedef {import("estree").Position} Position */
  199. /**
  200. * Get the `(` token of the given function node.
  201. * @param {FunctionExpression | FunctionDeclaration} node - The function node to get.
  202. * @param {SourceCode} sourceCode - The source code object to get tokens.
  203. * @returns {Token} `(` token.
  204. */
  205. function getOpeningParenOfParams(node, sourceCode) {
  206. return node.id
  207. ? /** @type {Token} */ (
  208. sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  209. )
  210. : /** @type {Token} */ (
  211. sourceCode.getFirstToken(node, isOpeningParenToken)
  212. )
  213. }
  214. /**
  215. * Get the location of the given function node for reporting.
  216. * @param {FunctionNode} node - The function node to get.
  217. * @param {SourceCode} sourceCode - The source code object to get tokens.
  218. * @returns {SourceLocation|null} The location of the function node for reporting.
  219. */
  220. function getFunctionHeadLocation(node, sourceCode) {
  221. const parent = /** @type {RuleNode} */ (node).parent;
  222. /** @type {Position|null} */
  223. let start = null;
  224. /** @type {Position|null} */
  225. let end = null;
  226. if (node.type === "ArrowFunctionExpression") {
  227. const arrowToken = /** @type {Token} */ (
  228. sourceCode.getTokenBefore(node.body, isArrowToken)
  229. );
  230. start = arrowToken.loc.start;
  231. end = arrowToken.loc.end;
  232. } else if (
  233. parent &&
  234. (parent.type === "Property" ||
  235. parent.type === "MethodDefinition" ||
  236. parent.type === "PropertyDefinition")
  237. ) {
  238. start = /** @type {SourceLocation} */ (parent.loc).start;
  239. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  240. } else {
  241. start = /** @type {SourceLocation} */ (node.loc).start;
  242. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  243. }
  244. return {
  245. start: { ...start },
  246. end: { ...end },
  247. }
  248. }
  249. /* globals globalThis, global, self, window */
  250. /** @typedef {import("./types.mjs").StaticValue} StaticValue */
  251. /** @typedef {import("eslint").Scope.Scope} Scope */
  252. /** @typedef {import("eslint").Scope.Variable} Variable */
  253. /** @typedef {import("estree").Node} Node */
  254. /** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
  255. /** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */
  256. /** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */
  257. /** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */
  258. /** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */
  259. /** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */
  260. /** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */
  261. const globalObject =
  262. typeof globalThis !== "undefined"
  263. ? globalThis
  264. : // @ts-ignore
  265. typeof self !== "undefined"
  266. ? // @ts-ignore
  267. self
  268. : // @ts-ignore
  269. typeof window !== "undefined"
  270. ? // @ts-ignore
  271. window
  272. : typeof global !== "undefined"
  273. ? global
  274. : {};
  275. const builtinNames = Object.freeze(
  276. new Set([
  277. "Array",
  278. "ArrayBuffer",
  279. "BigInt",
  280. "BigInt64Array",
  281. "BigUint64Array",
  282. "Boolean",
  283. "DataView",
  284. "Date",
  285. "decodeURI",
  286. "decodeURIComponent",
  287. "encodeURI",
  288. "encodeURIComponent",
  289. "escape",
  290. "Float32Array",
  291. "Float64Array",
  292. "Function",
  293. "Infinity",
  294. "Int16Array",
  295. "Int32Array",
  296. "Int8Array",
  297. "isFinite",
  298. "isNaN",
  299. "isPrototypeOf",
  300. "JSON",
  301. "Map",
  302. "Math",
  303. "NaN",
  304. "Number",
  305. "Object",
  306. "parseFloat",
  307. "parseInt",
  308. "Promise",
  309. "Proxy",
  310. "Reflect",
  311. "RegExp",
  312. "Set",
  313. "String",
  314. "Symbol",
  315. "Uint16Array",
  316. "Uint32Array",
  317. "Uint8Array",
  318. "Uint8ClampedArray",
  319. "undefined",
  320. "unescape",
  321. "WeakMap",
  322. "WeakSet",
  323. ]),
  324. );
  325. const callAllowed = new Set(
  326. [
  327. Array.isArray,
  328. Array.of,
  329. Array.prototype.at,
  330. Array.prototype.concat,
  331. Array.prototype.entries,
  332. Array.prototype.every,
  333. Array.prototype.filter,
  334. Array.prototype.find,
  335. Array.prototype.findIndex,
  336. Array.prototype.flat,
  337. Array.prototype.includes,
  338. Array.prototype.indexOf,
  339. Array.prototype.join,
  340. Array.prototype.keys,
  341. Array.prototype.lastIndexOf,
  342. Array.prototype.slice,
  343. Array.prototype.some,
  344. Array.prototype.toString,
  345. Array.prototype.values,
  346. typeof BigInt === "function" ? BigInt : undefined,
  347. Boolean,
  348. Date,
  349. Date.parse,
  350. decodeURI,
  351. decodeURIComponent,
  352. encodeURI,
  353. encodeURIComponent,
  354. escape,
  355. isFinite,
  356. isNaN,
  357. // @ts-ignore
  358. isPrototypeOf,
  359. Map,
  360. Map.prototype.entries,
  361. Map.prototype.get,
  362. Map.prototype.has,
  363. Map.prototype.keys,
  364. Map.prototype.values,
  365. .../** @type {(keyof typeof Math)[]} */ (
  366. Object.getOwnPropertyNames(Math)
  367. )
  368. .filter((k) => k !== "random")
  369. .map((k) => Math[k])
  370. .filter((f) => typeof f === "function"),
  371. Number,
  372. Number.isFinite,
  373. Number.isNaN,
  374. Number.parseFloat,
  375. Number.parseInt,
  376. Number.prototype.toExponential,
  377. Number.prototype.toFixed,
  378. Number.prototype.toPrecision,
  379. Number.prototype.toString,
  380. Object,
  381. Object.entries,
  382. Object.is,
  383. Object.isExtensible,
  384. Object.isFrozen,
  385. Object.isSealed,
  386. Object.keys,
  387. Object.values,
  388. parseFloat,
  389. parseInt,
  390. RegExp,
  391. Set,
  392. Set.prototype.entries,
  393. Set.prototype.has,
  394. Set.prototype.keys,
  395. Set.prototype.values,
  396. String,
  397. String.fromCharCode,
  398. String.fromCodePoint,
  399. String.raw,
  400. String.prototype.at,
  401. String.prototype.charAt,
  402. String.prototype.charCodeAt,
  403. String.prototype.codePointAt,
  404. String.prototype.concat,
  405. String.prototype.endsWith,
  406. String.prototype.includes,
  407. String.prototype.indexOf,
  408. String.prototype.lastIndexOf,
  409. String.prototype.normalize,
  410. String.prototype.padEnd,
  411. String.prototype.padStart,
  412. String.prototype.slice,
  413. String.prototype.startsWith,
  414. String.prototype.substr,
  415. String.prototype.substring,
  416. String.prototype.toLowerCase,
  417. String.prototype.toString,
  418. String.prototype.toUpperCase,
  419. String.prototype.trim,
  420. String.prototype.trimEnd,
  421. String.prototype.trimLeft,
  422. String.prototype.trimRight,
  423. String.prototype.trimStart,
  424. Symbol.for,
  425. Symbol.keyFor,
  426. unescape,
  427. ].filter((f) => typeof f === "function"),
  428. );
  429. const callPassThrough = new Set([
  430. Object.freeze,
  431. Object.preventExtensions,
  432. Object.seal,
  433. ]);
  434. /** @type {ReadonlyArray<readonly [Function, ReadonlySet<string>]>} */
  435. const getterAllowed = [
  436. [Map, new Set(["size"])],
  437. [
  438. RegExp,
  439. new Set([
  440. "dotAll",
  441. "flags",
  442. "global",
  443. "hasIndices",
  444. "ignoreCase",
  445. "multiline",
  446. "source",
  447. "sticky",
  448. "unicode",
  449. ]),
  450. ],
  451. [Set, new Set(["size"])],
  452. ];
  453. /**
  454. * Get the property descriptor.
  455. * @param {object} object The object to get.
  456. * @param {string|number|symbol} name The property name to get.
  457. */
  458. function getPropertyDescriptor(object, name) {
  459. let x = object;
  460. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  461. const d = Object.getOwnPropertyDescriptor(x, name);
  462. if (d) {
  463. return d
  464. }
  465. x = Object.getPrototypeOf(x);
  466. }
  467. return null
  468. }
  469. /**
  470. * Check if a property is getter or not.
  471. * @param {object} object The object to check.
  472. * @param {string|number|symbol} name The property name to check.
  473. */
  474. function isGetter(object, name) {
  475. const d = getPropertyDescriptor(object, name);
  476. return d != null && d.get != null
  477. }
  478. /**
  479. * Get the element values of a given node list.
  480. * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.
  481. * @param {Scope|undefined|null} initialScope The initial scope to find variables.
  482. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  483. */
  484. function getElementValues(nodeList, initialScope) {
  485. const valueList = [];
  486. for (let i = 0; i < nodeList.length; ++i) {
  487. const elementNode = nodeList[i];
  488. if (elementNode == null) {
  489. valueList.length = i + 1;
  490. } else if (elementNode.type === "SpreadElement") {
  491. const argument = getStaticValueR(elementNode.argument, initialScope);
  492. if (argument == null) {
  493. return null
  494. }
  495. valueList.push(.../** @type {Iterable<any>} */ (argument.value));
  496. } else {
  497. const element = getStaticValueR(elementNode, initialScope);
  498. if (element == null) {
  499. return null
  500. }
  501. valueList.push(element.value);
  502. }
  503. }
  504. return valueList
  505. }
  506. /**
  507. * Checks if a variable is a built-in global.
  508. * @param {Variable|null} variable The variable to check.
  509. * @returns {variable is Variable & {defs:[]}}
  510. */
  511. function isBuiltinGlobal(variable) {
  512. return (
  513. variable != null &&
  514. variable.defs.length === 0 &&
  515. builtinNames.has(variable.name) &&
  516. variable.name in globalObject
  517. )
  518. }
  519. /**
  520. * Checks if a variable can be considered as a constant.
  521. * @param {Variable} variable
  522. * @returns {variable is Variable & {defs: [import("eslint").Scope.Definition & { type: "Variable" }]}} True if the variable can be considered as a constant.
  523. */
  524. function canBeConsideredConst(variable) {
  525. if (variable.defs.length !== 1) {
  526. return false
  527. }
  528. const def = variable.defs[0];
  529. return Boolean(
  530. def.parent &&
  531. def.type === "Variable" &&
  532. (def.parent.kind === "const" || isEffectivelyConst(variable)),
  533. )
  534. }
  535. /**
  536. * Returns whether the given variable is never written to after initialization.
  537. * @param {Variable} variable
  538. * @returns {boolean}
  539. */
  540. function isEffectivelyConst(variable) {
  541. const refs = variable.references;
  542. const inits = refs.filter((r) => r.init).length;
  543. const reads = refs.filter((r) => r.isReadOnly()).length;
  544. if (inits === 1 && reads + inits === refs.length) {
  545. // there is only one init and all other references only read
  546. return true
  547. }
  548. return false
  549. }
  550. /**
  551. * Checks if a variable has mutation in its property.
  552. * @param {Variable} variable The variable to check.
  553. * @param {Scope|null} initialScope The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  554. * @returns {boolean} True if the variable has mutation in its property.
  555. */
  556. function hasMutationInProperty(variable, initialScope) {
  557. for (const ref of variable.references) {
  558. let node = /** @type {TSESTreeNode} */ (ref.identifier);
  559. while (node && node.parent && node.parent.type === "MemberExpression") {
  560. node = node.parent;
  561. }
  562. if (!node || !node.parent) {
  563. continue
  564. }
  565. if (
  566. (node.parent.type === "AssignmentExpression" &&
  567. node.parent.left === node) ||
  568. (node.parent.type === "UpdateExpression" &&
  569. node.parent.argument === node)
  570. ) {
  571. // This is a mutation.
  572. return true
  573. }
  574. if (
  575. node.parent.type === "CallExpression" &&
  576. node.parent.callee === node &&
  577. node.type === "MemberExpression"
  578. ) {
  579. const methodName = getStaticPropertyNameValue(node, initialScope);
  580. if (isNameOfMutationArrayMethod(methodName)) {
  581. // This is a mutation.
  582. return true
  583. }
  584. }
  585. }
  586. return false
  587. /**
  588. * Checks if a method name is one of the mutation array methods.
  589. * @param {StaticValue|null} methodName The method name to check.
  590. * @returns {boolean} True if the method name is a mutation array method.
  591. */
  592. function isNameOfMutationArrayMethod(methodName) {
  593. if (methodName == null || methodName.value == null) {
  594. return false
  595. }
  596. const name = methodName.value;
  597. return (
  598. name === "copyWithin" ||
  599. name === "fill" ||
  600. name === "pop" ||
  601. name === "push" ||
  602. name === "reverse" ||
  603. name === "shift" ||
  604. name === "sort" ||
  605. name === "splice" ||
  606. name === "unshift"
  607. )
  608. }
  609. }
  610. /**
  611. * @template {TSESTreeNodeTypes} T
  612. * @callback VisitorCallback
  613. * @param {TSESTreeNode & { type: T }} node
  614. * @param {Scope|undefined|null} initialScope
  615. * @returns {StaticValue | null}
  616. */
  617. /**
  618. * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback<K> } } Operations
  619. */
  620. /**
  621. * @type {Operations}
  622. */
  623. const operations = Object.freeze({
  624. ArrayExpression(node, initialScope) {
  625. const elements = getElementValues(node.elements, initialScope);
  626. return elements != null ? { value: elements } : null
  627. },
  628. AssignmentExpression(node, initialScope) {
  629. if (node.operator === "=") {
  630. return getStaticValueR(node.right, initialScope)
  631. }
  632. return null
  633. },
  634. //eslint-disable-next-line complexity
  635. BinaryExpression(node, initialScope) {
  636. if (node.operator === "in" || node.operator === "instanceof") {
  637. // Not supported.
  638. return null
  639. }
  640. const left = getStaticValueR(node.left, initialScope);
  641. const right = getStaticValueR(node.right, initialScope);
  642. if (left != null && right != null) {
  643. switch (node.operator) {
  644. case "==":
  645. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  646. case "!=":
  647. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  648. case "===":
  649. return { value: left.value === right.value }
  650. case "!==":
  651. return { value: left.value !== right.value }
  652. case "<":
  653. return {
  654. value:
  655. /** @type {any} */ (left.value) <
  656. /** @type {any} */ (right.value),
  657. }
  658. case "<=":
  659. return {
  660. value:
  661. /** @type {any} */ (left.value) <=
  662. /** @type {any} */ (right.value),
  663. }
  664. case ">":
  665. return {
  666. value:
  667. /** @type {any} */ (left.value) >
  668. /** @type {any} */ (right.value),
  669. }
  670. case ">=":
  671. return {
  672. value:
  673. /** @type {any} */ (left.value) >=
  674. /** @type {any} */ (right.value),
  675. }
  676. case "<<":
  677. return {
  678. value:
  679. /** @type {any} */ (left.value) <<
  680. /** @type {any} */ (right.value),
  681. }
  682. case ">>":
  683. return {
  684. value:
  685. /** @type {any} */ (left.value) >>
  686. /** @type {any} */ (right.value),
  687. }
  688. case ">>>":
  689. return {
  690. value:
  691. /** @type {any} */ (left.value) >>>
  692. /** @type {any} */ (right.value),
  693. }
  694. case "+":
  695. return {
  696. value:
  697. /** @type {any} */ (left.value) +
  698. /** @type {any} */ (right.value),
  699. }
  700. case "-":
  701. return {
  702. value:
  703. /** @type {any} */ (left.value) -
  704. /** @type {any} */ (right.value),
  705. }
  706. case "*":
  707. return {
  708. value:
  709. /** @type {any} */ (left.value) *
  710. /** @type {any} */ (right.value),
  711. }
  712. case "/":
  713. return {
  714. value:
  715. /** @type {any} */ (left.value) /
  716. /** @type {any} */ (right.value),
  717. }
  718. case "%":
  719. return {
  720. value:
  721. /** @type {any} */ (left.value) %
  722. /** @type {any} */ (right.value),
  723. }
  724. case "**":
  725. return {
  726. value:
  727. /** @type {any} */ (left.value) **
  728. /** @type {any} */ (right.value),
  729. }
  730. case "|":
  731. return {
  732. value:
  733. /** @type {any} */ (left.value) |
  734. /** @type {any} */ (right.value),
  735. }
  736. case "^":
  737. return {
  738. value:
  739. /** @type {any} */ (left.value) ^
  740. /** @type {any} */ (right.value),
  741. }
  742. case "&":
  743. return {
  744. value:
  745. /** @type {any} */ (left.value) &
  746. /** @type {any} */ (right.value),
  747. }
  748. // no default
  749. }
  750. }
  751. return null
  752. },
  753. CallExpression(node, initialScope) {
  754. const calleeNode = node.callee;
  755. const args = getElementValues(node.arguments, initialScope);
  756. if (args != null) {
  757. if (calleeNode.type === "MemberExpression") {
  758. if (calleeNode.property.type === "PrivateIdentifier") {
  759. return null
  760. }
  761. const object = getStaticValueR(calleeNode.object, initialScope);
  762. if (object != null) {
  763. if (
  764. object.value == null &&
  765. (object.optional || node.optional)
  766. ) {
  767. return { value: undefined, optional: true }
  768. }
  769. const property = getStaticPropertyNameValue(
  770. calleeNode,
  771. initialScope,
  772. );
  773. if (property != null) {
  774. const receiver =
  775. /** @type {Record<PropertyKey, (...args: any[]) => any>} */ (
  776. object.value
  777. );
  778. const methodName = /** @type {PropertyKey} */ (
  779. property.value
  780. );
  781. if (callAllowed.has(receiver[methodName])) {
  782. return {
  783. value: receiver[methodName](...args),
  784. }
  785. }
  786. if (callPassThrough.has(receiver[methodName])) {
  787. return { value: args[0] }
  788. }
  789. }
  790. }
  791. } else {
  792. const callee = getStaticValueR(calleeNode, initialScope);
  793. if (callee != null) {
  794. if (callee.value == null && node.optional) {
  795. return { value: undefined, optional: true }
  796. }
  797. const func = /** @type {(...args: any[]) => any} */ (
  798. callee.value
  799. );
  800. if (callAllowed.has(func)) {
  801. return { value: func(...args) }
  802. }
  803. if (callPassThrough.has(func)) {
  804. return { value: args[0] }
  805. }
  806. }
  807. }
  808. }
  809. return null
  810. },
  811. ConditionalExpression(node, initialScope) {
  812. const test = getStaticValueR(node.test, initialScope);
  813. if (test != null) {
  814. return test.value
  815. ? getStaticValueR(node.consequent, initialScope)
  816. : getStaticValueR(node.alternate, initialScope)
  817. }
  818. return null
  819. },
  820. ExpressionStatement(node, initialScope) {
  821. return getStaticValueR(node.expression, initialScope)
  822. },
  823. Identifier(node, initialScope) {
  824. if (initialScope != null) {
  825. const variable = findVariable(initialScope, node);
  826. if (variable != null) {
  827. // Built-in globals.
  828. if (isBuiltinGlobal(variable)) {
  829. return { value: globalObject[variable.name] }
  830. }
  831. // Constants.
  832. if (canBeConsideredConst(variable)) {
  833. const def = variable.defs[0];
  834. if (
  835. // TODO(mysticatea): don't support destructuring here.
  836. def.node.id.type === "Identifier"
  837. ) {
  838. const init = getStaticValueR(
  839. def.node.init,
  840. initialScope,
  841. );
  842. if (
  843. init &&
  844. typeof init.value === "object" &&
  845. init.value !== null
  846. ) {
  847. if (hasMutationInProperty(variable, initialScope)) {
  848. // This variable has mutation in its property.
  849. return null
  850. }
  851. }
  852. return init
  853. }
  854. }
  855. }
  856. }
  857. return null
  858. },
  859. Literal(node) {
  860. const literal =
  861. /** @type {Partial<Literal> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
  862. node
  863. );
  864. //istanbul ignore if : this is implementation-specific behavior.
  865. if (
  866. (literal.regex != null || literal.bigint != null) &&
  867. literal.value == null
  868. ) {
  869. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  870. return null
  871. }
  872. return { value: literal.value }
  873. },
  874. LogicalExpression(node, initialScope) {
  875. const left = getStaticValueR(node.left, initialScope);
  876. if (left != null) {
  877. if (
  878. (node.operator === "||" && Boolean(left.value) === true) ||
  879. (node.operator === "&&" && Boolean(left.value) === false) ||
  880. (node.operator === "??" && left.value != null)
  881. ) {
  882. return left
  883. }
  884. const right = getStaticValueR(node.right, initialScope);
  885. if (right != null) {
  886. return right
  887. }
  888. }
  889. return null
  890. },
  891. MemberExpression(node, initialScope) {
  892. if (node.property.type === "PrivateIdentifier") {
  893. return null
  894. }
  895. const object = getStaticValueR(node.object, initialScope);
  896. if (object != null) {
  897. if (object.value == null && (object.optional || node.optional)) {
  898. return { value: undefined, optional: true }
  899. }
  900. const property = getStaticPropertyNameValue(node, initialScope);
  901. if (property != null) {
  902. if (
  903. !isGetter(
  904. /** @type {object} */ (object.value),
  905. /** @type {PropertyKey} */ (property.value),
  906. )
  907. ) {
  908. return {
  909. value: /** @type {Record<PropertyKey, unknown>} */ (
  910. object.value
  911. )[/** @type {PropertyKey} */ (property.value)],
  912. }
  913. }
  914. for (const [classFn, allowed] of getterAllowed) {
  915. if (
  916. object.value instanceof classFn &&
  917. allowed.has(/** @type {string} */ (property.value))
  918. ) {
  919. return {
  920. value: /** @type {Record<PropertyKey, unknown>} */ (
  921. object.value
  922. )[/** @type {PropertyKey} */ (property.value)],
  923. }
  924. }
  925. }
  926. }
  927. }
  928. return null
  929. },
  930. ChainExpression(node, initialScope) {
  931. const expression = getStaticValueR(node.expression, initialScope);
  932. if (expression != null) {
  933. return { value: expression.value }
  934. }
  935. return null
  936. },
  937. NewExpression(node, initialScope) {
  938. const callee = getStaticValueR(node.callee, initialScope);
  939. const args = getElementValues(node.arguments, initialScope);
  940. if (callee != null && args != null) {
  941. const Func = /** @type {new (...args: any[]) => any} */ (
  942. callee.value
  943. );
  944. if (callAllowed.has(Func)) {
  945. return { value: new Func(...args) }
  946. }
  947. }
  948. return null
  949. },
  950. ObjectExpression(node, initialScope) {
  951. /** @type {Record<PropertyKey, unknown>} */
  952. const object = {};
  953. for (const propertyNode of node.properties) {
  954. if (propertyNode.type === "Property") {
  955. if (propertyNode.kind !== "init") {
  956. return null
  957. }
  958. const key = getStaticPropertyNameValue(
  959. propertyNode,
  960. initialScope,
  961. );
  962. const value = getStaticValueR(propertyNode.value, initialScope);
  963. if (key == null || value == null) {
  964. return null
  965. }
  966. object[/** @type {PropertyKey} */ (key.value)] = value.value;
  967. } else if (
  968. propertyNode.type === "SpreadElement" ||
  969. // @ts-expect-error -- Backward compatibility
  970. propertyNode.type === "ExperimentalSpreadProperty"
  971. ) {
  972. const argument = getStaticValueR(
  973. propertyNode.argument,
  974. initialScope,
  975. );
  976. if (argument == null) {
  977. return null
  978. }
  979. Object.assign(object, argument.value);
  980. } else {
  981. return null
  982. }
  983. }
  984. return { value: object }
  985. },
  986. SequenceExpression(node, initialScope) {
  987. const last = node.expressions[node.expressions.length - 1];
  988. return getStaticValueR(last, initialScope)
  989. },
  990. TaggedTemplateExpression(node, initialScope) {
  991. const tag = getStaticValueR(node.tag, initialScope);
  992. const expressions = getElementValues(
  993. node.quasi.expressions,
  994. initialScope,
  995. );
  996. if (tag != null && expressions != null) {
  997. const func = /** @type {(...args: any[]) => any} */ (tag.value);
  998. /** @type {any[] & { raw?: string[] }} */
  999. const strings = node.quasi.quasis.map((q) => q.value.cooked);
  1000. strings.raw = node.quasi.quasis.map((q) => q.value.raw);
  1001. if (func === String.raw) {
  1002. return { value: func(strings, ...expressions) }
  1003. }
  1004. }
  1005. return null
  1006. },
  1007. TemplateLiteral(node, initialScope) {
  1008. const expressions = getElementValues(node.expressions, initialScope);
  1009. if (expressions != null) {
  1010. let value = node.quasis[0].value.cooked;
  1011. for (let i = 0; i < expressions.length; ++i) {
  1012. value += expressions[i];
  1013. value += /** @type {string} */ (node.quasis[i + 1].value.cooked);
  1014. }
  1015. return { value }
  1016. }
  1017. return null
  1018. },
  1019. UnaryExpression(node, initialScope) {
  1020. if (node.operator === "delete") {
  1021. // Not supported.
  1022. return null
  1023. }
  1024. if (node.operator === "void") {
  1025. return { value: undefined }
  1026. }
  1027. const arg = getStaticValueR(node.argument, initialScope);
  1028. if (arg != null) {
  1029. switch (node.operator) {
  1030. case "-":
  1031. return { value: -(/** @type {any} */ (arg.value)) }
  1032. case "+":
  1033. return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion
  1034. case "!":
  1035. return { value: !arg.value }
  1036. case "~":
  1037. return { value: ~(/** @type {any} */ (arg.value)) }
  1038. case "typeof":
  1039. return { value: typeof arg.value }
  1040. // no default
  1041. }
  1042. }
  1043. return null
  1044. },
  1045. TSAsExpression(node, initialScope) {
  1046. return getStaticValueR(node.expression, initialScope)
  1047. },
  1048. TSSatisfiesExpression(node, initialScope) {
  1049. return getStaticValueR(node.expression, initialScope)
  1050. },
  1051. TSTypeAssertion(node, initialScope) {
  1052. return getStaticValueR(node.expression, initialScope)
  1053. },
  1054. TSNonNullExpression(node, initialScope) {
  1055. return getStaticValueR(node.expression, initialScope)
  1056. },
  1057. TSInstantiationExpression(node, initialScope) {
  1058. return getStaticValueR(node.expression, initialScope)
  1059. },
  1060. });
  1061. /**
  1062. * Get the value of a given node if it's a static value.
  1063. * @param {Node|TSESTreeNode|null|undefined} node The node to get.
  1064. * @param {Scope|undefined|null} initialScope The scope to start finding variable.
  1065. * @returns {StaticValue|null} The static value of the node, or `null`.
  1066. */
  1067. function getStaticValueR(node, initialScope) {
  1068. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  1069. return /** @type {VisitorCallback<any>} */ (operations[node.type])(
  1070. /** @type {TSESTreeNode} */ (node),
  1071. initialScope,
  1072. )
  1073. }
  1074. return null
  1075. }
  1076. /**
  1077. * Get the static value of property name from a MemberExpression node or a Property node.
  1078. * @param {MemberExpression|Property} node The node to get.
  1079. * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  1080. * @returns {StaticValue|null} The static value of the property name of the node, or `null`.
  1081. */
  1082. function getStaticPropertyNameValue(node, initialScope) {
  1083. const nameNode = node.type === "Property" ? node.key : node.property;
  1084. if (node.computed) {
  1085. return getStaticValueR(nameNode, initialScope)
  1086. }
  1087. if (nameNode.type === "Identifier") {
  1088. return { value: nameNode.name }
  1089. }
  1090. if (nameNode.type === "Literal") {
  1091. if (/** @type {Partial<BigIntLiteral>} */ (nameNode).bigint) {
  1092. return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }
  1093. }
  1094. return { value: String(nameNode.value) }
  1095. }
  1096. return null
  1097. }
  1098. /**
  1099. * Get the value of a given node if it's a static value.
  1100. * @param {Node} node The node to get.
  1101. * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
  1102. * @returns {StaticValue | null} The static value of the node, or `null`.
  1103. */
  1104. function getStaticValue(node, initialScope = null) {
  1105. try {
  1106. return getStaticValueR(node, initialScope)
  1107. } catch (_error) {
  1108. return null
  1109. }
  1110. }
  1111. /** @typedef {import("eslint").Scope.Scope} Scope */
  1112. /** @typedef {import("estree").Node} Node */
  1113. /** @typedef {import("estree").RegExpLiteral} RegExpLiteral */
  1114. /** @typedef {import("estree").BigIntLiteral} BigIntLiteral */
  1115. /** @typedef {import("estree").SimpleLiteral} SimpleLiteral */
  1116. /**
  1117. * Get the value of a given node if it's a literal or a template literal.
  1118. * @param {Node} node The node to get.
  1119. * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
  1120. * @returns {string|null} The value of the node, or `null`.
  1121. */
  1122. function getStringIfConstant(node, initialScope = null) {
  1123. // Handle the literals that the platform doesn't support natively.
  1124. if (node && node.type === "Literal" && node.value === null) {
  1125. const literal =
  1126. /** @type {Partial<SimpleLiteral> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
  1127. node
  1128. );
  1129. if (literal.regex) {
  1130. return `/${literal.regex.pattern}/${literal.regex.flags}`
  1131. }
  1132. if (literal.bigint) {
  1133. return literal.bigint
  1134. }
  1135. }
  1136. const evaluated = getStaticValue(node, initialScope);
  1137. if (evaluated) {
  1138. // `String(Symbol.prototype)` throws error
  1139. try {
  1140. return String(evaluated.value)
  1141. } catch {
  1142. // No op
  1143. }
  1144. }
  1145. return null
  1146. }
  1147. /** @typedef {import("eslint").Scope.Scope} Scope */
  1148. /** @typedef {import("estree").MemberExpression} MemberExpression */
  1149. /** @typedef {import("estree").MethodDefinition} MethodDefinition */
  1150. /** @typedef {import("estree").Property} Property */
  1151. /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
  1152. /** @typedef {import("estree").Identifier} Identifier */
  1153. /**
  1154. * Get the property name from a MemberExpression node or a Property node.
  1155. * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.
  1156. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  1157. * @returns {string|null|undefined} The property name of the node.
  1158. */
  1159. function getPropertyName(node, initialScope) {
  1160. switch (node.type) {
  1161. case "MemberExpression":
  1162. if (node.computed) {
  1163. return getStringIfConstant(node.property, initialScope)
  1164. }
  1165. if (node.property.type === "PrivateIdentifier") {
  1166. return null
  1167. }
  1168. return /** @type {Partial<Identifier>} */ (node.property).name
  1169. case "Property":
  1170. case "MethodDefinition":
  1171. case "PropertyDefinition":
  1172. if (node.computed) {
  1173. return getStringIfConstant(node.key, initialScope)
  1174. }
  1175. if (node.key.type === "Literal") {
  1176. return String(node.key.value)
  1177. }
  1178. if (node.key.type === "PrivateIdentifier") {
  1179. return null
  1180. }
  1181. return /** @type {Partial<Identifier>} */ (node.key).name
  1182. }
  1183. return null
  1184. }
  1185. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1186. /** @typedef {import("eslint").SourceCode} SourceCode */
  1187. /** @typedef {import("estree").Function} FunctionNode */
  1188. /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
  1189. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  1190. /** @typedef {import("estree").Identifier} Identifier */
  1191. /**
  1192. * Get the name and kind of the given function node.
  1193. * @param {FunctionNode} node - The function node to get.
  1194. * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
  1195. * @returns {string} The name and kind of the function node.
  1196. */
  1197. // eslint-disable-next-line complexity
  1198. function getFunctionNameWithKind(node, sourceCode) {
  1199. const parent = /** @type {RuleNode} */ (node).parent;
  1200. if (!parent) {
  1201. return ""
  1202. }
  1203. const tokens = [];
  1204. const isObjectMethod = parent.type === "Property" && parent.value === node;
  1205. const isClassMethod =
  1206. parent.type === "MethodDefinition" && parent.value === node;
  1207. const isClassFieldMethod =
  1208. parent.type === "PropertyDefinition" && parent.value === node;
  1209. // Modifiers.
  1210. if (isClassMethod || isClassFieldMethod) {
  1211. if (parent.static) {
  1212. tokens.push("static");
  1213. }
  1214. if (parent.key.type === "PrivateIdentifier") {
  1215. tokens.push("private");
  1216. }
  1217. }
  1218. if (node.async) {
  1219. tokens.push("async");
  1220. }
  1221. if (node.generator) {
  1222. tokens.push("generator");
  1223. }
  1224. // Kinds.
  1225. if (isObjectMethod || isClassMethod) {
  1226. if (parent.kind === "constructor") {
  1227. return "constructor"
  1228. }
  1229. if (parent.kind === "get") {
  1230. tokens.push("getter");
  1231. } else if (parent.kind === "set") {
  1232. tokens.push("setter");
  1233. } else {
  1234. tokens.push("method");
  1235. }
  1236. } else if (isClassFieldMethod) {
  1237. tokens.push("method");
  1238. } else {
  1239. if (node.type === "ArrowFunctionExpression") {
  1240. tokens.push("arrow");
  1241. }
  1242. tokens.push("function");
  1243. }
  1244. // Names.
  1245. if (isObjectMethod || isClassMethod || isClassFieldMethod) {
  1246. if (parent.key.type === "PrivateIdentifier") {
  1247. tokens.push(`#${parent.key.name}`);
  1248. } else {
  1249. const name = getPropertyName(parent);
  1250. if (name) {
  1251. tokens.push(`'${name}'`);
  1252. } else if (sourceCode) {
  1253. const keyText = sourceCode.getText(parent.key);
  1254. if (!keyText.includes("\n")) {
  1255. tokens.push(`[${keyText}]`);
  1256. }
  1257. }
  1258. }
  1259. } else if (hasId(node)) {
  1260. tokens.push(`'${node.id.name}'`);
  1261. } else if (
  1262. parent.type === "VariableDeclarator" &&
  1263. parent.id &&
  1264. parent.id.type === "Identifier"
  1265. ) {
  1266. tokens.push(`'${parent.id.name}'`);
  1267. } else if (
  1268. (parent.type === "AssignmentExpression" ||
  1269. parent.type === "AssignmentPattern") &&
  1270. parent.left &&
  1271. parent.left.type === "Identifier"
  1272. ) {
  1273. tokens.push(`'${parent.left.name}'`);
  1274. } else if (
  1275. parent.type === "ExportDefaultDeclaration" &&
  1276. parent.declaration === node
  1277. ) {
  1278. tokens.push("'default'");
  1279. }
  1280. return tokens.join(" ")
  1281. }
  1282. /**
  1283. * @param {FunctionNode} node
  1284. * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}
  1285. */
  1286. function hasId(node) {
  1287. return Boolean(
  1288. /** @type {Partial<FunctionDeclaration | FunctionExpression>} */ (node)
  1289. .id,
  1290. )
  1291. }
  1292. /** @typedef {import("estree").Node} Node */
  1293. /** @typedef {import("eslint").SourceCode} SourceCode */
  1294. /** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */
  1295. /** @typedef {import("estree").BinaryExpression} BinaryExpression */
  1296. /** @typedef {import("estree").MemberExpression} MemberExpression */
  1297. /** @typedef {import("estree").MethodDefinition} MethodDefinition */
  1298. /** @typedef {import("estree").Property} Property */
  1299. /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
  1300. /** @typedef {import("estree").UnaryExpression} UnaryExpression */
  1301. const typeConversionBinaryOps = Object.freeze(
  1302. new Set([
  1303. "==",
  1304. "!=",
  1305. "<",
  1306. "<=",
  1307. ">",
  1308. ">=",
  1309. "<<",
  1310. ">>",
  1311. ">>>",
  1312. "+",
  1313. "-",
  1314. "*",
  1315. "/",
  1316. "%",
  1317. "|",
  1318. "^",
  1319. "&",
  1320. "in",
  1321. ]),
  1322. );
  1323. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  1324. /**
  1325. * Check whether the given value is an ASTNode or not.
  1326. * @param {any} x The value to check.
  1327. * @returns {x is Node} `true` if the value is an ASTNode.
  1328. */
  1329. function isNode(x) {
  1330. return x !== null && typeof x === "object" && typeof x.type === "string"
  1331. }
  1332. const visitor = Object.freeze(
  1333. Object.assign(Object.create(null), {
  1334. /**
  1335. * @param {Node} node
  1336. * @param {HasSideEffectOptions} options
  1337. * @param {Record<string, string[]>} visitorKeys
  1338. */
  1339. $visit(node, options, visitorKeys) {
  1340. const { type } = node;
  1341. if (typeof (/** @type {any} */ (this)[type]) === "function") {
  1342. return /** @type {any} */ (this)[type](
  1343. node,
  1344. options,
  1345. visitorKeys,
  1346. )
  1347. }
  1348. return this.$visitChildren(node, options, visitorKeys)
  1349. },
  1350. /**
  1351. * @param {Node} node
  1352. * @param {HasSideEffectOptions} options
  1353. * @param {Record<string, string[]>} visitorKeys
  1354. */
  1355. $visitChildren(node, options, visitorKeys) {
  1356. const { type } = node;
  1357. for (const key of /** @type {(keyof Node)[]} */ (
  1358. visitorKeys[type] || getKeys(node)
  1359. )) {
  1360. const value = node[key];
  1361. if (Array.isArray(value)) {
  1362. for (const element of value) {
  1363. if (
  1364. isNode(element) &&
  1365. this.$visit(element, options, visitorKeys)
  1366. ) {
  1367. return true
  1368. }
  1369. }
  1370. } else if (
  1371. isNode(value) &&
  1372. this.$visit(value, options, visitorKeys)
  1373. ) {
  1374. return true
  1375. }
  1376. }
  1377. return false
  1378. },
  1379. ArrowFunctionExpression() {
  1380. return false
  1381. },
  1382. AssignmentExpression() {
  1383. return true
  1384. },
  1385. AwaitExpression() {
  1386. return true
  1387. },
  1388. /**
  1389. * @param {BinaryExpression} node
  1390. * @param {HasSideEffectOptions} options
  1391. * @param {Record<string, string[]>} visitorKeys
  1392. */
  1393. BinaryExpression(node, options, visitorKeys) {
  1394. if (
  1395. options.considerImplicitTypeConversion &&
  1396. typeConversionBinaryOps.has(node.operator) &&
  1397. (node.left.type !== "Literal" || node.right.type !== "Literal")
  1398. ) {
  1399. return true
  1400. }
  1401. return this.$visitChildren(node, options, visitorKeys)
  1402. },
  1403. CallExpression() {
  1404. return true
  1405. },
  1406. FunctionExpression() {
  1407. return false
  1408. },
  1409. ImportExpression() {
  1410. return true
  1411. },
  1412. /**
  1413. * @param {MemberExpression} node
  1414. * @param {HasSideEffectOptions} options
  1415. * @param {Record<string, string[]>} visitorKeys
  1416. */
  1417. MemberExpression(node, options, visitorKeys) {
  1418. if (options.considerGetters) {
  1419. return true
  1420. }
  1421. if (
  1422. options.considerImplicitTypeConversion &&
  1423. node.computed &&
  1424. node.property.type !== "Literal"
  1425. ) {
  1426. return true
  1427. }
  1428. return this.$visitChildren(node, options, visitorKeys)
  1429. },
  1430. /**
  1431. * @param {MethodDefinition} node
  1432. * @param {HasSideEffectOptions} options
  1433. * @param {Record<string, string[]>} visitorKeys
  1434. */
  1435. MethodDefinition(node, options, visitorKeys) {
  1436. if (
  1437. options.considerImplicitTypeConversion &&
  1438. node.computed &&
  1439. node.key.type !== "Literal"
  1440. ) {
  1441. return true
  1442. }
  1443. return this.$visitChildren(node, options, visitorKeys)
  1444. },
  1445. NewExpression() {
  1446. return true
  1447. },
  1448. /**
  1449. * @param {Property} node
  1450. * @param {HasSideEffectOptions} options
  1451. * @param {Record<string, string[]>} visitorKeys
  1452. */
  1453. Property(node, options, visitorKeys) {
  1454. if (
  1455. options.considerImplicitTypeConversion &&
  1456. node.computed &&
  1457. node.key.type !== "Literal"
  1458. ) {
  1459. return true
  1460. }
  1461. return this.$visitChildren(node, options, visitorKeys)
  1462. },
  1463. /**
  1464. * @param {PropertyDefinition} node
  1465. * @param {HasSideEffectOptions} options
  1466. * @param {Record<string, string[]>} visitorKeys
  1467. */
  1468. PropertyDefinition(node, options, visitorKeys) {
  1469. if (
  1470. options.considerImplicitTypeConversion &&
  1471. node.computed &&
  1472. node.key.type !== "Literal"
  1473. ) {
  1474. return true
  1475. }
  1476. return this.$visitChildren(node, options, visitorKeys)
  1477. },
  1478. /**
  1479. * @param {UnaryExpression} node
  1480. * @param {HasSideEffectOptions} options
  1481. * @param {Record<string, string[]>} visitorKeys
  1482. */
  1483. UnaryExpression(node, options, visitorKeys) {
  1484. if (node.operator === "delete") {
  1485. return true
  1486. }
  1487. if (
  1488. options.considerImplicitTypeConversion &&
  1489. typeConversionUnaryOps.has(node.operator) &&
  1490. node.argument.type !== "Literal"
  1491. ) {
  1492. return true
  1493. }
  1494. return this.$visitChildren(node, options, visitorKeys)
  1495. },
  1496. UpdateExpression() {
  1497. return true
  1498. },
  1499. YieldExpression() {
  1500. return true
  1501. },
  1502. }),
  1503. );
  1504. /**
  1505. * Check whether a given node has any side effect or not.
  1506. * @param {Node} node The node to get.
  1507. * @param {SourceCode} sourceCode The source code object.
  1508. * @param {HasSideEffectOptions} [options] The option object.
  1509. * @returns {boolean} `true` if the node has a certain side effect.
  1510. */
  1511. function hasSideEffect(node, sourceCode, options = {}) {
  1512. const { considerGetters = false, considerImplicitTypeConversion = false } =
  1513. options;
  1514. return visitor.$visit(
  1515. node,
  1516. { considerGetters, considerImplicitTypeConversion },
  1517. sourceCode.visitorKeys || KEYS,
  1518. )
  1519. }
  1520. /** @typedef {import("estree").Node} Node */
  1521. /** @typedef {import("@typescript-eslint/types").TSESTree.NewExpression} TSNewExpression */
  1522. /** @typedef {import("@typescript-eslint/types").TSESTree.CallExpression} TSCallExpression */
  1523. /** @typedef {import("eslint").SourceCode} SourceCode */
  1524. /** @typedef {import("eslint").AST.Token} Token */
  1525. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1526. /**
  1527. * Get the left parenthesis of the parent node syntax if it exists.
  1528. * E.g., `if (a) {}` then the `(`.
  1529. * @param {Node} node The AST node to check.
  1530. * @param {SourceCode} sourceCode The source code object to get tokens.
  1531. * @returns {Token|null} The left parenthesis of the parent node syntax
  1532. */
  1533. // eslint-disable-next-line complexity
  1534. function getParentSyntaxParen(node, sourceCode) {
  1535. const parent = /** @type {RuleNode} */ (node).parent;
  1536. if (!parent) {
  1537. return null
  1538. }
  1539. switch (parent.type) {
  1540. case "CallExpression":
  1541. case "NewExpression":
  1542. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  1543. return sourceCode.getTokenAfter(
  1544. // @ts-expect-error https://github.com/typescript-eslint/typescript-eslint/pull/5384
  1545. parent.typeArguments ||
  1546. /** @type {RuleNode} */ (
  1547. /** @type {unknown} */ (
  1548. /** @type {TSNewExpression | TSCallExpression} */ (
  1549. parent
  1550. ).typeParameters
  1551. )
  1552. ) ||
  1553. parent.callee,
  1554. isOpeningParenToken,
  1555. )
  1556. }
  1557. return null
  1558. case "DoWhileStatement":
  1559. if (parent.test === node) {
  1560. return sourceCode.getTokenAfter(
  1561. parent.body,
  1562. isOpeningParenToken,
  1563. )
  1564. }
  1565. return null
  1566. case "IfStatement":
  1567. case "WhileStatement":
  1568. if (parent.test === node) {
  1569. return sourceCode.getFirstToken(parent, 1)
  1570. }
  1571. return null
  1572. case "ImportExpression":
  1573. if (parent.source === node) {
  1574. return sourceCode.getFirstToken(parent, 1)
  1575. }
  1576. return null
  1577. case "SwitchStatement":
  1578. if (parent.discriminant === node) {
  1579. return sourceCode.getFirstToken(parent, 1)
  1580. }
  1581. return null
  1582. case "WithStatement":
  1583. if (parent.object === node) {
  1584. return sourceCode.getFirstToken(parent, 1)
  1585. }
  1586. return null
  1587. default:
  1588. return null
  1589. }
  1590. }
  1591. /**
  1592. * Check whether a given node is parenthesized or not.
  1593. * @param {number} times The number of parantheses.
  1594. * @param {Node} node The AST node to check.
  1595. * @param {SourceCode} sourceCode The source code object to get tokens.
  1596. * @returns {boolean} `true` if the node is parenthesized the given times.
  1597. */
  1598. /**
  1599. * Check whether a given node is parenthesized or not.
  1600. * @param {Node} node The AST node to check.
  1601. * @param {SourceCode} sourceCode The source code object to get tokens.
  1602. * @returns {boolean} `true` if the node is parenthesized.
  1603. */
  1604. /**
  1605. * Check whether a given node is parenthesized or not.
  1606. * @param {Node|number} timesOrNode The first parameter.
  1607. * @param {Node|SourceCode} nodeOrSourceCode The second parameter.
  1608. * @param {SourceCode} [optionalSourceCode] The third parameter.
  1609. * @returns {boolean} `true` if the node is parenthesized.
  1610. */
  1611. function isParenthesized(
  1612. timesOrNode,
  1613. nodeOrSourceCode,
  1614. optionalSourceCode,
  1615. ) {
  1616. /** @type {number} */
  1617. let times,
  1618. /** @type {RuleNode} */
  1619. node,
  1620. /** @type {SourceCode} */
  1621. sourceCode,
  1622. maybeLeftParen,
  1623. maybeRightParen;
  1624. if (typeof timesOrNode === "number") {
  1625. times = timesOrNode | 0;
  1626. node = /** @type {RuleNode} */ (nodeOrSourceCode);
  1627. sourceCode = /** @type {SourceCode} */ (optionalSourceCode);
  1628. if (!(times >= 1)) {
  1629. throw new TypeError("'times' should be a positive integer.")
  1630. }
  1631. } else {
  1632. times = 1;
  1633. node = /** @type {RuleNode} */ (timesOrNode);
  1634. sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode);
  1635. }
  1636. if (
  1637. node == null ||
  1638. // `Program` can't be parenthesized
  1639. node.parent == null ||
  1640. // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
  1641. (node.parent.type === "CatchClause" && node.parent.param === node)
  1642. ) {
  1643. return false
  1644. }
  1645. maybeLeftParen = maybeRightParen = node;
  1646. do {
  1647. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1648. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1649. } while (
  1650. maybeLeftParen != null &&
  1651. maybeRightParen != null &&
  1652. isOpeningParenToken(maybeLeftParen) &&
  1653. isClosingParenToken(maybeRightParen) &&
  1654. // Avoid false positive such as `if (a) {}`
  1655. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1656. --times > 0
  1657. )
  1658. return times === 0
  1659. }
  1660. /**
  1661. * @author Toru Nagashima <https://github.com/mysticatea>
  1662. * See LICENSE file in root directory for full license.
  1663. */
  1664. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1665. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1666. const internal = new WeakMap();
  1667. /**
  1668. * Check whether a given character is escaped or not.
  1669. * @param {string} str The string to check.
  1670. * @param {number} index The location of the character to check.
  1671. * @returns {boolean} `true` if the character is escaped.
  1672. */
  1673. function isEscaped(str, index) {
  1674. let escaped = false;
  1675. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1676. escaped = !escaped;
  1677. }
  1678. return escaped
  1679. }
  1680. /**
  1681. * Replace a given string by a given matcher.
  1682. * @param {PatternMatcher} matcher The pattern matcher.
  1683. * @param {string} str The string to be replaced.
  1684. * @param {string} replacement The new substring to replace each matched part.
  1685. * @returns {string} The replaced string.
  1686. */
  1687. function replaceS(matcher, str, replacement) {
  1688. const chunks = [];
  1689. let index = 0;
  1690. /**
  1691. * @param {string} key The placeholder.
  1692. * @param {RegExpExecArray} match The matched information.
  1693. * @returns {string} The replaced string.
  1694. */
  1695. function replacer(key, match) {
  1696. switch (key) {
  1697. case "$$":
  1698. return "$"
  1699. case "$&":
  1700. return match[0]
  1701. case "$`":
  1702. return str.slice(0, match.index)
  1703. case "$'":
  1704. return str.slice(match.index + match[0].length)
  1705. default: {
  1706. const i = key.slice(1);
  1707. if (i in match) {
  1708. return match[/** @type {any} */ (i)]
  1709. }
  1710. return key
  1711. }
  1712. }
  1713. }
  1714. for (const match of matcher.execAll(str)) {
  1715. chunks.push(str.slice(index, match.index));
  1716. chunks.push(
  1717. replacement.replace(placeholder, (key) => replacer(key, match)),
  1718. );
  1719. index = match.index + match[0].length;
  1720. }
  1721. chunks.push(str.slice(index));
  1722. return chunks.join("")
  1723. }
  1724. /**
  1725. * Replace a given string by a given matcher.
  1726. * @param {PatternMatcher} matcher The pattern matcher.
  1727. * @param {string} str The string to be replaced.
  1728. * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.
  1729. * @returns {string} The replaced string.
  1730. */
  1731. function replaceF(matcher, str, replace) {
  1732. const chunks = [];
  1733. let index = 0;
  1734. for (const match of matcher.execAll(str)) {
  1735. chunks.push(str.slice(index, match.index));
  1736. chunks.push(
  1737. String(
  1738. replace(
  1739. .../** @type {[string, ...string[]]} */ (
  1740. /** @type {string[]} */ (match)
  1741. ),
  1742. match.index,
  1743. match.input,
  1744. ),
  1745. ),
  1746. );
  1747. index = match.index + match[0].length;
  1748. }
  1749. chunks.push(str.slice(index));
  1750. return chunks.join("")
  1751. }
  1752. /**
  1753. * The class to find patterns as considering escape sequences.
  1754. */
  1755. class PatternMatcher {
  1756. /**
  1757. * Initialize this matcher.
  1758. * @param {RegExp} pattern The pattern to match.
  1759. * @param {{escaped?:boolean}} [options] The options.
  1760. */
  1761. constructor(pattern, options = {}) {
  1762. const { escaped = false } = options;
  1763. if (!(pattern instanceof RegExp)) {
  1764. throw new TypeError("'pattern' should be a RegExp instance.")
  1765. }
  1766. if (!pattern.flags.includes("g")) {
  1767. throw new Error("'pattern' should contains 'g' flag.")
  1768. }
  1769. internal.set(this, {
  1770. pattern: new RegExp(pattern.source, pattern.flags),
  1771. escaped: Boolean(escaped),
  1772. });
  1773. }
  1774. /**
  1775. * Find the pattern in a given string.
  1776. * @param {string} str The string to find.
  1777. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1778. */
  1779. *execAll(str) {
  1780. const { pattern, escaped } =
  1781. /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this));
  1782. let match = null;
  1783. let lastIndex = 0;
  1784. pattern.lastIndex = 0;
  1785. while ((match = pattern.exec(str)) != null) {
  1786. if (escaped || !isEscaped(str, match.index)) {
  1787. lastIndex = pattern.lastIndex;
  1788. yield match;
  1789. pattern.lastIndex = lastIndex;
  1790. }
  1791. }
  1792. }
  1793. /**
  1794. * Check whether the pattern is found in a given string.
  1795. * @param {string} str The string to check.
  1796. * @returns {boolean} `true` if the pattern was found in the string.
  1797. */
  1798. test(str) {
  1799. const it = this.execAll(str);
  1800. const ret = it.next();
  1801. return !ret.done
  1802. }
  1803. /**
  1804. * Replace a given string.
  1805. * @param {string} str The string to be replaced.
  1806. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1807. * @returns {string} The replaced string.
  1808. */
  1809. [Symbol.replace](str, replacer) {
  1810. return typeof replacer === "function"
  1811. ? replaceF(this, String(str), replacer)
  1812. : replaceS(this, String(str), String(replacer))
  1813. }
  1814. }
  1815. /** @typedef {import("eslint").Scope.Scope} Scope */
  1816. /** @typedef {import("eslint").Scope.Variable} Variable */
  1817. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1818. /** @typedef {import("estree").Node} Node */
  1819. /** @typedef {import("estree").Expression} Expression */
  1820. /** @typedef {import("estree").Pattern} Pattern */
  1821. /** @typedef {import("estree").Identifier} Identifier */
  1822. /** @typedef {import("estree").SimpleCallExpression} CallExpression */
  1823. /** @typedef {import("estree").Program} Program */
  1824. /** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
  1825. /** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
  1826. /** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
  1827. /** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
  1828. /** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
  1829. /** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */
  1830. /** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */
  1831. /** @typedef {import("estree").ExportSpecifier} ExportSpecifier */
  1832. /** @typedef {import("estree").Property} Property */
  1833. /** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
  1834. /** @typedef {import("estree").Literal} Literal */
  1835. /** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
  1836. /** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */
  1837. /**
  1838. * @template T
  1839. * @typedef {import("./types.mjs").TraceMap<T>} TraceMap
  1840. */
  1841. /**
  1842. * @template T
  1843. * @typedef {import("./types.mjs").TraceMapObject<T>} TraceMapObject
  1844. */
  1845. /**
  1846. * @template T
  1847. * @typedef {import("./types.mjs").TrackedReferences<T>} TrackedReferences
  1848. */
  1849. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1850. /**
  1851. * Check whether a given node is an import node or not.
  1852. * @param {Node} node
  1853. * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.
  1854. */
  1855. function isHasSource(node) {
  1856. return (
  1857. IMPORT_TYPE.test(node.type) &&
  1858. /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (
  1859. node
  1860. ).source != null
  1861. )
  1862. }
  1863. const has =
  1864. /** @type {<T>(traceMap: TraceMap<unknown>, v: T) => v is (string extends T ? string : T)} */ (
  1865. Function.call.bind(Object.hasOwnProperty)
  1866. );
  1867. const READ = Symbol("read");
  1868. const CALL = Symbol("call");
  1869. const CONSTRUCT = Symbol("construct");
  1870. const ESM = Symbol("esm");
  1871. const requireCall = { require: { [CALL]: true } };
  1872. /**
  1873. * Check whether a given variable is modified or not.
  1874. * @param {Variable|undefined} variable The variable to check.
  1875. * @returns {boolean} `true` if the variable is modified.
  1876. */
  1877. function isModifiedGlobal(variable) {
  1878. return (
  1879. variable == null ||
  1880. variable.defs.length !== 0 ||
  1881. variable.references.some((r) => r.isWrite())
  1882. )
  1883. }
  1884. /**
  1885. * Check if the value of a given node is passed through to the parent syntax as-is.
  1886. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1887. * @param {Node} node A node to check.
  1888. * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.
  1889. */
  1890. function isPassThrough(node) {
  1891. const parent = /** @type {TSESTreeNode} */ (node).parent;
  1892. if (parent) {
  1893. switch (parent.type) {
  1894. case "ConditionalExpression":
  1895. return parent.consequent === node || parent.alternate === node
  1896. case "LogicalExpression":
  1897. return true
  1898. case "SequenceExpression":
  1899. return (
  1900. parent.expressions[parent.expressions.length - 1] === node
  1901. )
  1902. case "ChainExpression":
  1903. return true
  1904. case "TSAsExpression":
  1905. case "TSSatisfiesExpression":
  1906. case "TSTypeAssertion":
  1907. case "TSNonNullExpression":
  1908. case "TSInstantiationExpression":
  1909. return true
  1910. default:
  1911. return false
  1912. }
  1913. }
  1914. return false
  1915. }
  1916. /**
  1917. * The reference tracker.
  1918. */
  1919. class ReferenceTracker {
  1920. /**
  1921. * Initialize this tracker.
  1922. * @param {Scope} globalScope The global scope.
  1923. * @param {object} [options] The options.
  1924. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1925. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
  1926. */
  1927. constructor(globalScope, options = {}) {
  1928. const {
  1929. mode = "strict",
  1930. globalObjectNames = ["global", "globalThis", "self", "window"],
  1931. } = options;
  1932. /** @private @type {Variable[]} */
  1933. this.variableStack = [];
  1934. /** @private */
  1935. this.globalScope = globalScope;
  1936. /** @private */
  1937. this.mode = mode;
  1938. /** @private */
  1939. this.globalObjectNames = globalObjectNames.slice(0);
  1940. }
  1941. /**
  1942. * Iterate the references of global variables.
  1943. * @template T
  1944. * @param {TraceMap<T>} traceMap The trace map.
  1945. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1946. */
  1947. *iterateGlobalReferences(traceMap) {
  1948. for (const key of Object.keys(traceMap)) {
  1949. const nextTraceMap = traceMap[key];
  1950. const path = [key];
  1951. const variable = this.globalScope.set.get(key);
  1952. if (isModifiedGlobal(variable)) {
  1953. continue
  1954. }
  1955. yield* this._iterateVariableReferences(
  1956. /** @type {Variable} */ (variable),
  1957. path,
  1958. nextTraceMap,
  1959. true,
  1960. );
  1961. }
  1962. for (const key of this.globalObjectNames) {
  1963. /** @type {string[]} */
  1964. const path = [];
  1965. const variable = this.globalScope.set.get(key);
  1966. if (isModifiedGlobal(variable)) {
  1967. continue
  1968. }
  1969. yield* this._iterateVariableReferences(
  1970. /** @type {Variable} */ (variable),
  1971. path,
  1972. traceMap,
  1973. false,
  1974. );
  1975. }
  1976. }
  1977. /**
  1978. * Iterate the references of CommonJS modules.
  1979. * @template T
  1980. * @param {TraceMap<T>} traceMap The trace map.
  1981. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1982. */
  1983. *iterateCjsReferences(traceMap) {
  1984. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1985. const key = getStringIfConstant(
  1986. /** @type {CallExpression} */ (node).arguments[0],
  1987. );
  1988. if (key == null || !has(traceMap, key)) {
  1989. continue
  1990. }
  1991. const nextTraceMap = traceMap[key];
  1992. const path = [key];
  1993. if (nextTraceMap[READ]) {
  1994. yield {
  1995. node,
  1996. path,
  1997. type: READ,
  1998. info: nextTraceMap[READ],
  1999. };
  2000. }
  2001. yield* this._iteratePropertyReferences(
  2002. /** @type {CallExpression} */ (node),
  2003. path,
  2004. nextTraceMap,
  2005. );
  2006. }
  2007. }
  2008. /**
  2009. * Iterate the references of ES modules.
  2010. * @template T
  2011. * @param {TraceMap<T>} traceMap The trace map.
  2012. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2013. */
  2014. *iterateEsmReferences(traceMap) {
  2015. const programNode = /** @type {Program} */ (this.globalScope.block);
  2016. for (const node of programNode.body) {
  2017. if (!isHasSource(node)) {
  2018. continue
  2019. }
  2020. const moduleId = /** @type {string} */ (node.source.value);
  2021. if (!has(traceMap, moduleId)) {
  2022. continue
  2023. }
  2024. const nextTraceMap = traceMap[moduleId];
  2025. const path = [moduleId];
  2026. if (nextTraceMap[READ]) {
  2027. yield {
  2028. // eslint-disable-next-line object-shorthand -- apply type
  2029. node: /** @type {RuleNode} */ (node),
  2030. path,
  2031. type: READ,
  2032. info: nextTraceMap[READ],
  2033. };
  2034. }
  2035. if (node.type === "ExportAllDeclaration") {
  2036. for (const key of Object.keys(nextTraceMap)) {
  2037. const exportTraceMap = nextTraceMap[key];
  2038. if (exportTraceMap[READ]) {
  2039. yield {
  2040. // eslint-disable-next-line object-shorthand -- apply type
  2041. node: /** @type {RuleNode} */ (node),
  2042. path: path.concat(key),
  2043. type: READ,
  2044. info: exportTraceMap[READ],
  2045. };
  2046. }
  2047. }
  2048. } else {
  2049. for (const specifier of node.specifiers) {
  2050. const esm = has(nextTraceMap, ESM);
  2051. const it = this._iterateImportReferences(
  2052. specifier,
  2053. path,
  2054. esm
  2055. ? nextTraceMap
  2056. : this.mode === "legacy"
  2057. ? { default: nextTraceMap, ...nextTraceMap }
  2058. : { default: nextTraceMap },
  2059. );
  2060. if (esm) {
  2061. yield* it;
  2062. } else {
  2063. for (const report of it) {
  2064. report.path = report.path.filter(exceptDefault);
  2065. if (
  2066. report.path.length >= 2 ||
  2067. report.type !== READ
  2068. ) {
  2069. yield report;
  2070. }
  2071. }
  2072. }
  2073. }
  2074. }
  2075. }
  2076. }
  2077. /**
  2078. * Iterate the property references for a given expression AST node.
  2079. * @template T
  2080. * @param {Expression} node The expression AST node to iterate property references.
  2081. * @param {TraceMap<T>} traceMap The trace map.
  2082. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate property references.
  2083. */
  2084. *iteratePropertyReferences(node, traceMap) {
  2085. yield* this._iteratePropertyReferences(node, [], traceMap);
  2086. }
  2087. /**
  2088. * Iterate the references for a given variable.
  2089. * @private
  2090. * @template T
  2091. * @param {Variable} variable The variable to iterate that references.
  2092. * @param {string[]} path The current path.
  2093. * @param {TraceMapObject<T>} traceMap The trace map.
  2094. * @param {boolean} shouldReport = The flag to report those references.
  2095. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2096. */
  2097. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  2098. if (this.variableStack.includes(variable)) {
  2099. return
  2100. }
  2101. this.variableStack.push(variable);
  2102. try {
  2103. for (const reference of variable.references) {
  2104. if (!reference.isRead()) {
  2105. continue
  2106. }
  2107. const node = /** @type {RuleNode & Identifier} */ (
  2108. reference.identifier
  2109. );
  2110. if (shouldReport && traceMap[READ]) {
  2111. yield { node, path, type: READ, info: traceMap[READ] };
  2112. }
  2113. yield* this._iteratePropertyReferences(node, path, traceMap);
  2114. }
  2115. } finally {
  2116. this.variableStack.pop();
  2117. }
  2118. }
  2119. /**
  2120. * Iterate the references for a given AST node.
  2121. * @private
  2122. * @template T
  2123. * @param {Expression} rootNode The AST node to iterate references.
  2124. * @param {string[]} path The current path.
  2125. * @param {TraceMapObject<T>} traceMap The trace map.
  2126. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2127. */
  2128. //eslint-disable-next-line complexity
  2129. *_iteratePropertyReferences(rootNode, path, traceMap) {
  2130. let node = rootNode;
  2131. while (isPassThrough(node)) {
  2132. node = node.parent;
  2133. }
  2134. const parent = /** @type {RuleNode} */ (node).parent;
  2135. if (!parent) {
  2136. return
  2137. }
  2138. if (parent.type === "MemberExpression") {
  2139. if (parent.object === node) {
  2140. const key = getPropertyName(parent);
  2141. if (key == null || !has(traceMap, key)) {
  2142. return
  2143. }
  2144. path = path.concat(key); //eslint-disable-line no-param-reassign
  2145. const nextTraceMap = traceMap[key];
  2146. if (nextTraceMap[READ]) {
  2147. yield {
  2148. node: parent,
  2149. path,
  2150. type: READ,
  2151. info: nextTraceMap[READ],
  2152. };
  2153. }
  2154. yield* this._iteratePropertyReferences(
  2155. parent,
  2156. path,
  2157. nextTraceMap,
  2158. );
  2159. }
  2160. return
  2161. }
  2162. if (parent.type === "CallExpression") {
  2163. if (parent.callee === node && traceMap[CALL]) {
  2164. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  2165. }
  2166. return
  2167. }
  2168. if (parent.type === "NewExpression") {
  2169. if (parent.callee === node && traceMap[CONSTRUCT]) {
  2170. yield {
  2171. node: parent,
  2172. path,
  2173. type: CONSTRUCT,
  2174. info: traceMap[CONSTRUCT],
  2175. };
  2176. }
  2177. return
  2178. }
  2179. if (parent.type === "AssignmentExpression") {
  2180. if (parent.right === node) {
  2181. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  2182. yield* this._iteratePropertyReferences(parent, path, traceMap);
  2183. }
  2184. return
  2185. }
  2186. if (parent.type === "AssignmentPattern") {
  2187. if (parent.right === node) {
  2188. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  2189. }
  2190. return
  2191. }
  2192. if (parent.type === "VariableDeclarator") {
  2193. if (parent.init === node) {
  2194. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  2195. }
  2196. }
  2197. }
  2198. /**
  2199. * Iterate the references for a given Pattern node.
  2200. * @private
  2201. * @template T
  2202. * @param {Pattern} patternNode The Pattern node to iterate references.
  2203. * @param {string[]} path The current path.
  2204. * @param {TraceMapObject<T>} traceMap The trace map.
  2205. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2206. */
  2207. *_iterateLhsReferences(patternNode, path, traceMap) {
  2208. if (patternNode.type === "Identifier") {
  2209. const variable = findVariable(this.globalScope, patternNode);
  2210. if (variable != null) {
  2211. yield* this._iterateVariableReferences(
  2212. variable,
  2213. path,
  2214. traceMap,
  2215. false,
  2216. );
  2217. }
  2218. return
  2219. }
  2220. if (patternNode.type === "ObjectPattern") {
  2221. for (const property of patternNode.properties) {
  2222. const key = getPropertyName(
  2223. /** @type {AssignmentProperty} */ (property),
  2224. );
  2225. if (key == null || !has(traceMap, key)) {
  2226. continue
  2227. }
  2228. const nextPath = path.concat(key);
  2229. const nextTraceMap = traceMap[key];
  2230. if (nextTraceMap[READ]) {
  2231. yield {
  2232. node: /** @type {RuleNode} */ (property),
  2233. path: nextPath,
  2234. type: READ,
  2235. info: nextTraceMap[READ],
  2236. };
  2237. }
  2238. yield* this._iterateLhsReferences(
  2239. /** @type {AssignmentProperty} */ (property).value,
  2240. nextPath,
  2241. nextTraceMap,
  2242. );
  2243. }
  2244. return
  2245. }
  2246. if (patternNode.type === "AssignmentPattern") {
  2247. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  2248. }
  2249. }
  2250. /**
  2251. * Iterate the references for a given ModuleSpecifier node.
  2252. * @private
  2253. * @template T
  2254. * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.
  2255. * @param {string[]} path The current path.
  2256. * @param {TraceMapObject<T>} traceMap The trace map.
  2257. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2258. */
  2259. *_iterateImportReferences(specifierNode, path, traceMap) {
  2260. const type = specifierNode.type;
  2261. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  2262. const key =
  2263. type === "ImportDefaultSpecifier"
  2264. ? "default"
  2265. : specifierNode.imported.type === "Identifier"
  2266. ? specifierNode.imported.name
  2267. : specifierNode.imported.value;
  2268. if (!has(traceMap, key)) {
  2269. return
  2270. }
  2271. path = path.concat(key); //eslint-disable-line no-param-reassign
  2272. const nextTraceMap = traceMap[key];
  2273. if (nextTraceMap[READ]) {
  2274. yield {
  2275. node: /** @type {RuleNode} */ (specifierNode),
  2276. path,
  2277. type: READ,
  2278. info: nextTraceMap[READ],
  2279. };
  2280. }
  2281. yield* this._iterateVariableReferences(
  2282. /** @type {Variable} */ (
  2283. findVariable(this.globalScope, specifierNode.local)
  2284. ),
  2285. path,
  2286. nextTraceMap,
  2287. false,
  2288. );
  2289. return
  2290. }
  2291. if (type === "ImportNamespaceSpecifier") {
  2292. yield* this._iterateVariableReferences(
  2293. /** @type {Variable} */ (
  2294. findVariable(this.globalScope, specifierNode.local)
  2295. ),
  2296. path,
  2297. traceMap,
  2298. false,
  2299. );
  2300. return
  2301. }
  2302. if (type === "ExportSpecifier") {
  2303. const key =
  2304. specifierNode.local.type === "Identifier"
  2305. ? specifierNode.local.name
  2306. : specifierNode.local.value;
  2307. if (!has(traceMap, key)) {
  2308. return
  2309. }
  2310. path = path.concat(key); //eslint-disable-line no-param-reassign
  2311. const nextTraceMap = traceMap[key];
  2312. if (nextTraceMap[READ]) {
  2313. yield {
  2314. node: /** @type {RuleNode} */ (specifierNode),
  2315. path,
  2316. type: READ,
  2317. info: nextTraceMap[READ],
  2318. };
  2319. }
  2320. }
  2321. }
  2322. }
  2323. ReferenceTracker.READ = READ;
  2324. ReferenceTracker.CALL = CALL;
  2325. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  2326. ReferenceTracker.ESM = ESM;
  2327. /**
  2328. * This is a predicate function for Array#filter.
  2329. * @param {string} name A name part.
  2330. * @param {number} index The index of the name.
  2331. * @returns {boolean} `false` if it's default.
  2332. */
  2333. function exceptDefault(name, index) {
  2334. return !(index === 1 && name === "default")
  2335. }
  2336. /** @typedef {import("./types.mjs").StaticValue} StaticValue */
  2337. var index = {
  2338. CALL,
  2339. CONSTRUCT,
  2340. ESM,
  2341. findVariable,
  2342. getFunctionHeadLocation,
  2343. getFunctionNameWithKind,
  2344. getInnermostScope,
  2345. getPropertyName,
  2346. getStaticValue,
  2347. getStringIfConstant,
  2348. hasSideEffect,
  2349. isArrowToken,
  2350. isClosingBraceToken,
  2351. isClosingBracketToken,
  2352. isClosingParenToken,
  2353. isColonToken,
  2354. isCommaToken,
  2355. isCommentToken,
  2356. isNotArrowToken,
  2357. isNotClosingBraceToken,
  2358. isNotClosingBracketToken,
  2359. isNotClosingParenToken,
  2360. isNotColonToken,
  2361. isNotCommaToken,
  2362. isNotCommentToken,
  2363. isNotOpeningBraceToken,
  2364. isNotOpeningBracketToken,
  2365. isNotOpeningParenToken,
  2366. isNotSemicolonToken,
  2367. isOpeningBraceToken,
  2368. isOpeningBracketToken,
  2369. isOpeningParenToken,
  2370. isParenthesized,
  2371. isSemicolonToken,
  2372. PatternMatcher,
  2373. READ,
  2374. ReferenceTracker,
  2375. };
  2376. export { CALL, CONSTRUCT, ESM, PatternMatcher, READ, ReferenceTracker, index as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
  2377. //# sourceMappingURL=index.mjs.map