index.mjs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. import { getKeys, KEYS } from 'eslint-visitor-keys';
  2. /**
  3. * Get the innermost scope which contains a given location.
  4. * @param {Scope} initialScope The initial scope to search.
  5. * @param {Node} node The location to search.
  6. * @returns {Scope} The innermost scope.
  7. */
  8. function getInnermostScope(initialScope, node) {
  9. const location = node.range[0];
  10. let scope = initialScope;
  11. let found = false;
  12. do {
  13. found = false;
  14. for (const childScope of scope.childScopes) {
  15. const range = childScope.block.range;
  16. if (range[0] <= location && location < range[1]) {
  17. scope = childScope;
  18. found = true;
  19. break
  20. }
  21. }
  22. } while (found)
  23. return scope
  24. }
  25. /**
  26. * Find the variable of a given name.
  27. * @param {Scope} initialScope The scope to start finding.
  28. * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  29. * @returns {Variable|null} The found variable or null.
  30. */
  31. function findVariable(initialScope, nameOrNode) {
  32. let name = "";
  33. let scope = initialScope;
  34. if (typeof nameOrNode === "string") {
  35. name = nameOrNode;
  36. } else {
  37. name = nameOrNode.name;
  38. scope = getInnermostScope(scope, nameOrNode);
  39. }
  40. while (scope != null) {
  41. const variable = scope.set.get(name);
  42. if (variable != null) {
  43. return variable
  44. }
  45. scope = scope.upper;
  46. }
  47. return null
  48. }
  49. /**
  50. * Negate the result of `this` calling.
  51. * @param {Token} token The token to check.
  52. * @returns {boolean} `true` if the result of `this(token)` is `false`.
  53. */
  54. function negate0(token) {
  55. return !this(token) //eslint-disable-line no-invalid-this
  56. }
  57. /**
  58. * Creates the negate function of the given function.
  59. * @param {function(Token):boolean} f - The function to negate.
  60. * @returns {function(Token):boolean} Negated function.
  61. */
  62. function negate(f) {
  63. return negate0.bind(f)
  64. }
  65. /**
  66. * Checks if the given token is a PunctuatorToken with the given value
  67. * @param {Token} token - The token to check.
  68. * @param {string} value - The value to check.
  69. * @returns {boolean} `true` if the token is a PunctuatorToken with the given value.
  70. */
  71. function isPunctuatorTokenWithValue(token, value) {
  72. return token.type === "Punctuator" && token.value === value
  73. }
  74. /**
  75. * Checks if the given token is an arrow token or not.
  76. * @param {Token} token - The token to check.
  77. * @returns {boolean} `true` if the token is an arrow token.
  78. */
  79. function isArrowToken(token) {
  80. return isPunctuatorTokenWithValue(token, "=>")
  81. }
  82. /**
  83. * Checks if the given token is a comma token or not.
  84. * @param {Token} token - The token to check.
  85. * @returns {boolean} `true` if the token is a comma token.
  86. */
  87. function isCommaToken(token) {
  88. return isPunctuatorTokenWithValue(token, ",")
  89. }
  90. /**
  91. * Checks if the given token is a semicolon token or not.
  92. * @param {Token} token - The token to check.
  93. * @returns {boolean} `true` if the token is a semicolon token.
  94. */
  95. function isSemicolonToken(token) {
  96. return isPunctuatorTokenWithValue(token, ";")
  97. }
  98. /**
  99. * Checks if the given token is a colon token or not.
  100. * @param {Token} token - The token to check.
  101. * @returns {boolean} `true` if the token is a colon token.
  102. */
  103. function isColonToken(token) {
  104. return isPunctuatorTokenWithValue(token, ":")
  105. }
  106. /**
  107. * Checks if the given token is an opening parenthesis token or not.
  108. * @param {Token} token - The token to check.
  109. * @returns {boolean} `true` if the token is an opening parenthesis token.
  110. */
  111. function isOpeningParenToken(token) {
  112. return isPunctuatorTokenWithValue(token, "(")
  113. }
  114. /**
  115. * Checks if the given token is a closing parenthesis token or not.
  116. * @param {Token} token - The token to check.
  117. * @returns {boolean} `true` if the token is a closing parenthesis token.
  118. */
  119. function isClosingParenToken(token) {
  120. return isPunctuatorTokenWithValue(token, ")")
  121. }
  122. /**
  123. * Checks if the given token is an opening square bracket token or not.
  124. * @param {Token} token - The token to check.
  125. * @returns {boolean} `true` if the token is an opening square bracket token.
  126. */
  127. function isOpeningBracketToken(token) {
  128. return isPunctuatorTokenWithValue(token, "[")
  129. }
  130. /**
  131. * Checks if the given token is a closing square bracket token or not.
  132. * @param {Token} token - The token to check.
  133. * @returns {boolean} `true` if the token is a closing square bracket token.
  134. */
  135. function isClosingBracketToken(token) {
  136. return isPunctuatorTokenWithValue(token, "]")
  137. }
  138. /**
  139. * Checks if the given token is an opening brace token or not.
  140. * @param {Token} token - The token to check.
  141. * @returns {boolean} `true` if the token is an opening brace token.
  142. */
  143. function isOpeningBraceToken(token) {
  144. return isPunctuatorTokenWithValue(token, "{")
  145. }
  146. /**
  147. * Checks if the given token is a closing brace token or not.
  148. * @param {Token} token - The token to check.
  149. * @returns {boolean} `true` if the token is a closing brace token.
  150. */
  151. function isClosingBraceToken(token) {
  152. return isPunctuatorTokenWithValue(token, "}")
  153. }
  154. /**
  155. * Checks if the given token is a comment token or not.
  156. * @param {Token} token - The token to check.
  157. * @returns {boolean} `true` if the token is a comment token.
  158. */
  159. function isCommentToken(token) {
  160. return ["Block", "Line", "Shebang"].includes(token.type)
  161. }
  162. const isNotArrowToken = negate(isArrowToken);
  163. const isNotCommaToken = negate(isCommaToken);
  164. const isNotSemicolonToken = negate(isSemicolonToken);
  165. const isNotColonToken = negate(isColonToken);
  166. const isNotOpeningParenToken = negate(isOpeningParenToken);
  167. const isNotClosingParenToken = negate(isClosingParenToken);
  168. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  169. const isNotClosingBracketToken = negate(isClosingBracketToken);
  170. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  171. const isNotClosingBraceToken = negate(isClosingBraceToken);
  172. const isNotCommentToken = negate(isCommentToken);
  173. /**
  174. * Get the `(` token of the given function node.
  175. * @param {Node} node - The function node to get.
  176. * @param {SourceCode} sourceCode - The source code object to get tokens.
  177. * @returns {Token} `(` token.
  178. */
  179. function getOpeningParenOfParams(node, sourceCode) {
  180. return node.id
  181. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  182. : sourceCode.getFirstToken(node, isOpeningParenToken)
  183. }
  184. /**
  185. * Get the location of the given function node for reporting.
  186. * @param {Node} node - The function node to get.
  187. * @param {SourceCode} sourceCode - The source code object to get tokens.
  188. * @returns {string} The location of the function node for reporting.
  189. */
  190. function getFunctionHeadLocation(node, sourceCode) {
  191. const parent = node.parent;
  192. let start = null;
  193. let end = null;
  194. if (node.type === "ArrowFunctionExpression") {
  195. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  196. start = arrowToken.loc.start;
  197. end = arrowToken.loc.end;
  198. } else if (
  199. parent.type === "Property" ||
  200. parent.type === "MethodDefinition" ||
  201. parent.type === "PropertyDefinition"
  202. ) {
  203. start = parent.loc.start;
  204. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  205. } else {
  206. start = node.loc.start;
  207. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  208. }
  209. return {
  210. start: { ...start },
  211. end: { ...end },
  212. }
  213. }
  214. /* globals globalThis, global, self, window */
  215. const globalObject =
  216. typeof globalThis !== "undefined"
  217. ? globalThis
  218. : typeof self !== "undefined"
  219. ? self
  220. : typeof window !== "undefined"
  221. ? window
  222. : typeof global !== "undefined"
  223. ? global
  224. : {};
  225. const builtinNames = Object.freeze(
  226. new Set([
  227. "Array",
  228. "ArrayBuffer",
  229. "BigInt",
  230. "BigInt64Array",
  231. "BigUint64Array",
  232. "Boolean",
  233. "DataView",
  234. "Date",
  235. "decodeURI",
  236. "decodeURIComponent",
  237. "encodeURI",
  238. "encodeURIComponent",
  239. "escape",
  240. "Float32Array",
  241. "Float64Array",
  242. "Function",
  243. "Infinity",
  244. "Int16Array",
  245. "Int32Array",
  246. "Int8Array",
  247. "isFinite",
  248. "isNaN",
  249. "isPrototypeOf",
  250. "JSON",
  251. "Map",
  252. "Math",
  253. "NaN",
  254. "Number",
  255. "Object",
  256. "parseFloat",
  257. "parseInt",
  258. "Promise",
  259. "Proxy",
  260. "Reflect",
  261. "RegExp",
  262. "Set",
  263. "String",
  264. "Symbol",
  265. "Uint16Array",
  266. "Uint32Array",
  267. "Uint8Array",
  268. "Uint8ClampedArray",
  269. "undefined",
  270. "unescape",
  271. "WeakMap",
  272. "WeakSet",
  273. ]),
  274. );
  275. const callAllowed = new Set(
  276. [
  277. Array.isArray,
  278. typeof BigInt === "function" ? BigInt : undefined,
  279. Boolean,
  280. Date,
  281. Date.parse,
  282. decodeURI,
  283. decodeURIComponent,
  284. encodeURI,
  285. encodeURIComponent,
  286. escape,
  287. isFinite,
  288. isNaN,
  289. isPrototypeOf,
  290. ...Object.getOwnPropertyNames(Math)
  291. .map((k) => Math[k])
  292. .filter((f) => typeof f === "function"),
  293. Number,
  294. Number.isFinite,
  295. Number.isNaN,
  296. Number.parseFloat,
  297. Number.parseInt,
  298. Object,
  299. Object.entries,
  300. Object.is,
  301. Object.isExtensible,
  302. Object.isFrozen,
  303. Object.isSealed,
  304. Object.keys,
  305. Object.values,
  306. parseFloat,
  307. parseInt,
  308. RegExp,
  309. String,
  310. String.fromCharCode,
  311. String.fromCodePoint,
  312. String.raw,
  313. Symbol.for,
  314. Symbol.keyFor,
  315. unescape,
  316. ].filter((f) => typeof f === "function"),
  317. );
  318. const callPassThrough = new Set([
  319. Object.freeze,
  320. Object.preventExtensions,
  321. Object.seal,
  322. ]);
  323. /**
  324. * Get the property descriptor.
  325. * @param {object} object The object to get.
  326. * @param {string|number|symbol} name The property name to get.
  327. */
  328. function getPropertyDescriptor(object, name) {
  329. let x = object;
  330. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  331. const d = Object.getOwnPropertyDescriptor(x, name);
  332. if (d) {
  333. return d
  334. }
  335. x = Object.getPrototypeOf(x);
  336. }
  337. return null
  338. }
  339. /**
  340. * Check if a property is getter or not.
  341. * @param {object} object The object to check.
  342. * @param {string|number|symbol} name The property name to check.
  343. */
  344. function isGetter(object, name) {
  345. const d = getPropertyDescriptor(object, name);
  346. return d != null && d.get != null
  347. }
  348. /**
  349. * Get the element values of a given node list.
  350. * @param {Node[]} nodeList The node list to get values.
  351. * @param {Scope|undefined} initialScope The initial scope to find variables.
  352. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  353. */
  354. function getElementValues(nodeList, initialScope) {
  355. const valueList = [];
  356. for (let i = 0; i < nodeList.length; ++i) {
  357. const elementNode = nodeList[i];
  358. if (elementNode == null) {
  359. valueList.length = i + 1;
  360. } else if (elementNode.type === "SpreadElement") {
  361. const argument = getStaticValueR(elementNode.argument, initialScope);
  362. if (argument == null) {
  363. return null
  364. }
  365. valueList.push(...argument.value);
  366. } else {
  367. const element = getStaticValueR(elementNode, initialScope);
  368. if (element == null) {
  369. return null
  370. }
  371. valueList.push(element.value);
  372. }
  373. }
  374. return valueList
  375. }
  376. const operations = Object.freeze({
  377. ArrayExpression(node, initialScope) {
  378. const elements = getElementValues(node.elements, initialScope);
  379. return elements != null ? { value: elements } : null
  380. },
  381. AssignmentExpression(node, initialScope) {
  382. if (node.operator === "=") {
  383. return getStaticValueR(node.right, initialScope)
  384. }
  385. return null
  386. },
  387. //eslint-disable-next-line complexity
  388. BinaryExpression(node, initialScope) {
  389. if (node.operator === "in" || node.operator === "instanceof") {
  390. // Not supported.
  391. return null
  392. }
  393. const left = getStaticValueR(node.left, initialScope);
  394. const right = getStaticValueR(node.right, initialScope);
  395. if (left != null && right != null) {
  396. switch (node.operator) {
  397. case "==":
  398. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  399. case "!=":
  400. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  401. case "===":
  402. return { value: left.value === right.value }
  403. case "!==":
  404. return { value: left.value !== right.value }
  405. case "<":
  406. return { value: left.value < right.value }
  407. case "<=":
  408. return { value: left.value <= right.value }
  409. case ">":
  410. return { value: left.value > right.value }
  411. case ">=":
  412. return { value: left.value >= right.value }
  413. case "<<":
  414. return { value: left.value << right.value }
  415. case ">>":
  416. return { value: left.value >> right.value }
  417. case ">>>":
  418. return { value: left.value >>> right.value }
  419. case "+":
  420. return { value: left.value + right.value }
  421. case "-":
  422. return { value: left.value - right.value }
  423. case "*":
  424. return { value: left.value * right.value }
  425. case "/":
  426. return { value: left.value / right.value }
  427. case "%":
  428. return { value: left.value % right.value }
  429. case "**":
  430. return { value: left.value ** right.value }
  431. case "|":
  432. return { value: left.value | right.value }
  433. case "^":
  434. return { value: left.value ^ right.value }
  435. case "&":
  436. return { value: left.value & right.value }
  437. // no default
  438. }
  439. }
  440. return null
  441. },
  442. CallExpression(node, initialScope) {
  443. const calleeNode = node.callee;
  444. const args = getElementValues(node.arguments, initialScope);
  445. if (args != null) {
  446. if (calleeNode.type === "MemberExpression") {
  447. if (calleeNode.property.type === "PrivateIdentifier") {
  448. return null
  449. }
  450. const object = getStaticValueR(calleeNode.object, initialScope);
  451. if (object != null) {
  452. if (
  453. object.value == null &&
  454. (object.optional || node.optional)
  455. ) {
  456. return { value: undefined, optional: true }
  457. }
  458. const property = getStaticPropertyNameValue(
  459. calleeNode,
  460. initialScope,
  461. );
  462. if (property != null) {
  463. const receiver = object.value;
  464. const methodName = property.value;
  465. if (callAllowed.has(receiver[methodName])) {
  466. return { value: receiver[methodName](...args) }
  467. }
  468. if (callPassThrough.has(receiver[methodName])) {
  469. return { value: args[0] }
  470. }
  471. }
  472. }
  473. } else {
  474. const callee = getStaticValueR(calleeNode, initialScope);
  475. if (callee != null) {
  476. if (callee.value == null && node.optional) {
  477. return { value: undefined, optional: true }
  478. }
  479. const func = callee.value;
  480. if (callAllowed.has(func)) {
  481. return { value: func(...args) }
  482. }
  483. if (callPassThrough.has(func)) {
  484. return { value: args[0] }
  485. }
  486. }
  487. }
  488. }
  489. return null
  490. },
  491. ConditionalExpression(node, initialScope) {
  492. const test = getStaticValueR(node.test, initialScope);
  493. if (test != null) {
  494. return test.value
  495. ? getStaticValueR(node.consequent, initialScope)
  496. : getStaticValueR(node.alternate, initialScope)
  497. }
  498. return null
  499. },
  500. ExpressionStatement(node, initialScope) {
  501. return getStaticValueR(node.expression, initialScope)
  502. },
  503. Identifier(node, initialScope) {
  504. if (initialScope != null) {
  505. const variable = findVariable(initialScope, node);
  506. // Built-in globals.
  507. if (
  508. variable != null &&
  509. variable.defs.length === 0 &&
  510. builtinNames.has(variable.name) &&
  511. variable.name in globalObject
  512. ) {
  513. return { value: globalObject[variable.name] }
  514. }
  515. // Constants.
  516. if (variable != null && variable.defs.length === 1) {
  517. const def = variable.defs[0];
  518. if (
  519. def.parent &&
  520. def.parent.kind === "const" &&
  521. // TODO(mysticatea): don't support destructuring here.
  522. def.node.id.type === "Identifier"
  523. ) {
  524. return getStaticValueR(def.node.init, initialScope)
  525. }
  526. }
  527. }
  528. return null
  529. },
  530. Literal(node) {
  531. //istanbul ignore if : this is implementation-specific behavior.
  532. if ((node.regex != null || node.bigint != null) && node.value == null) {
  533. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  534. return null
  535. }
  536. return { value: node.value }
  537. },
  538. LogicalExpression(node, initialScope) {
  539. const left = getStaticValueR(node.left, initialScope);
  540. if (left != null) {
  541. if (
  542. (node.operator === "||" && Boolean(left.value) === true) ||
  543. (node.operator === "&&" && Boolean(left.value) === false) ||
  544. (node.operator === "??" && left.value != null)
  545. ) {
  546. return left
  547. }
  548. const right = getStaticValueR(node.right, initialScope);
  549. if (right != null) {
  550. return right
  551. }
  552. }
  553. return null
  554. },
  555. MemberExpression(node, initialScope) {
  556. if (node.property.type === "PrivateIdentifier") {
  557. return null
  558. }
  559. const object = getStaticValueR(node.object, initialScope);
  560. if (object != null) {
  561. if (object.value == null && (object.optional || node.optional)) {
  562. return { value: undefined, optional: true }
  563. }
  564. const property = getStaticPropertyNameValue(node, initialScope);
  565. if (property != null && !isGetter(object.value, property.value)) {
  566. return { value: object.value[property.value] }
  567. }
  568. }
  569. return null
  570. },
  571. ChainExpression(node, initialScope) {
  572. const expression = getStaticValueR(node.expression, initialScope);
  573. if (expression != null) {
  574. return { value: expression.value }
  575. }
  576. return null
  577. },
  578. NewExpression(node, initialScope) {
  579. const callee = getStaticValueR(node.callee, initialScope);
  580. const args = getElementValues(node.arguments, initialScope);
  581. if (callee != null && args != null) {
  582. const Func = callee.value;
  583. if (callAllowed.has(Func)) {
  584. return { value: new Func(...args) }
  585. }
  586. }
  587. return null
  588. },
  589. ObjectExpression(node, initialScope) {
  590. const object = {};
  591. for (const propertyNode of node.properties) {
  592. if (propertyNode.type === "Property") {
  593. if (propertyNode.kind !== "init") {
  594. return null
  595. }
  596. const key = getStaticPropertyNameValue(
  597. propertyNode,
  598. initialScope,
  599. );
  600. const value = getStaticValueR(propertyNode.value, initialScope);
  601. if (key == null || value == null) {
  602. return null
  603. }
  604. object[key.value] = value.value;
  605. } else if (
  606. propertyNode.type === "SpreadElement" ||
  607. propertyNode.type === "ExperimentalSpreadProperty"
  608. ) {
  609. const argument = getStaticValueR(
  610. propertyNode.argument,
  611. initialScope,
  612. );
  613. if (argument == null) {
  614. return null
  615. }
  616. Object.assign(object, argument.value);
  617. } else {
  618. return null
  619. }
  620. }
  621. return { value: object }
  622. },
  623. SequenceExpression(node, initialScope) {
  624. const last = node.expressions[node.expressions.length - 1];
  625. return getStaticValueR(last, initialScope)
  626. },
  627. TaggedTemplateExpression(node, initialScope) {
  628. const tag = getStaticValueR(node.tag, initialScope);
  629. const expressions = getElementValues(
  630. node.quasi.expressions,
  631. initialScope,
  632. );
  633. if (tag != null && expressions != null) {
  634. const func = tag.value;
  635. const strings = node.quasi.quasis.map((q) => q.value.cooked);
  636. strings.raw = node.quasi.quasis.map((q) => q.value.raw);
  637. if (func === String.raw) {
  638. return { value: func(strings, ...expressions) }
  639. }
  640. }
  641. return null
  642. },
  643. TemplateLiteral(node, initialScope) {
  644. const expressions = getElementValues(node.expressions, initialScope);
  645. if (expressions != null) {
  646. let value = node.quasis[0].value.cooked;
  647. for (let i = 0; i < expressions.length; ++i) {
  648. value += expressions[i];
  649. value += node.quasis[i + 1].value.cooked;
  650. }
  651. return { value }
  652. }
  653. return null
  654. },
  655. UnaryExpression(node, initialScope) {
  656. if (node.operator === "delete") {
  657. // Not supported.
  658. return null
  659. }
  660. if (node.operator === "void") {
  661. return { value: undefined }
  662. }
  663. const arg = getStaticValueR(node.argument, initialScope);
  664. if (arg != null) {
  665. switch (node.operator) {
  666. case "-":
  667. return { value: -arg.value }
  668. case "+":
  669. return { value: +arg.value } //eslint-disable-line no-implicit-coercion
  670. case "!":
  671. return { value: !arg.value }
  672. case "~":
  673. return { value: ~arg.value }
  674. case "typeof":
  675. return { value: typeof arg.value }
  676. // no default
  677. }
  678. }
  679. return null
  680. },
  681. });
  682. /**
  683. * Get the value of a given node if it's a static value.
  684. * @param {Node} node The node to get.
  685. * @param {Scope|undefined} initialScope The scope to start finding variable.
  686. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  687. */
  688. function getStaticValueR(node, initialScope) {
  689. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  690. return operations[node.type](node, initialScope)
  691. }
  692. return null
  693. }
  694. /**
  695. * Get the static value of property name from a MemberExpression node or a Property node.
  696. * @param {Node} node The node to get.
  697. * @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.
  698. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the property name of the node, or `null`.
  699. */
  700. function getStaticPropertyNameValue(node, initialScope) {
  701. const nameNode = node.type === "Property" ? node.key : node.property;
  702. if (node.computed) {
  703. return getStaticValueR(nameNode, initialScope)
  704. }
  705. if (nameNode.type === "Identifier") {
  706. return { value: nameNode.name }
  707. }
  708. if (nameNode.type === "Literal") {
  709. if (nameNode.bigint) {
  710. return { value: nameNode.bigint }
  711. }
  712. return { value: String(nameNode.value) }
  713. }
  714. return null
  715. }
  716. /**
  717. * Get the value of a given node if it's a static value.
  718. * @param {Node} node The node to get.
  719. * @param {Scope} [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.
  720. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  721. */
  722. function getStaticValue(node, initialScope = null) {
  723. try {
  724. return getStaticValueR(node, initialScope)
  725. } catch (_error) {
  726. return null
  727. }
  728. }
  729. /**
  730. * Get the value of a given node if it's a literal or a template literal.
  731. * @param {Node} node The node to get.
  732. * @param {Scope} [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.
  733. * @returns {string|null} The value of the node, or `null`.
  734. */
  735. function getStringIfConstant(node, initialScope = null) {
  736. // Handle the literals that the platform doesn't support natively.
  737. if (node && node.type === "Literal" && node.value === null) {
  738. if (node.regex) {
  739. return `/${node.regex.pattern}/${node.regex.flags}`
  740. }
  741. if (node.bigint) {
  742. return node.bigint
  743. }
  744. }
  745. const evaluated = getStaticValue(node, initialScope);
  746. return evaluated && String(evaluated.value)
  747. }
  748. /**
  749. * Get the property name from a MemberExpression node or a Property node.
  750. * @param {Node} node The node to get.
  751. * @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.
  752. * @returns {string|null} The property name of the node.
  753. */
  754. function getPropertyName(node, initialScope) {
  755. switch (node.type) {
  756. case "MemberExpression":
  757. if (node.computed) {
  758. return getStringIfConstant(node.property, initialScope)
  759. }
  760. if (node.property.type === "PrivateIdentifier") {
  761. return null
  762. }
  763. return node.property.name
  764. case "Property":
  765. case "MethodDefinition":
  766. case "PropertyDefinition":
  767. if (node.computed) {
  768. return getStringIfConstant(node.key, initialScope)
  769. }
  770. if (node.key.type === "Literal") {
  771. return String(node.key.value)
  772. }
  773. if (node.key.type === "PrivateIdentifier") {
  774. return null
  775. }
  776. return node.key.name
  777. // no default
  778. }
  779. return null
  780. }
  781. /**
  782. * Get the name and kind of the given function node.
  783. * @param {ASTNode} node - The function node to get.
  784. * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
  785. * @returns {string} The name and kind of the function node.
  786. */
  787. // eslint-disable-next-line complexity
  788. function getFunctionNameWithKind(node, sourceCode) {
  789. const parent = node.parent;
  790. const tokens = [];
  791. const isObjectMethod = parent.type === "Property" && parent.value === node;
  792. const isClassMethod =
  793. parent.type === "MethodDefinition" && parent.value === node;
  794. const isClassFieldMethod =
  795. parent.type === "PropertyDefinition" && parent.value === node;
  796. // Modifiers.
  797. if (isClassMethod || isClassFieldMethod) {
  798. if (parent.static) {
  799. tokens.push("static");
  800. }
  801. if (parent.key.type === "PrivateIdentifier") {
  802. tokens.push("private");
  803. }
  804. }
  805. if (node.async) {
  806. tokens.push("async");
  807. }
  808. if (node.generator) {
  809. tokens.push("generator");
  810. }
  811. // Kinds.
  812. if (isObjectMethod || isClassMethod) {
  813. if (parent.kind === "constructor") {
  814. return "constructor"
  815. }
  816. if (parent.kind === "get") {
  817. tokens.push("getter");
  818. } else if (parent.kind === "set") {
  819. tokens.push("setter");
  820. } else {
  821. tokens.push("method");
  822. }
  823. } else if (isClassFieldMethod) {
  824. tokens.push("method");
  825. } else {
  826. if (node.type === "ArrowFunctionExpression") {
  827. tokens.push("arrow");
  828. }
  829. tokens.push("function");
  830. }
  831. // Names.
  832. if (isObjectMethod || isClassMethod || isClassFieldMethod) {
  833. if (parent.key.type === "PrivateIdentifier") {
  834. tokens.push(`#${parent.key.name}`);
  835. } else {
  836. const name = getPropertyName(parent);
  837. if (name) {
  838. tokens.push(`'${name}'`);
  839. } else if (sourceCode) {
  840. const keyText = sourceCode.getText(parent.key);
  841. if (!keyText.includes("\n")) {
  842. tokens.push(`[${keyText}]`);
  843. }
  844. }
  845. }
  846. } else if (node.id) {
  847. tokens.push(`'${node.id.name}'`);
  848. } else if (
  849. parent.type === "VariableDeclarator" &&
  850. parent.id &&
  851. parent.id.type === "Identifier"
  852. ) {
  853. tokens.push(`'${parent.id.name}'`);
  854. } else if (
  855. (parent.type === "AssignmentExpression" ||
  856. parent.type === "AssignmentPattern") &&
  857. parent.left &&
  858. parent.left.type === "Identifier"
  859. ) {
  860. tokens.push(`'${parent.left.name}'`);
  861. } else if (
  862. parent.type === "ExportDefaultDeclaration" &&
  863. parent.declaration === node
  864. ) {
  865. tokens.push("'default'");
  866. }
  867. return tokens.join(" ")
  868. }
  869. const typeConversionBinaryOps = Object.freeze(
  870. new Set([
  871. "==",
  872. "!=",
  873. "<",
  874. "<=",
  875. ">",
  876. ">=",
  877. "<<",
  878. ">>",
  879. ">>>",
  880. "+",
  881. "-",
  882. "*",
  883. "/",
  884. "%",
  885. "|",
  886. "^",
  887. "&",
  888. "in",
  889. ]),
  890. );
  891. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  892. /**
  893. * Check whether the given value is an ASTNode or not.
  894. * @param {any} x The value to check.
  895. * @returns {boolean} `true` if the value is an ASTNode.
  896. */
  897. function isNode(x) {
  898. return x !== null && typeof x === "object" && typeof x.type === "string"
  899. }
  900. const visitor = Object.freeze(
  901. Object.assign(Object.create(null), {
  902. $visit(node, options, visitorKeys) {
  903. const { type } = node;
  904. if (typeof this[type] === "function") {
  905. return this[type](node, options, visitorKeys)
  906. }
  907. return this.$visitChildren(node, options, visitorKeys)
  908. },
  909. $visitChildren(node, options, visitorKeys) {
  910. const { type } = node;
  911. for (const key of visitorKeys[type] || getKeys(node)) {
  912. const value = node[key];
  913. if (Array.isArray(value)) {
  914. for (const element of value) {
  915. if (
  916. isNode(element) &&
  917. this.$visit(element, options, visitorKeys)
  918. ) {
  919. return true
  920. }
  921. }
  922. } else if (
  923. isNode(value) &&
  924. this.$visit(value, options, visitorKeys)
  925. ) {
  926. return true
  927. }
  928. }
  929. return false
  930. },
  931. ArrowFunctionExpression() {
  932. return false
  933. },
  934. AssignmentExpression() {
  935. return true
  936. },
  937. AwaitExpression() {
  938. return true
  939. },
  940. BinaryExpression(node, options, visitorKeys) {
  941. if (
  942. options.considerImplicitTypeConversion &&
  943. typeConversionBinaryOps.has(node.operator) &&
  944. (node.left.type !== "Literal" || node.right.type !== "Literal")
  945. ) {
  946. return true
  947. }
  948. return this.$visitChildren(node, options, visitorKeys)
  949. },
  950. CallExpression() {
  951. return true
  952. },
  953. FunctionExpression() {
  954. return false
  955. },
  956. ImportExpression() {
  957. return true
  958. },
  959. MemberExpression(node, options, visitorKeys) {
  960. if (options.considerGetters) {
  961. return true
  962. }
  963. if (
  964. options.considerImplicitTypeConversion &&
  965. node.computed &&
  966. node.property.type !== "Literal"
  967. ) {
  968. return true
  969. }
  970. return this.$visitChildren(node, options, visitorKeys)
  971. },
  972. MethodDefinition(node, options, visitorKeys) {
  973. if (
  974. options.considerImplicitTypeConversion &&
  975. node.computed &&
  976. node.key.type !== "Literal"
  977. ) {
  978. return true
  979. }
  980. return this.$visitChildren(node, options, visitorKeys)
  981. },
  982. NewExpression() {
  983. return true
  984. },
  985. Property(node, options, visitorKeys) {
  986. if (
  987. options.considerImplicitTypeConversion &&
  988. node.computed &&
  989. node.key.type !== "Literal"
  990. ) {
  991. return true
  992. }
  993. return this.$visitChildren(node, options, visitorKeys)
  994. },
  995. PropertyDefinition(node, options, visitorKeys) {
  996. if (
  997. options.considerImplicitTypeConversion &&
  998. node.computed &&
  999. node.key.type !== "Literal"
  1000. ) {
  1001. return true
  1002. }
  1003. return this.$visitChildren(node, options, visitorKeys)
  1004. },
  1005. UnaryExpression(node, options, visitorKeys) {
  1006. if (node.operator === "delete") {
  1007. return true
  1008. }
  1009. if (
  1010. options.considerImplicitTypeConversion &&
  1011. typeConversionUnaryOps.has(node.operator) &&
  1012. node.argument.type !== "Literal"
  1013. ) {
  1014. return true
  1015. }
  1016. return this.$visitChildren(node, options, visitorKeys)
  1017. },
  1018. UpdateExpression() {
  1019. return true
  1020. },
  1021. YieldExpression() {
  1022. return true
  1023. },
  1024. }),
  1025. );
  1026. /**
  1027. * Check whether a given node has any side effect or not.
  1028. * @param {Node} node The node to get.
  1029. * @param {SourceCode} sourceCode The source code object.
  1030. * @param {object} [options] The option object.
  1031. * @param {boolean} [options.considerGetters=false] If `true` then it considers member accesses as the node which has side effects.
  1032. * @param {boolean} [options.considerImplicitTypeConversion=false] If `true` then it considers implicit type conversion as the node which has side effects.
  1033. * @param {object} [options.visitorKeys=KEYS] The keys to traverse nodes. Use `context.getSourceCode().visitorKeys`.
  1034. * @returns {boolean} `true` if the node has a certain side effect.
  1035. */
  1036. function hasSideEffect(
  1037. node,
  1038. sourceCode,
  1039. { considerGetters = false, considerImplicitTypeConversion = false } = {},
  1040. ) {
  1041. return visitor.$visit(
  1042. node,
  1043. { considerGetters, considerImplicitTypeConversion },
  1044. sourceCode.visitorKeys || KEYS,
  1045. )
  1046. }
  1047. /**
  1048. * Get the left parenthesis of the parent node syntax if it exists.
  1049. * E.g., `if (a) {}` then the `(`.
  1050. * @param {Node} node The AST node to check.
  1051. * @param {SourceCode} sourceCode The source code object to get tokens.
  1052. * @returns {Token|null} The left parenthesis of the parent node syntax
  1053. */
  1054. function getParentSyntaxParen(node, sourceCode) {
  1055. const parent = node.parent;
  1056. switch (parent.type) {
  1057. case "CallExpression":
  1058. case "NewExpression":
  1059. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  1060. return sourceCode.getTokenAfter(
  1061. parent.callee,
  1062. isOpeningParenToken,
  1063. )
  1064. }
  1065. return null
  1066. case "DoWhileStatement":
  1067. if (parent.test === node) {
  1068. return sourceCode.getTokenAfter(
  1069. parent.body,
  1070. isOpeningParenToken,
  1071. )
  1072. }
  1073. return null
  1074. case "IfStatement":
  1075. case "WhileStatement":
  1076. if (parent.test === node) {
  1077. return sourceCode.getFirstToken(parent, 1)
  1078. }
  1079. return null
  1080. case "ImportExpression":
  1081. if (parent.source === node) {
  1082. return sourceCode.getFirstToken(parent, 1)
  1083. }
  1084. return null
  1085. case "SwitchStatement":
  1086. if (parent.discriminant === node) {
  1087. return sourceCode.getFirstToken(parent, 1)
  1088. }
  1089. return null
  1090. case "WithStatement":
  1091. if (parent.object === node) {
  1092. return sourceCode.getFirstToken(parent, 1)
  1093. }
  1094. return null
  1095. default:
  1096. return null
  1097. }
  1098. }
  1099. /**
  1100. * Check whether a given node is parenthesized or not.
  1101. * @param {number} times The number of parantheses.
  1102. * @param {Node} node The AST node to check.
  1103. * @param {SourceCode} sourceCode The source code object to get tokens.
  1104. * @returns {boolean} `true` if the node is parenthesized the given times.
  1105. */
  1106. /**
  1107. * Check whether a given node is parenthesized or not.
  1108. * @param {Node} node The AST node to check.
  1109. * @param {SourceCode} sourceCode The source code object to get tokens.
  1110. * @returns {boolean} `true` if the node is parenthesized.
  1111. */
  1112. function isParenthesized(
  1113. timesOrNode,
  1114. nodeOrSourceCode,
  1115. optionalSourceCode,
  1116. ) {
  1117. let times, node, sourceCode, maybeLeftParen, maybeRightParen;
  1118. if (typeof timesOrNode === "number") {
  1119. times = timesOrNode | 0;
  1120. node = nodeOrSourceCode;
  1121. sourceCode = optionalSourceCode;
  1122. if (!(times >= 1)) {
  1123. throw new TypeError("'times' should be a positive integer.")
  1124. }
  1125. } else {
  1126. times = 1;
  1127. node = timesOrNode;
  1128. sourceCode = nodeOrSourceCode;
  1129. }
  1130. if (
  1131. node == null ||
  1132. // `Program` can't be parenthesized
  1133. node.parent == null ||
  1134. // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
  1135. (node.parent.type === "CatchClause" && node.parent.param === node)
  1136. ) {
  1137. return false
  1138. }
  1139. maybeLeftParen = maybeRightParen = node;
  1140. do {
  1141. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1142. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1143. } while (
  1144. maybeLeftParen != null &&
  1145. maybeRightParen != null &&
  1146. isOpeningParenToken(maybeLeftParen) &&
  1147. isClosingParenToken(maybeRightParen) &&
  1148. // Avoid false positive such as `if (a) {}`
  1149. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1150. --times > 0
  1151. )
  1152. return times === 0
  1153. }
  1154. /**
  1155. * @author Toru Nagashima <https://github.com/mysticatea>
  1156. * See LICENSE file in root directory for full license.
  1157. */
  1158. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1159. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1160. const internal = new WeakMap();
  1161. /**
  1162. * Check whether a given character is escaped or not.
  1163. * @param {string} str The string to check.
  1164. * @param {number} index The location of the character to check.
  1165. * @returns {boolean} `true` if the character is escaped.
  1166. */
  1167. function isEscaped(str, index) {
  1168. let escaped = false;
  1169. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1170. escaped = !escaped;
  1171. }
  1172. return escaped
  1173. }
  1174. /**
  1175. * Replace a given string by a given matcher.
  1176. * @param {PatternMatcher} matcher The pattern matcher.
  1177. * @param {string} str The string to be replaced.
  1178. * @param {string} replacement The new substring to replace each matched part.
  1179. * @returns {string} The replaced string.
  1180. */
  1181. function replaceS(matcher, str, replacement) {
  1182. const chunks = [];
  1183. let index = 0;
  1184. /** @type {RegExpExecArray} */
  1185. let match = null;
  1186. /**
  1187. * @param {string} key The placeholder.
  1188. * @returns {string} The replaced string.
  1189. */
  1190. function replacer(key) {
  1191. switch (key) {
  1192. case "$$":
  1193. return "$"
  1194. case "$&":
  1195. return match[0]
  1196. case "$`":
  1197. return str.slice(0, match.index)
  1198. case "$'":
  1199. return str.slice(match.index + match[0].length)
  1200. default: {
  1201. const i = key.slice(1);
  1202. if (i in match) {
  1203. return match[i]
  1204. }
  1205. return key
  1206. }
  1207. }
  1208. }
  1209. for (match of matcher.execAll(str)) {
  1210. chunks.push(str.slice(index, match.index));
  1211. chunks.push(replacement.replace(placeholder, replacer));
  1212. index = match.index + match[0].length;
  1213. }
  1214. chunks.push(str.slice(index));
  1215. return chunks.join("")
  1216. }
  1217. /**
  1218. * Replace a given string by a given matcher.
  1219. * @param {PatternMatcher} matcher The pattern matcher.
  1220. * @param {string} str The string to be replaced.
  1221. * @param {(...strs[])=>string} replace The function to replace each matched part.
  1222. * @returns {string} The replaced string.
  1223. */
  1224. function replaceF(matcher, str, replace) {
  1225. const chunks = [];
  1226. let index = 0;
  1227. for (const match of matcher.execAll(str)) {
  1228. chunks.push(str.slice(index, match.index));
  1229. chunks.push(String(replace(...match, match.index, match.input)));
  1230. index = match.index + match[0].length;
  1231. }
  1232. chunks.push(str.slice(index));
  1233. return chunks.join("")
  1234. }
  1235. /**
  1236. * The class to find patterns as considering escape sequences.
  1237. */
  1238. class PatternMatcher {
  1239. /**
  1240. * Initialize this matcher.
  1241. * @param {RegExp} pattern The pattern to match.
  1242. * @param {{escaped:boolean}} options The options.
  1243. */
  1244. constructor(pattern, { escaped = false } = {}) {
  1245. if (!(pattern instanceof RegExp)) {
  1246. throw new TypeError("'pattern' should be a RegExp instance.")
  1247. }
  1248. if (!pattern.flags.includes("g")) {
  1249. throw new Error("'pattern' should contains 'g' flag.")
  1250. }
  1251. internal.set(this, {
  1252. pattern: new RegExp(pattern.source, pattern.flags),
  1253. escaped: Boolean(escaped),
  1254. });
  1255. }
  1256. /**
  1257. * Find the pattern in a given string.
  1258. * @param {string} str The string to find.
  1259. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1260. */
  1261. *execAll(str) {
  1262. const { pattern, escaped } = internal.get(this);
  1263. let match = null;
  1264. let lastIndex = 0;
  1265. pattern.lastIndex = 0;
  1266. while ((match = pattern.exec(str)) != null) {
  1267. if (escaped || !isEscaped(str, match.index)) {
  1268. lastIndex = pattern.lastIndex;
  1269. yield match;
  1270. pattern.lastIndex = lastIndex;
  1271. }
  1272. }
  1273. }
  1274. /**
  1275. * Check whether the pattern is found in a given string.
  1276. * @param {string} str The string to check.
  1277. * @returns {boolean} `true` if the pattern was found in the string.
  1278. */
  1279. test(str) {
  1280. const it = this.execAll(str);
  1281. const ret = it.next();
  1282. return !ret.done
  1283. }
  1284. /**
  1285. * Replace a given string.
  1286. * @param {string} str The string to be replaced.
  1287. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1288. * @returns {string} The replaced string.
  1289. */
  1290. [Symbol.replace](str, replacer) {
  1291. return typeof replacer === "function"
  1292. ? replaceF(this, String(str), replacer)
  1293. : replaceS(this, String(str), String(replacer))
  1294. }
  1295. }
  1296. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1297. const has = Function.call.bind(Object.hasOwnProperty);
  1298. const READ = Symbol("read");
  1299. const CALL = Symbol("call");
  1300. const CONSTRUCT = Symbol("construct");
  1301. const ESM = Symbol("esm");
  1302. const requireCall = { require: { [CALL]: true } };
  1303. /**
  1304. * Check whether a given variable is modified or not.
  1305. * @param {Variable} variable The variable to check.
  1306. * @returns {boolean} `true` if the variable is modified.
  1307. */
  1308. function isModifiedGlobal(variable) {
  1309. return (
  1310. variable == null ||
  1311. variable.defs.length !== 0 ||
  1312. variable.references.some((r) => r.isWrite())
  1313. )
  1314. }
  1315. /**
  1316. * Check if the value of a given node is passed through to the parent syntax as-is.
  1317. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1318. * @param {Node} node A node to check.
  1319. * @returns {boolean} `true` if the node is passed through.
  1320. */
  1321. function isPassThrough(node) {
  1322. const parent = node.parent;
  1323. switch (parent && parent.type) {
  1324. case "ConditionalExpression":
  1325. return parent.consequent === node || parent.alternate === node
  1326. case "LogicalExpression":
  1327. return true
  1328. case "SequenceExpression":
  1329. return parent.expressions[parent.expressions.length - 1] === node
  1330. case "ChainExpression":
  1331. return true
  1332. default:
  1333. return false
  1334. }
  1335. }
  1336. /**
  1337. * The reference tracker.
  1338. */
  1339. class ReferenceTracker {
  1340. /**
  1341. * Initialize this tracker.
  1342. * @param {Scope} globalScope The global scope.
  1343. * @param {object} [options] The options.
  1344. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1345. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
  1346. */
  1347. constructor(
  1348. globalScope,
  1349. {
  1350. mode = "strict",
  1351. globalObjectNames = ["global", "globalThis", "self", "window"],
  1352. } = {},
  1353. ) {
  1354. this.variableStack = [];
  1355. this.globalScope = globalScope;
  1356. this.mode = mode;
  1357. this.globalObjectNames = globalObjectNames.slice(0);
  1358. }
  1359. /**
  1360. * Iterate the references of global variables.
  1361. * @param {object} traceMap The trace map.
  1362. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1363. */
  1364. *iterateGlobalReferences(traceMap) {
  1365. for (const key of Object.keys(traceMap)) {
  1366. const nextTraceMap = traceMap[key];
  1367. const path = [key];
  1368. const variable = this.globalScope.set.get(key);
  1369. if (isModifiedGlobal(variable)) {
  1370. continue
  1371. }
  1372. yield* this._iterateVariableReferences(
  1373. variable,
  1374. path,
  1375. nextTraceMap,
  1376. true,
  1377. );
  1378. }
  1379. for (const key of this.globalObjectNames) {
  1380. const path = [];
  1381. const variable = this.globalScope.set.get(key);
  1382. if (isModifiedGlobal(variable)) {
  1383. continue
  1384. }
  1385. yield* this._iterateVariableReferences(
  1386. variable,
  1387. path,
  1388. traceMap,
  1389. false,
  1390. );
  1391. }
  1392. }
  1393. /**
  1394. * Iterate the references of CommonJS modules.
  1395. * @param {object} traceMap The trace map.
  1396. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1397. */
  1398. *iterateCjsReferences(traceMap) {
  1399. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1400. const key = getStringIfConstant(node.arguments[0]);
  1401. if (key == null || !has(traceMap, key)) {
  1402. continue
  1403. }
  1404. const nextTraceMap = traceMap[key];
  1405. const path = [key];
  1406. if (nextTraceMap[READ]) {
  1407. yield {
  1408. node,
  1409. path,
  1410. type: READ,
  1411. info: nextTraceMap[READ],
  1412. };
  1413. }
  1414. yield* this._iteratePropertyReferences(node, path, nextTraceMap);
  1415. }
  1416. }
  1417. /**
  1418. * Iterate the references of ES modules.
  1419. * @param {object} traceMap The trace map.
  1420. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1421. */
  1422. *iterateEsmReferences(traceMap) {
  1423. const programNode = this.globalScope.block;
  1424. for (const node of programNode.body) {
  1425. if (!IMPORT_TYPE.test(node.type) || node.source == null) {
  1426. continue
  1427. }
  1428. const moduleId = node.source.value;
  1429. if (!has(traceMap, moduleId)) {
  1430. continue
  1431. }
  1432. const nextTraceMap = traceMap[moduleId];
  1433. const path = [moduleId];
  1434. if (nextTraceMap[READ]) {
  1435. yield { node, path, type: READ, info: nextTraceMap[READ] };
  1436. }
  1437. if (node.type === "ExportAllDeclaration") {
  1438. for (const key of Object.keys(nextTraceMap)) {
  1439. const exportTraceMap = nextTraceMap[key];
  1440. if (exportTraceMap[READ]) {
  1441. yield {
  1442. node,
  1443. path: path.concat(key),
  1444. type: READ,
  1445. info: exportTraceMap[READ],
  1446. };
  1447. }
  1448. }
  1449. } else {
  1450. for (const specifier of node.specifiers) {
  1451. const esm = has(nextTraceMap, ESM);
  1452. const it = this._iterateImportReferences(
  1453. specifier,
  1454. path,
  1455. esm
  1456. ? nextTraceMap
  1457. : this.mode === "legacy"
  1458. ? { default: nextTraceMap, ...nextTraceMap }
  1459. : { default: nextTraceMap },
  1460. );
  1461. if (esm) {
  1462. yield* it;
  1463. } else {
  1464. for (const report of it) {
  1465. report.path = report.path.filter(exceptDefault);
  1466. if (
  1467. report.path.length >= 2 ||
  1468. report.type !== READ
  1469. ) {
  1470. yield report;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. }
  1477. }
  1478. /**
  1479. * Iterate the references for a given variable.
  1480. * @param {Variable} variable The variable to iterate that references.
  1481. * @param {string[]} path The current path.
  1482. * @param {object} traceMap The trace map.
  1483. * @param {boolean} shouldReport = The flag to report those references.
  1484. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1485. */
  1486. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  1487. if (this.variableStack.includes(variable)) {
  1488. return
  1489. }
  1490. this.variableStack.push(variable);
  1491. try {
  1492. for (const reference of variable.references) {
  1493. if (!reference.isRead()) {
  1494. continue
  1495. }
  1496. const node = reference.identifier;
  1497. if (shouldReport && traceMap[READ]) {
  1498. yield { node, path, type: READ, info: traceMap[READ] };
  1499. }
  1500. yield* this._iteratePropertyReferences(node, path, traceMap);
  1501. }
  1502. } finally {
  1503. this.variableStack.pop();
  1504. }
  1505. }
  1506. /**
  1507. * Iterate the references for a given AST node.
  1508. * @param rootNode The AST node to iterate references.
  1509. * @param {string[]} path The current path.
  1510. * @param {object} traceMap The trace map.
  1511. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1512. */
  1513. //eslint-disable-next-line complexity
  1514. *_iteratePropertyReferences(rootNode, path, traceMap) {
  1515. let node = rootNode;
  1516. while (isPassThrough(node)) {
  1517. node = node.parent;
  1518. }
  1519. const parent = node.parent;
  1520. if (parent.type === "MemberExpression") {
  1521. if (parent.object === node) {
  1522. const key = getPropertyName(parent);
  1523. if (key == null || !has(traceMap, key)) {
  1524. return
  1525. }
  1526. path = path.concat(key); //eslint-disable-line no-param-reassign
  1527. const nextTraceMap = traceMap[key];
  1528. if (nextTraceMap[READ]) {
  1529. yield {
  1530. node: parent,
  1531. path,
  1532. type: READ,
  1533. info: nextTraceMap[READ],
  1534. };
  1535. }
  1536. yield* this._iteratePropertyReferences(
  1537. parent,
  1538. path,
  1539. nextTraceMap,
  1540. );
  1541. }
  1542. return
  1543. }
  1544. if (parent.type === "CallExpression") {
  1545. if (parent.callee === node && traceMap[CALL]) {
  1546. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  1547. }
  1548. return
  1549. }
  1550. if (parent.type === "NewExpression") {
  1551. if (parent.callee === node && traceMap[CONSTRUCT]) {
  1552. yield {
  1553. node: parent,
  1554. path,
  1555. type: CONSTRUCT,
  1556. info: traceMap[CONSTRUCT],
  1557. };
  1558. }
  1559. return
  1560. }
  1561. if (parent.type === "AssignmentExpression") {
  1562. if (parent.right === node) {
  1563. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1564. yield* this._iteratePropertyReferences(parent, path, traceMap);
  1565. }
  1566. return
  1567. }
  1568. if (parent.type === "AssignmentPattern") {
  1569. if (parent.right === node) {
  1570. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1571. }
  1572. return
  1573. }
  1574. if (parent.type === "VariableDeclarator") {
  1575. if (parent.init === node) {
  1576. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  1577. }
  1578. }
  1579. }
  1580. /**
  1581. * Iterate the references for a given Pattern node.
  1582. * @param {Node} patternNode The Pattern node to iterate references.
  1583. * @param {string[]} path The current path.
  1584. * @param {object} traceMap The trace map.
  1585. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1586. */
  1587. *_iterateLhsReferences(patternNode, path, traceMap) {
  1588. if (patternNode.type === "Identifier") {
  1589. const variable = findVariable(this.globalScope, patternNode);
  1590. if (variable != null) {
  1591. yield* this._iterateVariableReferences(
  1592. variable,
  1593. path,
  1594. traceMap,
  1595. false,
  1596. );
  1597. }
  1598. return
  1599. }
  1600. if (patternNode.type === "ObjectPattern") {
  1601. for (const property of patternNode.properties) {
  1602. const key = getPropertyName(property);
  1603. if (key == null || !has(traceMap, key)) {
  1604. continue
  1605. }
  1606. const nextPath = path.concat(key);
  1607. const nextTraceMap = traceMap[key];
  1608. if (nextTraceMap[READ]) {
  1609. yield {
  1610. node: property,
  1611. path: nextPath,
  1612. type: READ,
  1613. info: nextTraceMap[READ],
  1614. };
  1615. }
  1616. yield* this._iterateLhsReferences(
  1617. property.value,
  1618. nextPath,
  1619. nextTraceMap,
  1620. );
  1621. }
  1622. return
  1623. }
  1624. if (patternNode.type === "AssignmentPattern") {
  1625. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  1626. }
  1627. }
  1628. /**
  1629. * Iterate the references for a given ModuleSpecifier node.
  1630. * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
  1631. * @param {string[]} path The current path.
  1632. * @param {object} traceMap The trace map.
  1633. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1634. */
  1635. *_iterateImportReferences(specifierNode, path, traceMap) {
  1636. const type = specifierNode.type;
  1637. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  1638. const key =
  1639. type === "ImportDefaultSpecifier"
  1640. ? "default"
  1641. : specifierNode.imported.name;
  1642. if (!has(traceMap, key)) {
  1643. return
  1644. }
  1645. path = path.concat(key); //eslint-disable-line no-param-reassign
  1646. const nextTraceMap = traceMap[key];
  1647. if (nextTraceMap[READ]) {
  1648. yield {
  1649. node: specifierNode,
  1650. path,
  1651. type: READ,
  1652. info: nextTraceMap[READ],
  1653. };
  1654. }
  1655. yield* this._iterateVariableReferences(
  1656. findVariable(this.globalScope, specifierNode.local),
  1657. path,
  1658. nextTraceMap,
  1659. false,
  1660. );
  1661. return
  1662. }
  1663. if (type === "ImportNamespaceSpecifier") {
  1664. yield* this._iterateVariableReferences(
  1665. findVariable(this.globalScope, specifierNode.local),
  1666. path,
  1667. traceMap,
  1668. false,
  1669. );
  1670. return
  1671. }
  1672. if (type === "ExportSpecifier") {
  1673. const key = specifierNode.local.name;
  1674. if (!has(traceMap, key)) {
  1675. return
  1676. }
  1677. path = path.concat(key); //eslint-disable-line no-param-reassign
  1678. const nextTraceMap = traceMap[key];
  1679. if (nextTraceMap[READ]) {
  1680. yield {
  1681. node: specifierNode,
  1682. path,
  1683. type: READ,
  1684. info: nextTraceMap[READ],
  1685. };
  1686. }
  1687. }
  1688. }
  1689. }
  1690. ReferenceTracker.READ = READ;
  1691. ReferenceTracker.CALL = CALL;
  1692. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  1693. ReferenceTracker.ESM = ESM;
  1694. /**
  1695. * This is a predicate function for Array#filter.
  1696. * @param {string} name A name part.
  1697. * @param {number} index The index of the name.
  1698. * @returns {boolean} `false` if it's default.
  1699. */
  1700. function exceptDefault(name, index) {
  1701. return !(index === 1 && name === "default")
  1702. }
  1703. var index = {
  1704. CALL,
  1705. CONSTRUCT,
  1706. ESM,
  1707. findVariable,
  1708. getFunctionHeadLocation,
  1709. getFunctionNameWithKind,
  1710. getInnermostScope,
  1711. getPropertyName,
  1712. getStaticValue,
  1713. getStringIfConstant,
  1714. hasSideEffect,
  1715. isArrowToken,
  1716. isClosingBraceToken,
  1717. isClosingBracketToken,
  1718. isClosingParenToken,
  1719. isColonToken,
  1720. isCommaToken,
  1721. isCommentToken,
  1722. isNotArrowToken,
  1723. isNotClosingBraceToken,
  1724. isNotClosingBracketToken,
  1725. isNotClosingParenToken,
  1726. isNotColonToken,
  1727. isNotCommaToken,
  1728. isNotCommentToken,
  1729. isNotOpeningBraceToken,
  1730. isNotOpeningBracketToken,
  1731. isNotOpeningParenToken,
  1732. isNotSemicolonToken,
  1733. isOpeningBraceToken,
  1734. isOpeningBracketToken,
  1735. isOpeningParenToken,
  1736. isParenthesized,
  1737. isSemicolonToken,
  1738. PatternMatcher,
  1739. READ,
  1740. ReferenceTracker,
  1741. };
  1742. 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 };
  1743. //# sourceMappingURL=index.mjs.map