index.js 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. const { getScope } = require('./scope')
  8. /**
  9. * @typedef {import('eslint').Rule.RuleModule} RuleModule
  10. * @typedef {import('estree').Position} Position
  11. * @typedef {import('eslint').Rule.CodePath} CodePath
  12. * @typedef {import('eslint').Rule.CodePathSegment} CodePathSegment
  13. */
  14. /**
  15. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayProp} ComponentArrayProp
  16. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectProp} ComponentObjectProp
  17. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeProp} ComponentTypeProp
  18. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeProp} ComponentInferTypeProp
  19. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownProp} ComponentUnknownProp
  20. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentProp} ComponentProp
  21. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayEmit} ComponentArrayEmit
  22. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectEmit} ComponentObjectEmit
  23. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeEmit} ComponentTypeEmit
  24. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeEmit} ComponentInferTypeEmit
  25. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownEmit} ComponentUnknownEmit
  26. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentEmit} ComponentEmit
  27. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeSlot} ComponentTypeSlot
  28. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeSlot} ComponentInferTypeSlot
  29. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownSlot} ComponentUnknownSlot
  30. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentSlot} ComponentSlot
  31. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModelName} ComponentModelName
  32. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModel} ComponentModel
  33. */
  34. /**
  35. * @typedef { {key: string | null, value: BlockStatement | null} } ComponentComputedProperty
  36. */
  37. /**
  38. * @typedef { 'props' | 'asyncData' | 'data' | 'computed' | 'setup' | 'watch' | 'methods' | 'provide' | 'inject' | 'expose' } GroupName
  39. * @typedef { { type: 'array', name: string, groupName: GroupName, node: Literal | TemplateLiteral } } ComponentArrayPropertyData
  40. * @typedef { { type: 'object', name: string, groupName: GroupName, node: Identifier | Literal | TemplateLiteral, property: Property } } ComponentObjectPropertyData
  41. * @typedef { ComponentArrayPropertyData | ComponentObjectPropertyData } ComponentPropertyData
  42. */
  43. /**
  44. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectType} VueObjectType
  45. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectData} VueObjectData
  46. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueVisitor} VueVisitor
  47. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ScriptSetupVisitor} ScriptSetupVisitor
  48. */
  49. // ------------------------------------------------------------------------------
  50. // Helpers
  51. // ------------------------------------------------------------------------------
  52. const HTML_ELEMENT_NAMES = new Set(require('./html-elements.json'))
  53. const SVG_ELEMENT_NAMES = new Set(require('./svg-elements.json'))
  54. const MATH_ELEMENT_NAMES = new Set(require('./math-elements.json'))
  55. const VOID_ELEMENT_NAMES = new Set(require('./void-elements.json'))
  56. const VUE2_BUILTIN_COMPONENT_NAMES = new Set(
  57. require('./vue2-builtin-components')
  58. )
  59. const VUE3_BUILTIN_COMPONENT_NAMES = new Set(
  60. require('./vue3-builtin-components')
  61. )
  62. const VUE_BUILTIN_ELEMENT_NAMES = new Set(require('./vue-builtin-elements'))
  63. const path = require('path')
  64. const vueEslintParser = require('vue-eslint-parser')
  65. const { traverseNodes, getFallbackKeys, NS } = vueEslintParser.AST
  66. const {
  67. findVariable,
  68. ReferenceTracker
  69. } = require('@eslint-community/eslint-utils')
  70. const {
  71. getComponentPropsFromTypeDefine,
  72. getComponentEmitsFromTypeDefine,
  73. getComponentSlotsFromTypeDefine,
  74. isTypeNode
  75. } = require('./ts-utils')
  76. /**
  77. * @type { WeakMap<RuleContext, Token[]> }
  78. */
  79. const componentComments = new WeakMap()
  80. /** @type { Map<string, RuleModule> | null } */
  81. let coreRuleMap = null
  82. /** @type { Map<string, RuleModule> } */
  83. const stylisticRuleMap = new Map()
  84. /**
  85. * Get the core rule implementation from the rule name
  86. * @param {string} name
  87. * @returns {RuleModule | null}
  88. */
  89. function getCoreRule(name) {
  90. const eslint = require('eslint')
  91. try {
  92. const map = coreRuleMap || (coreRuleMap = new eslint.Linter().getRules())
  93. return map.get(name) || null
  94. } catch {
  95. // getRules() is no longer available in flat config.
  96. }
  97. const { builtinRules } = require('eslint/use-at-your-own-risk')
  98. return /** @type {any} */ (builtinRules.get(name) || null)
  99. }
  100. /**
  101. * Get ESLint Stylistic rule implementation from the rule name
  102. * @param {string} name
  103. * @param {'@stylistic/eslint-plugin' | '@stylistic/eslint-plugin-ts' | '@stylistic/eslint-plugin-js'} [preferModule]
  104. * @returns {RuleModule | null}
  105. */
  106. function getStylisticRule(name, preferModule) {
  107. if (!preferModule) {
  108. const cached = stylisticRuleMap.get(name)
  109. if (cached) {
  110. return cached
  111. }
  112. }
  113. const stylisticPluginNames = [
  114. '@stylistic/eslint-plugin',
  115. '@stylistic/eslint-plugin-ts',
  116. '@stylistic/eslint-plugin-js'
  117. ]
  118. if (preferModule) {
  119. stylisticPluginNames.unshift(preferModule)
  120. }
  121. for (const stylisticPluginName of stylisticPluginNames) {
  122. try {
  123. const plugin = createRequire(`${process.cwd()}/__placeholder__.js`)(
  124. stylisticPluginName
  125. )
  126. const rule = plugin?.rules?.[name]
  127. if (!preferModule) stylisticRuleMap.set(name, rule)
  128. return rule
  129. } catch {
  130. // ignore
  131. }
  132. }
  133. return null
  134. }
  135. /**
  136. * @template {object} T
  137. * @param {T} target
  138. * @param {Partial<T>[]} propsArray
  139. * @returns {T}
  140. */
  141. function newProxy(target, ...propsArray) {
  142. const result = new Proxy(
  143. {},
  144. {
  145. get(_object, key) {
  146. for (const props of propsArray) {
  147. if (key in props) {
  148. // @ts-expect-error
  149. return props[key]
  150. }
  151. }
  152. // @ts-expect-error
  153. return target[key]
  154. },
  155. has(_object, key) {
  156. return key in target
  157. },
  158. ownKeys(_object) {
  159. return Reflect.ownKeys(target)
  160. },
  161. getPrototypeOf(_object) {
  162. return Reflect.getPrototypeOf(target)
  163. }
  164. }
  165. )
  166. return /** @type {T} */ (result)
  167. }
  168. /**
  169. * Wrap the rule context object to override methods which access to tokens (such as getTokenAfter).
  170. * @param {RuleContext} context The rule context object.
  171. * @param {ParserServices.TokenStore} tokenStore The token store object for template.
  172. * @param {Object} options The option of this rule.
  173. * @param {boolean} [options.applyDocument] If `true`, apply check to document fragment.
  174. * @returns {RuleContext}
  175. */
  176. function wrapContextToOverrideTokenMethods(context, tokenStore, options) {
  177. const eslintSourceCode = context.getSourceCode()
  178. const rootNode = options.applyDocument
  179. ? eslintSourceCode.parserServices.getDocumentFragment &&
  180. eslintSourceCode.parserServices.getDocumentFragment()
  181. : eslintSourceCode.ast.templateBody
  182. /** @type {Token[] | null} */
  183. let tokensAndComments = null
  184. function getTokensAndComments() {
  185. if (tokensAndComments) {
  186. return tokensAndComments
  187. }
  188. tokensAndComments = rootNode
  189. ? tokenStore.getTokens(rootNode, {
  190. includeComments: true
  191. })
  192. : []
  193. return tokensAndComments
  194. }
  195. /** @param {number} index */
  196. function getNodeByRangeIndex(index) {
  197. if (!rootNode) {
  198. return eslintSourceCode.ast
  199. }
  200. /** @type {ASTNode} */
  201. let result = eslintSourceCode.ast
  202. /** @type {ASTNode[]} */
  203. const skipNodes = []
  204. let breakFlag = false
  205. traverseNodes(rootNode, {
  206. enterNode(node, parent) {
  207. if (breakFlag) {
  208. return
  209. }
  210. if (skipNodes[0] === parent) {
  211. skipNodes.unshift(node)
  212. return
  213. }
  214. if (node.range[0] <= index && index < node.range[1]) {
  215. result = node
  216. } else {
  217. skipNodes.unshift(node)
  218. }
  219. },
  220. leaveNode(node) {
  221. if (breakFlag) {
  222. return
  223. }
  224. if (result === node) {
  225. breakFlag = true
  226. } else if (skipNodes[0] === node) {
  227. skipNodes.shift()
  228. }
  229. }
  230. })
  231. return result
  232. }
  233. const sourceCode = newProxy(
  234. eslintSourceCode,
  235. {
  236. get tokensAndComments() {
  237. return getTokensAndComments()
  238. },
  239. getNodeByRangeIndex,
  240. // @ts-expect-error -- Added in ESLint v8.38.0
  241. getDeclaredVariables
  242. },
  243. tokenStore
  244. )
  245. /** @type {WeakMap<ASTNode, import('eslint').Scope.ScopeManager>} */
  246. const containerScopes = new WeakMap()
  247. /**
  248. * @param {ASTNode} node
  249. * @returns {import('eslint').Scope.ScopeManager|null}
  250. */
  251. function getContainerScope(node) {
  252. const exprContainer = getVExpressionContainer(node)
  253. if (!exprContainer) {
  254. return null
  255. }
  256. const cache = containerScopes.get(exprContainer)
  257. if (cache) {
  258. return cache
  259. }
  260. const programNode = eslintSourceCode.ast
  261. const parserOptions =
  262. context.languageOptions?.parserOptions ?? context.parserOptions ?? {}
  263. const ecmaFeatures = parserOptions.ecmaFeatures || {}
  264. const ecmaVersion =
  265. context.languageOptions?.ecmaVersion ?? parserOptions.ecmaVersion ?? 2020
  266. const sourceType = programNode.sourceType
  267. try {
  268. const eslintScope = createRequire(require.resolve('eslint'))(
  269. 'eslint-scope'
  270. )
  271. const expStmt = newProxy(exprContainer, {
  272. // @ts-expect-error
  273. type: 'ExpressionStatement'
  274. })
  275. const scopeProgram = newProxy(programNode, {
  276. // @ts-expect-error
  277. body: [expStmt]
  278. })
  279. const scope = eslintScope.analyze(scopeProgram, {
  280. ignoreEval: true,
  281. nodejsScope: false,
  282. impliedStrict: ecmaFeatures.impliedStrict,
  283. ecmaVersion,
  284. sourceType,
  285. fallback: getFallbackKeys
  286. })
  287. containerScopes.set(exprContainer, scope)
  288. return scope
  289. } catch (error) {
  290. // ignore
  291. // console.log(error)
  292. }
  293. return null
  294. }
  295. return newProxy(context, {
  296. getSourceCode() {
  297. return sourceCode
  298. },
  299. get sourceCode() {
  300. return sourceCode
  301. },
  302. getDeclaredVariables
  303. })
  304. /**
  305. * @param {ESNode} node
  306. * @returns {Variable[]}
  307. */
  308. function getDeclaredVariables(node) {
  309. const scope = getContainerScope(node)
  310. return (
  311. scope?.getDeclaredVariables?.(node) ??
  312. context.getDeclaredVariables?.(node) ??
  313. []
  314. )
  315. }
  316. }
  317. /**
  318. * Wrap the rule context object to override report method to skip the dynamic argument.
  319. * @param {RuleContext} context The rule context object.
  320. * @returns {RuleContext}
  321. */
  322. function wrapContextToOverrideReportMethodToSkipDynamicArgument(context) {
  323. const sourceCode = context.getSourceCode()
  324. const templateBody = sourceCode.ast.templateBody
  325. if (!templateBody) {
  326. return context
  327. }
  328. /** @type {Range[]} */
  329. const directiveKeyRanges = []
  330. traverseNodes(templateBody, {
  331. enterNode(node, parent) {
  332. if (
  333. parent &&
  334. parent.type === 'VDirectiveKey' &&
  335. node.type === 'VExpressionContainer'
  336. ) {
  337. directiveKeyRanges.push(node.range)
  338. }
  339. },
  340. leaveNode() {}
  341. })
  342. return newProxy(context, {
  343. report(descriptor, ...args) {
  344. let range = null
  345. if (descriptor.loc) {
  346. const startLoc = descriptor.loc.start || descriptor.loc
  347. const endLoc = descriptor.loc.end || startLoc
  348. range = [
  349. sourceCode.getIndexFromLoc(startLoc),
  350. sourceCode.getIndexFromLoc(endLoc)
  351. ]
  352. } else if (descriptor.node) {
  353. range = descriptor.node.range
  354. }
  355. if (range) {
  356. for (const directiveKeyRange of directiveKeyRanges) {
  357. if (
  358. range[0] < directiveKeyRange[1] &&
  359. directiveKeyRange[0] < range[1]
  360. ) {
  361. return
  362. }
  363. }
  364. }
  365. context.report(descriptor, ...args)
  366. }
  367. })
  368. }
  369. /**
  370. * @callback WrapRuleCreate
  371. * @param {RuleContext} ruleContext
  372. * @param {WrapRuleCreateContext} wrapContext
  373. * @returns {TemplateListener}
  374. *
  375. * @typedef {object} WrapRuleCreateContext
  376. * @property {RuleListener} baseHandlers
  377. */
  378. /**
  379. * @callback WrapRulePreprocess
  380. * @param {RuleContext} ruleContext
  381. * @param {WrapRulePreprocessContext} wrapContext
  382. * @returns {void}
  383. *
  384. * @typedef {object} WrapRulePreprocessContext
  385. * @property { (override: Partial<RuleContext>) => RuleContext } wrapContextToOverrideProperties Wrap the rule context object to override
  386. * @property { (visitor: TemplateListener) => void } defineVisitor Define template body visitor
  387. */
  388. /**
  389. * @typedef {object} WrapRuleOptions
  390. * @property {string[]} [categories] The categories of this rule.
  391. * @property {boolean} [skipDynamicArguments] If `true`, skip validation within dynamic arguments.
  392. * @property {boolean} [skipDynamicArgumentsReport] If `true`, skip report within dynamic arguments.
  393. * @property {boolean} [applyDocument] If `true`, apply check to document fragment.
  394. * @property {boolean} [skipBaseHandlers] If `true`, skip base rule handlers.
  395. * @property {WrapRulePreprocess} [preprocess] Preprocess to calling create of base rule.
  396. * @property {WrapRuleCreate} [create] If define, extend base rule.
  397. */
  398. /**
  399. * Wrap a given core rule to apply it to Vue.js template.
  400. * @param {string} coreRuleName The name of the core rule implementation to wrap.
  401. * @param {WrapRuleOptions} [options] The option of this rule.
  402. * @returns {RuleModule} The wrapped rule implementation.
  403. */
  404. function wrapCoreRule(coreRuleName, options) {
  405. const coreRule = getCoreRule(coreRuleName)
  406. if (!coreRule) {
  407. return {
  408. meta: {
  409. type: 'problem',
  410. docs: {
  411. url: `https://eslint.vuejs.org/rules/${coreRuleName}.html`
  412. }
  413. },
  414. create(context) {
  415. return defineTemplateBodyVisitor(context, {
  416. "VElement[name='template'][parent.type='VDocumentFragment']"(node) {
  417. context.report({
  418. node,
  419. message: `Failed to extend ESLint core rule "${coreRuleName}". You may be able to use this rule by upgrading the version of ESLint. If you cannot upgrade it, turn off this rule.`
  420. })
  421. }
  422. })
  423. }
  424. }
  425. }
  426. const rule = wrapRuleModule(coreRule, coreRuleName, options)
  427. const meta = {
  428. ...rule.meta,
  429. docs: {
  430. ...rule.meta.docs,
  431. extensionSource: {
  432. url: coreRule.meta.docs.url,
  433. name: 'ESLint core'
  434. }
  435. }
  436. }
  437. return {
  438. ...rule,
  439. meta
  440. }
  441. }
  442. /**
  443. * @typedef {object} RuleNames
  444. * @property {string} core The name of the core rule implementation to wrap.
  445. * @property {string} stylistic The name of ESLint Stylistic rule implementation to wrap.
  446. * @property {string} vue The name of the wrapped rule
  447. */
  448. /**
  449. * Wrap a core rule or ESLint Stylistic rule to apply it to Vue.js template.
  450. * @param {RuleNames|string} ruleNames The names of the rule implementation to wrap.
  451. * @param {WrapRuleOptions} [options] The option of this rule.
  452. * @returns {RuleModule} The wrapped rule implementation.
  453. */
  454. function wrapStylisticOrCoreRule(ruleNames, options) {
  455. const stylisticRuleName =
  456. typeof ruleNames === 'string' ? ruleNames : ruleNames.stylistic
  457. const coreRuleName =
  458. typeof ruleNames === 'string' ? ruleNames : ruleNames.core
  459. const vueRuleName = typeof ruleNames === 'string' ? ruleNames : ruleNames.vue
  460. const stylisticRule = getStylisticRule(stylisticRuleName)
  461. const baseRule = stylisticRule || getCoreRule(coreRuleName)
  462. if (!baseRule) {
  463. return {
  464. meta: {
  465. type: 'problem',
  466. docs: {
  467. url: `https://eslint.vuejs.org/rules/${vueRuleName}.html`
  468. }
  469. },
  470. create(context) {
  471. return defineTemplateBodyVisitor(context, {
  472. "VElement[name='template'][parent.type='VDocumentFragment']"(node) {
  473. context.report({
  474. node,
  475. message: `Failed to extend ESLint Stylistic rule "${stylisticRule}". You may be able to use this rule by installing ESLint Stylistic plugin (https://eslint.style/). If you cannot install it, turn off this rule.`
  476. })
  477. }
  478. })
  479. }
  480. }
  481. }
  482. const rule = wrapRuleModule(baseRule, vueRuleName, options)
  483. const jsRule = getStylisticRule(
  484. stylisticRuleName,
  485. '@stylistic/eslint-plugin-js'
  486. )
  487. const description = stylisticRule
  488. ? `${jsRule?.meta.docs.description} in \`<template>\``
  489. : rule.meta.docs.description
  490. const meta = {
  491. ...rule.meta,
  492. docs: {
  493. ...rule.meta.docs,
  494. description,
  495. extensionSource: {
  496. url: baseRule.meta.docs.url,
  497. name: stylisticRule ? 'ESLint Stylistic' : 'ESLint core'
  498. }
  499. },
  500. deprecated: undefined,
  501. replacedBy: undefined
  502. }
  503. return {
  504. ...rule,
  505. meta
  506. }
  507. }
  508. /**
  509. * Wrap a given rule to apply it to Vue.js template.
  510. * @param {RuleModule} baseRule The rule implementation to wrap.
  511. * @param {string} ruleName The name of the wrapped rule.
  512. * @param {WrapRuleOptions} [options] The option of this rule.
  513. * @returns {RuleModule} The wrapped rule implementation.
  514. */
  515. function wrapRuleModule(baseRule, ruleName, options) {
  516. let description = baseRule.meta.docs.description
  517. if (description) {
  518. description += ' in `<template>`'
  519. }
  520. const {
  521. categories,
  522. skipDynamicArguments,
  523. skipDynamicArgumentsReport,
  524. skipBaseHandlers,
  525. applyDocument,
  526. preprocess,
  527. create
  528. } = options || {}
  529. return {
  530. create(context) {
  531. const sourceCode = context.getSourceCode()
  532. const tokenStore =
  533. sourceCode.parserServices.getTemplateBodyTokenStore &&
  534. sourceCode.parserServices.getTemplateBodyTokenStore()
  535. // The `context.getSourceCode()` cannot access the tokens of templates.
  536. // So override the methods which access to tokens by the `tokenStore`.
  537. if (tokenStore) {
  538. context = wrapContextToOverrideTokenMethods(context, tokenStore, {
  539. applyDocument
  540. })
  541. }
  542. if (skipDynamicArgumentsReport) {
  543. context =
  544. wrapContextToOverrideReportMethodToSkipDynamicArgument(context)
  545. }
  546. /** @type {TemplateListener} */
  547. const handlers = {}
  548. if (preprocess) {
  549. preprocess(context, {
  550. wrapContextToOverrideProperties(override) {
  551. context = newProxy(context, override)
  552. return context
  553. },
  554. defineVisitor(visitor) {
  555. compositingVisitors(handlers, visitor)
  556. }
  557. })
  558. }
  559. const baseHandlers = baseRule.create(context)
  560. if (!skipBaseHandlers) {
  561. compositingVisitors(handlers, baseHandlers)
  562. }
  563. // Move `Program` handlers to `VElement[parent.type!='VElement']`
  564. if (handlers.Program) {
  565. handlers[
  566. applyDocument
  567. ? 'VDocumentFragment'
  568. : "VElement[parent.type!='VElement']"
  569. ] = /** @type {any} */ (handlers.Program)
  570. delete handlers.Program
  571. }
  572. if (handlers['Program:exit']) {
  573. handlers[
  574. applyDocument
  575. ? 'VDocumentFragment:exit'
  576. : "VElement[parent.type!='VElement']:exit"
  577. ] = /** @type {any} */ (handlers['Program:exit'])
  578. delete handlers['Program:exit']
  579. }
  580. if (skipDynamicArguments) {
  581. let withinDynamicArguments = false
  582. for (const name of Object.keys(handlers)) {
  583. const original = handlers[name]
  584. /** @param {any[]} args */
  585. handlers[name] = (...args) => {
  586. if (withinDynamicArguments) return
  587. // @ts-expect-error
  588. original(...args)
  589. }
  590. }
  591. handlers['VDirectiveKey > VExpressionContainer'] = () => {
  592. withinDynamicArguments = true
  593. }
  594. handlers['VDirectiveKey > VExpressionContainer:exit'] = () => {
  595. withinDynamicArguments = false
  596. }
  597. }
  598. if (create) {
  599. compositingVisitors(handlers, create(context, { baseHandlers }))
  600. }
  601. if (applyDocument) {
  602. // Apply the handlers to document.
  603. return defineDocumentVisitor(context, handlers)
  604. }
  605. // Apply the handlers to templates.
  606. return defineTemplateBodyVisitor(context, handlers)
  607. },
  608. meta: Object.assign({}, baseRule.meta, {
  609. docs: Object.assign({}, baseRule.meta.docs, {
  610. description,
  611. category: null,
  612. categories,
  613. url: `https://eslint.vuejs.org/rules/${ruleName}.html`
  614. })
  615. })
  616. }
  617. }
  618. // ------------------------------------------------------------------------------
  619. // Exports
  620. // ------------------------------------------------------------------------------
  621. module.exports = {
  622. /**
  623. * Register the given visitor to parser services.
  624. * If the parser service of `vue-eslint-parser` was not found,
  625. * this generates a warning.
  626. *
  627. * @param {RuleContext} context The rule context to use parser services.
  628. * @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body.
  629. * @param {RuleListener} [scriptVisitor] The visitor to traverse the script.
  630. * @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options.
  631. * @returns {RuleListener} The merged visitor.
  632. */
  633. defineTemplateBodyVisitor,
  634. /**
  635. * Register the given visitor to parser services.
  636. * If the parser service of `vue-eslint-parser` was not found,
  637. * this generates a warning.
  638. *
  639. * @param {RuleContext} context The rule context to use parser services.
  640. * @param {TemplateListener} documentVisitor The visitor to traverse the document.
  641. * @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options.
  642. * @returns {RuleListener} The merged visitor.
  643. */
  644. defineDocumentVisitor,
  645. /**
  646. * Wrap a given core rule to apply it to Vue.js template.
  647. * @type {typeof wrapCoreRule}
  648. */
  649. wrapCoreRule,
  650. wrapStylisticOrCoreRule,
  651. getCoreRule,
  652. /**
  653. * Checks whether the given value is defined.
  654. * @template T
  655. * @param {T | null | undefined} v
  656. * @returns {v is T}
  657. */
  658. isDef,
  659. /**
  660. * Flattens arrays, objects and iterable objects.
  661. * @template T
  662. * @param {T | Iterable<T> | null | undefined} v
  663. * @returns {T[]}
  664. */
  665. flatten,
  666. /**
  667. * Get the previous sibling element of the given element.
  668. * @param {VElement} node The element node to get the previous sibling element.
  669. * @returns {VElement|null} The previous sibling element.
  670. */
  671. prevSibling(node) {
  672. let prevElement = null
  673. for (const siblingNode of (node.parent && node.parent.children) || []) {
  674. if (siblingNode === node) {
  675. return prevElement
  676. }
  677. if (siblingNode.type === 'VElement') {
  678. prevElement = siblingNode
  679. }
  680. }
  681. return null
  682. },
  683. /**
  684. * Check whether the given directive attribute has their empty value (`=""`).
  685. * @param {VDirective} node The directive attribute node to check.
  686. * @param {RuleContext} context The rule context to use parser services.
  687. * @returns {boolean} `true` if the directive attribute has their empty value (`=""`).
  688. */
  689. isEmptyValueDirective(node, context) {
  690. if (node.value == null) {
  691. return false
  692. }
  693. if (node.value.expression != null) {
  694. return false
  695. }
  696. let valueText = context.getSourceCode().getText(node.value)
  697. if (
  698. (valueText[0] === '"' || valueText[0] === "'") &&
  699. valueText[0] === valueText[valueText.length - 1]
  700. ) {
  701. // quoted
  702. valueText = valueText.slice(1, -1)
  703. }
  704. if (!valueText) {
  705. // empty
  706. return true
  707. }
  708. return false
  709. },
  710. /**
  711. * Check whether the given directive attribute has their empty expression value (e.g. `=" "`, `="/* &ast;/"`).
  712. * @param {VDirective} node The directive attribute node to check.
  713. * @param {RuleContext} context The rule context to use parser services.
  714. * @returns {boolean} `true` if the directive attribute has their empty expression value.
  715. */
  716. isEmptyExpressionValueDirective(node, context) {
  717. if (node.value == null) {
  718. return false
  719. }
  720. if (node.value.expression != null) {
  721. return false
  722. }
  723. const sourceCode = context.getSourceCode()
  724. const valueNode = node.value
  725. const tokenStore = sourceCode.parserServices.getTemplateBodyTokenStore()
  726. let quote1 = null
  727. let quote2 = null
  728. // `node.value` may be only comments, so cannot get the correct tokens with `tokenStore.getTokens(node.value)`.
  729. for (const token of tokenStore.getTokens(node)) {
  730. if (token.range[1] <= valueNode.range[0]) {
  731. continue
  732. }
  733. if (valueNode.range[1] <= token.range[0]) {
  734. // empty
  735. return true
  736. }
  737. if (
  738. !quote1 &&
  739. token.type === 'Punctuator' &&
  740. (token.value === '"' || token.value === "'")
  741. ) {
  742. quote1 = token
  743. continue
  744. }
  745. if (
  746. !quote2 &&
  747. quote1 &&
  748. token.type === 'Punctuator' &&
  749. token.value === quote1.value
  750. ) {
  751. quote2 = token
  752. continue
  753. }
  754. // not empty
  755. return false
  756. }
  757. // empty
  758. return true
  759. },
  760. /**
  761. * Get the attribute which has the given name.
  762. * @param {VElement} node The start tag node to check.
  763. * @param {string} name The attribute name to check.
  764. * @param {string} [value] The attribute value to check.
  765. * @returns {VAttribute | null} The found attribute.
  766. */
  767. getAttribute,
  768. /**
  769. * Check whether the given start tag has specific directive.
  770. * @param {VElement} node The start tag node to check.
  771. * @param {string} name The attribute name to check.
  772. * @param {string} [value] The attribute value to check.
  773. * @returns {boolean} `true` if the start tag has the attribute.
  774. */
  775. hasAttribute,
  776. /**
  777. * Get the directive list which has the given name.
  778. * @param {VElement | VStartTag} node The start tag node to check.
  779. * @param {string} name The directive name to check.
  780. * @returns {VDirective[]} The array of `v-slot` directives.
  781. */
  782. getDirectives,
  783. /**
  784. * Get the directive which has the given name.
  785. * @param {VElement} node The start tag node to check.
  786. * @param {string} name The directive name to check.
  787. * @param {string} [argument] The directive argument to check.
  788. * @returns {VDirective | null} The found directive.
  789. */
  790. getDirective,
  791. /**
  792. * Check whether the given start tag has specific directive.
  793. * @param {VElement} node The start tag node to check.
  794. * @param {string} name The directive name to check.
  795. * @param {string} [argument] The directive argument to check.
  796. * @returns {boolean} `true` if the start tag has the directive.
  797. */
  798. hasDirective,
  799. isVBindSameNameShorthand,
  800. /**
  801. * Returns the list of all registered components
  802. * @param {ObjectExpression} componentObject
  803. * @returns { { node: Property, name: string }[] } Array of ASTNodes
  804. */
  805. getRegisteredComponents(componentObject) {
  806. const componentsNode = componentObject.properties.find(
  807. /**
  808. * @param {ESNode} p
  809. * @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })}
  810. */
  811. (p) =>
  812. p.type === 'Property' &&
  813. getStaticPropertyName(p) === 'components' &&
  814. p.value.type === 'ObjectExpression'
  815. )
  816. if (!componentsNode) {
  817. return []
  818. }
  819. return componentsNode.value.properties
  820. .filter(isProperty)
  821. .map((node) => {
  822. const name = getStaticPropertyName(node)
  823. return name ? { node, name } : null
  824. })
  825. .filter(isDef)
  826. },
  827. /**
  828. * Check whether the previous sibling element has `if` or `else-if` directive.
  829. * @param {VElement} node The element node to check.
  830. * @returns {boolean} `true` if the previous sibling element has `if` or `else-if` directive.
  831. */
  832. prevElementHasIf(node) {
  833. const prev = this.prevSibling(node)
  834. return (
  835. prev != null &&
  836. prev.startTag.attributes.some(
  837. (a) =>
  838. a.directive &&
  839. (a.key.name.name === 'if' || a.key.name.name === 'else-if')
  840. )
  841. )
  842. },
  843. /**
  844. * Returns a generator with all child element v-if chains of the given element.
  845. * @param {VElement} node The element node to check.
  846. * @returns {IterableIterator<VElement[]>}
  847. */
  848. *iterateChildElementsChains(node) {
  849. let vIf = false
  850. /** @type {VElement[]} */
  851. let elementChain = []
  852. for (const childNode of node.children) {
  853. if (childNode.type === 'VElement') {
  854. let connected
  855. if (hasDirective(childNode, 'if')) {
  856. connected = false
  857. vIf = true
  858. } else if (hasDirective(childNode, 'else-if')) {
  859. connected = vIf
  860. vIf = true
  861. } else if (hasDirective(childNode, 'else')) {
  862. connected = vIf
  863. vIf = false
  864. } else {
  865. connected = false
  866. vIf = false
  867. }
  868. if (connected) {
  869. elementChain.push(childNode)
  870. } else {
  871. if (elementChain.length > 0) {
  872. yield elementChain
  873. }
  874. elementChain = [childNode]
  875. }
  876. } else if (childNode.type !== 'VText' || childNode.value.trim() !== '') {
  877. vIf = false
  878. }
  879. }
  880. if (elementChain.length > 0) {
  881. yield elementChain
  882. }
  883. },
  884. /**
  885. * @param {ASTNode} node
  886. * @returns {node is Literal | TemplateLiteral}
  887. */
  888. isStringLiteral(node) {
  889. return (
  890. (node.type === 'Literal' && typeof node.value === 'string') ||
  891. (node.type === 'TemplateLiteral' && node.expressions.length === 0)
  892. )
  893. },
  894. /**
  895. * Check whether the given node is a custom component or not.
  896. * @param {VElement} node The start tag node to check.
  897. * @param {boolean} [ignoreElementNamespaces=false] If `true`, ignore element namespaces.
  898. * @returns {boolean} `true` if the node is a custom component.
  899. */
  900. isCustomComponent(node, ignoreElementNamespaces = false) {
  901. if (
  902. hasAttribute(node, 'is') ||
  903. hasDirective(node, 'bind', 'is') ||
  904. hasDirective(node, 'is')
  905. ) {
  906. return true
  907. }
  908. const isHtmlName = this.isHtmlWellKnownElementName(node.rawName)
  909. const isSvgName = this.isSvgWellKnownElementName(node.rawName)
  910. const isMathName = this.isMathWellKnownElementName(node.rawName)
  911. if (ignoreElementNamespaces) {
  912. return !isHtmlName && !isSvgName && !isMathName
  913. }
  914. return (
  915. (this.isHtmlElementNode(node) && !isHtmlName) ||
  916. (this.isSvgElementNode(node) && !isSvgName) ||
  917. (this.isMathElementNode(node) && !isMathName)
  918. )
  919. },
  920. /**
  921. * Check whether the given node is a HTML element or not.
  922. * @param {VElement} node The node to check.
  923. * @returns {boolean} `true` if the node is a HTML element.
  924. */
  925. isHtmlElementNode(node) {
  926. return node.namespace === NS.HTML
  927. },
  928. /**
  929. * Check whether the given node is a SVG element or not.
  930. * @param {VElement} node The node to check.
  931. * @returns {boolean} `true` if the name is a SVG element.
  932. */
  933. isSvgElementNode(node) {
  934. return node.namespace === NS.SVG
  935. },
  936. /**
  937. * Check whether the given name is a MathML element or not.
  938. * @param {VElement} node The node to check.
  939. * @returns {boolean} `true` if the node is a MathML element.
  940. */
  941. isMathElementNode(node) {
  942. return node.namespace === NS.MathML
  943. },
  944. /**
  945. * Check whether the given name is an well-known element or not.
  946. * @param {string} name The name to check.
  947. * @returns {boolean} `true` if the name is an well-known element name.
  948. */
  949. isHtmlWellKnownElementName(name) {
  950. return HTML_ELEMENT_NAMES.has(name)
  951. },
  952. /**
  953. * Check whether the given name is an well-known SVG element or not.
  954. * @param {string} name The name to check.
  955. * @returns {boolean} `true` if the name is an well-known SVG element name.
  956. */
  957. isSvgWellKnownElementName(name) {
  958. return SVG_ELEMENT_NAMES.has(name)
  959. },
  960. /**
  961. * Check whether the given name is a well-known MathML element or not.
  962. * @param {string} name The name to check.
  963. * @returns {boolean} `true` if the name is a well-known MathML element name.
  964. */
  965. isMathWellKnownElementName(name) {
  966. return MATH_ELEMENT_NAMES.has(name)
  967. },
  968. /**
  969. * Check whether the given name is a void element name or not.
  970. * @param {string} name The name to check.
  971. * @returns {boolean} `true` if the name is a void element name.
  972. */
  973. isHtmlVoidElementName(name) {
  974. return VOID_ELEMENT_NAMES.has(name)
  975. },
  976. /**
  977. * Check whether the given name is Vue builtin component name or not.
  978. * @param {string} name The name to check.
  979. * @returns {boolean} `true` if the name is a builtin component name
  980. */
  981. isBuiltInComponentName(name) {
  982. return (
  983. VUE3_BUILTIN_COMPONENT_NAMES.has(name) ||
  984. VUE2_BUILTIN_COMPONENT_NAMES.has(name)
  985. )
  986. },
  987. /**
  988. * Check whether the given name is Vue builtin element name or not.
  989. * @param {string} name The name to check.
  990. * @returns {boolean} `true` if the name is a builtin Vue element name
  991. */
  992. isVueBuiltInElementName(name) {
  993. return VUE_BUILTIN_ELEMENT_NAMES.has(name.toLowerCase())
  994. },
  995. /**
  996. * Check whether the given name is Vue builtin directive name or not.
  997. * @param {string} name The name to check.
  998. * @returns {boolean} `true` if the name is a builtin Directive name
  999. */
  1000. isBuiltInDirectiveName(name) {
  1001. return (
  1002. name === 'bind' ||
  1003. name === 'on' ||
  1004. name === 'text' ||
  1005. name === 'html' ||
  1006. name === 'show' ||
  1007. name === 'if' ||
  1008. name === 'else' ||
  1009. name === 'else-if' ||
  1010. name === 'for' ||
  1011. name === 'model' ||
  1012. name === 'slot' ||
  1013. name === 'pre' ||
  1014. name === 'cloak' ||
  1015. name === 'once' ||
  1016. name === 'memo' ||
  1017. name === 'is'
  1018. )
  1019. },
  1020. /**
  1021. * Gets the property name of a given node.
  1022. * @param {Property|AssignmentProperty|MethodDefinition|MemberExpression} node - The node to get.
  1023. * @return {string|null} The property name if static. Otherwise, null.
  1024. */
  1025. getStaticPropertyName,
  1026. /**
  1027. * Gets the string of a given node.
  1028. * @param {Literal|TemplateLiteral} node - The node to get.
  1029. * @return {string|null} The string if static. Otherwise, null.
  1030. */
  1031. getStringLiteralValue,
  1032. /**
  1033. * Get all props by looking at all component's properties
  1034. * @param {ObjectExpression} componentObject Object with component definition
  1035. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  1036. */
  1037. getComponentPropsFromOptions,
  1038. /**
  1039. * Get all emits by looking at all component's properties
  1040. * @param {ObjectExpression} componentObject Object with component definition
  1041. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits
  1042. */
  1043. getComponentEmitsFromOptions,
  1044. /**
  1045. * Get all computed properties by looking at all component's properties
  1046. * @param {ObjectExpression} componentObject Object with component definition
  1047. * @return {ComponentComputedProperty[]} Array of computed properties in format: [{key: String, value: ASTNode}]
  1048. */
  1049. getComputedProperties(componentObject) {
  1050. const computedPropertiesNode = componentObject.properties.find(
  1051. /**
  1052. * @param {ESNode} p
  1053. * @returns {p is (Property & { key: Identifier & {name: 'computed'}, value: ObjectExpression })}
  1054. */
  1055. (p) =>
  1056. p.type === 'Property' &&
  1057. getStaticPropertyName(p) === 'computed' &&
  1058. p.value.type === 'ObjectExpression'
  1059. )
  1060. if (!computedPropertiesNode) {
  1061. return []
  1062. }
  1063. return computedPropertiesNode.value.properties
  1064. .filter(isProperty)
  1065. .map((cp) => {
  1066. const key = getStaticPropertyName(cp)
  1067. /** @type {Expression} */
  1068. const propValue = skipTSAsExpression(cp.value)
  1069. /** @type {BlockStatement | null} */
  1070. let value = null
  1071. if (propValue.type === 'FunctionExpression') {
  1072. value = propValue.body
  1073. } else if (propValue.type === 'ObjectExpression') {
  1074. const get =
  1075. /** @type {(Property & { value: FunctionExpression }) | null} */ (
  1076. findProperty(
  1077. propValue,
  1078. 'get',
  1079. (p) => p.value.type === 'FunctionExpression'
  1080. )
  1081. )
  1082. value = get ? get.value.body : null
  1083. }
  1084. return { key, value }
  1085. })
  1086. },
  1087. /**
  1088. * Get getter body from computed function
  1089. * @param {CallExpression} callExpression call of computed function
  1090. * @return {FunctionExpression | ArrowFunctionExpression | null} getter function
  1091. */
  1092. getGetterBodyFromComputedFunction(callExpression) {
  1093. if (callExpression.arguments.length <= 0) {
  1094. return null
  1095. }
  1096. const arg = callExpression.arguments[0]
  1097. if (
  1098. arg.type === 'FunctionExpression' ||
  1099. arg.type === 'ArrowFunctionExpression'
  1100. ) {
  1101. return arg
  1102. }
  1103. if (arg.type === 'ObjectExpression') {
  1104. const getProperty =
  1105. /** @type {(Property & { value: FunctionExpression | ArrowFunctionExpression }) | null} */ (
  1106. findProperty(
  1107. arg,
  1108. 'get',
  1109. (p) =>
  1110. p.value.type === 'FunctionExpression' ||
  1111. p.value.type === 'ArrowFunctionExpression'
  1112. )
  1113. )
  1114. return getProperty ? getProperty.value : null
  1115. }
  1116. return null
  1117. },
  1118. isTypeScriptFile,
  1119. isVueFile,
  1120. /**
  1121. * Checks whether the current file is uses `<script setup>`
  1122. * @param {RuleContext} context The ESLint rule context object.
  1123. */
  1124. isScriptSetup,
  1125. /**
  1126. * Gets the element of `<script setup>`
  1127. * @param {RuleContext} context The ESLint rule context object.
  1128. * @returns {VElement | null} the element of `<script setup>`
  1129. */
  1130. getScriptSetupElement,
  1131. /**
  1132. * Check if current file is a Vue instance or component and call callback
  1133. * @param {RuleContext} context The ESLint rule context object.
  1134. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1135. */
  1136. executeOnVue(context, cb) {
  1137. return compositingVisitors(
  1138. this.executeOnVueComponent(context, cb),
  1139. this.executeOnVueInstance(context, cb)
  1140. )
  1141. },
  1142. /**
  1143. * Define handlers to traverse the Vue Objects.
  1144. * Some special events are available to visitor.
  1145. *
  1146. * - `onVueObjectEnter` ... Event when Vue Object is found.
  1147. * - `onVueObjectExit` ... Event when Vue Object visit ends.
  1148. * - `onSetupFunctionEnter` ... Event when setup function found.
  1149. * - `onRenderFunctionEnter` ... Event when render function found.
  1150. *
  1151. * @param {RuleContext} context The ESLint rule context object.
  1152. * @param {VueVisitor} visitor The visitor to traverse the Vue Objects.
  1153. */
  1154. defineVueVisitor(context, visitor) {
  1155. /** @type {VueObjectData | null} */
  1156. let vueStack = null
  1157. /**
  1158. * @param {string} key
  1159. * @param {ESNode} node
  1160. */
  1161. function callVisitor(key, node) {
  1162. if (visitor[key] && vueStack) {
  1163. // @ts-expect-error
  1164. visitor[key](node, vueStack)
  1165. }
  1166. }
  1167. /** @type {NodeListener} */
  1168. const vueVisitor = {}
  1169. for (const key in visitor) {
  1170. vueVisitor[key] = (node) => callVisitor(key, node)
  1171. }
  1172. /**
  1173. * @param {ObjectExpression} node
  1174. */
  1175. vueVisitor.ObjectExpression = (node) => {
  1176. const type = getVueObjectType(context, node)
  1177. if (type) {
  1178. vueStack = {
  1179. node,
  1180. type,
  1181. parent: vueStack,
  1182. get functional() {
  1183. const functional = node.properties.find(
  1184. /**
  1185. * @param {Property | SpreadElement} p
  1186. * @returns {p is Property}
  1187. */
  1188. (p) =>
  1189. p.type === 'Property' &&
  1190. getStaticPropertyName(p) === 'functional'
  1191. )
  1192. if (!functional) {
  1193. return false
  1194. }
  1195. if (
  1196. functional.value.type === 'Literal' &&
  1197. functional.value.value === false
  1198. ) {
  1199. return false
  1200. }
  1201. return true
  1202. }
  1203. }
  1204. callVisitor('onVueObjectEnter', node)
  1205. }
  1206. callVisitor('ObjectExpression', node)
  1207. }
  1208. vueVisitor['ObjectExpression:exit'] = (node) => {
  1209. callVisitor('ObjectExpression:exit', node)
  1210. if (vueStack && vueStack.node === node) {
  1211. callVisitor('onVueObjectExit', node)
  1212. vueStack = vueStack.parent
  1213. }
  1214. }
  1215. if (
  1216. visitor.onSetupFunctionEnter ||
  1217. visitor.onSetupFunctionExit ||
  1218. visitor.onRenderFunctionEnter
  1219. ) {
  1220. const setups = new Set()
  1221. /** @param { (FunctionExpression | ArrowFunctionExpression) & { parent: Property } } node */
  1222. vueVisitor[
  1223. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function'
  1224. ] = (node) => {
  1225. /** @type {Property} */
  1226. const prop = node.parent
  1227. if (vueStack && prop.parent === vueStack.node && prop.value === node) {
  1228. const name = getStaticPropertyName(prop)
  1229. if (name === 'setup') {
  1230. callVisitor('onSetupFunctionEnter', node)
  1231. setups.add(node)
  1232. } else if (name === 'render') {
  1233. callVisitor('onRenderFunctionEnter', node)
  1234. }
  1235. }
  1236. callVisitor(
  1237. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function',
  1238. node
  1239. )
  1240. }
  1241. if (visitor.onSetupFunctionExit) {
  1242. /** @param { (FunctionExpression | ArrowFunctionExpression) & { parent: Property } } node */
  1243. vueVisitor[
  1244. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function:exit'
  1245. ] = (node) => {
  1246. if (setups.has(node)) {
  1247. callVisitor('onSetupFunctionExit', node)
  1248. setups.delete(node)
  1249. }
  1250. }
  1251. }
  1252. }
  1253. return vueVisitor
  1254. },
  1255. /**
  1256. * Define handlers to traverse the AST nodes in `<script setup>`.
  1257. * Some special events are available to visitor.
  1258. *
  1259. * - `onDefinePropsEnter` ... Event when defineProps is found.
  1260. * - `onDefinePropsExit` ... Event when defineProps visit ends.
  1261. * - `onDefineEmitsEnter` ... Event when defineEmits is found.
  1262. * - `onDefineEmitsExit` ... Event when defineEmits visit ends.
  1263. * - `onDefineOptionsEnter` ... Event when defineOptions is found.
  1264. * - `onDefineOptionsExit` ... Event when defineOptions visit ends.
  1265. * - `onDefineSlotsEnter` ... Event when defineSlots is found.
  1266. * - `onDefineSlotsExit` ... Event when defineSlots visit ends.
  1267. * - `onDefineExposeEnter` ... Event when defineExpose is found.
  1268. * - `onDefineExposeExit` ... Event when defineExpose visit ends.
  1269. * - `onDefineModelEnter` ... Event when defineModel is found.
  1270. * - `onDefineModelExit` ... Event when defineModel visit ends.
  1271. *
  1272. * @param {RuleContext} context The ESLint rule context object.
  1273. * @param {ScriptSetupVisitor} visitor The visitor to traverse the AST nodes.
  1274. */
  1275. defineScriptSetupVisitor(context, visitor) {
  1276. const scriptSetup = getScriptSetupElement(context)
  1277. if (scriptSetup == null) {
  1278. return {}
  1279. }
  1280. const scriptSetupRange = scriptSetup.range
  1281. /**
  1282. * @param {ESNode} node
  1283. */
  1284. function inScriptSetup(node) {
  1285. return (
  1286. scriptSetupRange[0] <= node.range[0] &&
  1287. node.range[1] <= scriptSetupRange[1]
  1288. )
  1289. }
  1290. /**
  1291. * @param {string} key
  1292. * @param {ESNode} node
  1293. * @param {any[]} args
  1294. */
  1295. function callVisitor(key, node, ...args) {
  1296. if (visitor[key] && inScriptSetup(node)) {
  1297. // @ts-expect-error
  1298. visitor[key](node, ...args)
  1299. }
  1300. }
  1301. /** @type {NodeListener} */
  1302. const scriptSetupVisitor = {}
  1303. for (const key in visitor) {
  1304. scriptSetupVisitor[key] = (node) => callVisitor(key, node)
  1305. }
  1306. class MacroListener {
  1307. /**
  1308. * @param {string} name
  1309. * @param {string} enterName
  1310. * @param {string} exitName
  1311. * @param {(candidateMacro: Expression | null, node: CallExpression) => boolean} isMacroNode
  1312. * @param {(context: RuleContext, node: CallExpression) => unknown} buildParam
  1313. */
  1314. constructor(name, enterName, exitName, isMacroNode, buildParam) {
  1315. this.name = name
  1316. this.enterName = enterName
  1317. this.exitName = exitName
  1318. this.isMacroNode = isMacroNode
  1319. this.buildParam = buildParam
  1320. this.hasListener = Boolean(
  1321. visitor[this.enterName] || visitor[this.exitName]
  1322. )
  1323. this.paramsMap = new Map()
  1324. }
  1325. }
  1326. const macroListenerList = [
  1327. new MacroListener(
  1328. 'defineProps',
  1329. 'onDefinePropsEnter',
  1330. 'onDefinePropsExit',
  1331. (candidateMacro, node) =>
  1332. candidateMacro === node || candidateMacro === getWithDefaults(node),
  1333. getComponentPropsFromDefineProps
  1334. ),
  1335. new MacroListener(
  1336. 'defineEmits',
  1337. 'onDefineEmitsEnter',
  1338. 'onDefineEmitsExit',
  1339. (candidateMacro, node) => candidateMacro === node,
  1340. getComponentEmitsFromDefineEmits
  1341. ),
  1342. new MacroListener(
  1343. 'defineOptions',
  1344. 'onDefineOptionsEnter',
  1345. 'onDefineOptionsExit',
  1346. (candidateMacro, node) => candidateMacro === node,
  1347. () => undefined
  1348. ),
  1349. new MacroListener(
  1350. 'defineSlots',
  1351. 'onDefineSlotsEnter',
  1352. 'onDefineSlotsExit',
  1353. (candidateMacro, node) => candidateMacro === node,
  1354. getComponentSlotsFromDefineSlots
  1355. ),
  1356. new MacroListener(
  1357. 'defineExpose',
  1358. 'onDefineExposeEnter',
  1359. 'onDefineExposeExit',
  1360. (candidateMacro, node) => candidateMacro === node,
  1361. () => undefined
  1362. ),
  1363. new MacroListener(
  1364. 'defineModel',
  1365. 'onDefineModelEnter',
  1366. 'onDefineModelExit',
  1367. (candidateMacro, node) => candidateMacro === node,
  1368. getComponentModelFromDefineModel
  1369. )
  1370. ].filter((m) => m.hasListener)
  1371. if (macroListenerList.length > 0) {
  1372. /** @type {Expression | null} */
  1373. let candidateMacro = null
  1374. /** @param {VariableDeclarator|ExpressionStatement} node */
  1375. scriptSetupVisitor[
  1376. 'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement'
  1377. ] = (node) => {
  1378. if (!candidateMacro) {
  1379. candidateMacro =
  1380. node.type === 'VariableDeclarator' ? node.init : node.expression
  1381. }
  1382. }
  1383. /** @param {VariableDeclarator|ExpressionStatement} node */
  1384. scriptSetupVisitor[
  1385. 'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement:exit'
  1386. ] = (node) => {
  1387. if (
  1388. candidateMacro ===
  1389. (node.type === 'VariableDeclarator' ? node.init : node.expression)
  1390. ) {
  1391. candidateMacro = null
  1392. }
  1393. }
  1394. /**
  1395. * @param {CallExpression} node
  1396. */
  1397. scriptSetupVisitor.CallExpression = (node) => {
  1398. if (
  1399. candidateMacro &&
  1400. inScriptSetup(node) &&
  1401. node.callee.type === 'Identifier'
  1402. ) {
  1403. for (const macroListener of macroListenerList) {
  1404. if (
  1405. node.callee.name !== macroListener.name ||
  1406. !macroListener.isMacroNode(candidateMacro, node)
  1407. ) {
  1408. continue
  1409. }
  1410. const param = macroListener.buildParam(context, node)
  1411. callVisitor(macroListener.enterName, node, param)
  1412. macroListener.paramsMap.set(node, param)
  1413. break
  1414. }
  1415. }
  1416. callVisitor('CallExpression', node)
  1417. }
  1418. scriptSetupVisitor['CallExpression:exit'] = (node) => {
  1419. callVisitor('CallExpression:exit', node)
  1420. for (const macroListener of macroListenerList) {
  1421. if (macroListener.paramsMap.has(node)) {
  1422. callVisitor(
  1423. macroListener.exitName,
  1424. node,
  1425. macroListener.paramsMap.get(node)
  1426. )
  1427. macroListener.paramsMap.delete(node)
  1428. }
  1429. }
  1430. }
  1431. }
  1432. return scriptSetupVisitor
  1433. },
  1434. /**
  1435. * Checks whether given defineProps call node has withDefaults.
  1436. * @param {CallExpression} node The node of defineProps
  1437. * @returns {node is CallExpression & { parent: CallExpression }}
  1438. */
  1439. hasWithDefaults,
  1440. /**
  1441. * Gets a map of the expressions defined in withDefaults.
  1442. * @param {CallExpression} node The node of defineProps
  1443. * @returns { { [key: string]: Expression | undefined } }
  1444. */
  1445. getWithDefaultsPropExpressions(node) {
  1446. const map = getWithDefaultsProps(node)
  1447. /** @type {Record<string, Expression | undefined>} */
  1448. const result = {}
  1449. for (const key of Object.keys(map)) {
  1450. const prop = map[key]
  1451. result[key] = prop && prop.value
  1452. }
  1453. return result
  1454. },
  1455. /**
  1456. * Gets a map of the property nodes defined in withDefaults.
  1457. * @param {CallExpression} node The node of defineProps
  1458. * @returns { { [key: string]: Property | undefined } }
  1459. */
  1460. getWithDefaultsProps,
  1461. /**
  1462. * Gets the default definition nodes for defineProp
  1463. * using the props destructure with assignment pattern.
  1464. * @param {CallExpression} node The node of defineProps
  1465. * @returns { Record<string, {prop: AssignmentProperty , expression: Expression} | undefined> }
  1466. */
  1467. getDefaultPropExpressionsForPropsDestructure,
  1468. /**
  1469. * Checks whether the given defineProps node is using Props Destructure.
  1470. * @param {CallExpression} node The node of defineProps
  1471. * @returns {boolean}
  1472. */
  1473. isUsingPropsDestructure(node) {
  1474. const left = getLeftOfDefineProps(node)
  1475. return left?.type === 'ObjectPattern'
  1476. },
  1477. /**
  1478. * Gets the props destructure property nodes for defineProp.
  1479. * @param {CallExpression} node The node of defineProps
  1480. * @returns { Record<string, AssignmentProperty | undefined> }
  1481. */
  1482. getPropsDestructure,
  1483. getVueObjectType,
  1484. /**
  1485. * Get the Vue component definition type from given node
  1486. * Vue.component('xxx', {}) || component('xxx', {})
  1487. * @param {ObjectExpression} node Node to check
  1488. * @returns {'component' | 'mixin' | 'extend' | 'createApp' | 'defineComponent' | null}
  1489. */
  1490. getVueComponentDefinitionType,
  1491. /**
  1492. * Checks whether the given object is an SFC definition.
  1493. * @param {RuleContext} context The ESLint rule context object.
  1494. * @param {ObjectExpression} node Node to check
  1495. * @returns { boolean } `true`, the given object is an SFC definition.
  1496. */
  1497. isSFCObject,
  1498. compositingVisitors,
  1499. /**
  1500. * Check if current file is a Vue instance (new Vue) and call callback
  1501. * @param {RuleContext} context The ESLint rule context object.
  1502. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1503. */
  1504. executeOnVueInstance(context, cb) {
  1505. return {
  1506. /** @param {ObjectExpression} node */
  1507. 'ObjectExpression:exit'(node) {
  1508. const type = getVueObjectType(context, node)
  1509. if (!type || type !== 'instance') return
  1510. cb(node, type)
  1511. }
  1512. }
  1513. },
  1514. /**
  1515. * Check if current file is a Vue component and call callback
  1516. * @param {RuleContext} context The ESLint rule context object.
  1517. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1518. */
  1519. executeOnVueComponent(context, cb) {
  1520. return {
  1521. /** @param {ObjectExpression} node */
  1522. 'ObjectExpression:exit'(node) {
  1523. const type = getVueObjectType(context, node)
  1524. if (
  1525. !type ||
  1526. (type !== 'mark' && type !== 'export' && type !== 'definition')
  1527. )
  1528. return
  1529. cb(node, type)
  1530. }
  1531. }
  1532. },
  1533. /**
  1534. * Check call `Vue.component` and call callback.
  1535. * @param {RuleContext} _context The ESLint rule context object.
  1536. * @param { (node: CallExpression) => void } cb Callback function
  1537. */
  1538. executeOnCallVueComponent(_context, cb) {
  1539. return {
  1540. /** @param {Identifier & { parent: MemberExpression & { parent: CallExpression } } } node */
  1541. "CallExpression > MemberExpression > Identifier[name='component']": (
  1542. node
  1543. ) => {
  1544. const callExpr = node.parent.parent
  1545. const callee = callExpr.callee
  1546. if (callee.type === 'MemberExpression') {
  1547. const calleeObject = skipTSAsExpression(callee.object)
  1548. if (
  1549. calleeObject.type === 'Identifier' &&
  1550. // calleeObject.name === 'Vue' && // Any names can be used in Vue.js 3.x. e.g. app.component()
  1551. callee.property === node &&
  1552. callExpr.arguments.length > 0
  1553. ) {
  1554. cb(callExpr)
  1555. }
  1556. }
  1557. }
  1558. }
  1559. },
  1560. /**
  1561. * Return generator with all properties
  1562. * @param {ObjectExpression} node Node to check
  1563. * @param {Set<GroupName>} groups Name of parent group
  1564. * @returns {IterableIterator<ComponentPropertyData>}
  1565. */
  1566. *iterateProperties(node, groups) {
  1567. for (const item of node.properties) {
  1568. if (item.type !== 'Property') {
  1569. continue
  1570. }
  1571. const name = /** @type {GroupName | null} */ (getStaticPropertyName(item))
  1572. if (!name || !groups.has(name)) continue
  1573. switch (item.value.type) {
  1574. case 'ArrayExpression': {
  1575. yield* this.iterateArrayExpression(item.value, name)
  1576. break
  1577. }
  1578. case 'ObjectExpression': {
  1579. yield* this.iterateObjectExpression(item.value, name)
  1580. break
  1581. }
  1582. case 'FunctionExpression': {
  1583. yield* this.iterateFunctionExpression(item.value, name)
  1584. break
  1585. }
  1586. case 'ArrowFunctionExpression': {
  1587. yield* this.iterateArrowFunctionExpression(item.value, name)
  1588. break
  1589. }
  1590. }
  1591. }
  1592. },
  1593. /**
  1594. * Return generator with all elements inside ArrayExpression
  1595. * @param {ArrayExpression} node Node to check
  1596. * @param {GroupName} groupName Name of parent group
  1597. * @returns {IterableIterator<ComponentArrayPropertyData>}
  1598. */
  1599. *iterateArrayExpression(node, groupName) {
  1600. for (const item of node.elements) {
  1601. if (
  1602. item &&
  1603. (item.type === 'Literal' || item.type === 'TemplateLiteral')
  1604. ) {
  1605. const name = getStringLiteralValue(item)
  1606. if (name) {
  1607. yield { type: 'array', name, groupName, node: item }
  1608. }
  1609. }
  1610. }
  1611. },
  1612. /**
  1613. * Return generator with all elements inside ObjectExpression
  1614. * @param {ObjectExpression} node Node to check
  1615. * @param {GroupName} groupName Name of parent group
  1616. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1617. */
  1618. *iterateObjectExpression(node, groupName) {
  1619. /** @type {Set<Property> | undefined} */
  1620. let usedGetter
  1621. for (const item of node.properties) {
  1622. if (item.type === 'Property') {
  1623. const key = item.key
  1624. if (
  1625. key.type === 'Identifier' ||
  1626. key.type === 'Literal' ||
  1627. key.type === 'TemplateLiteral'
  1628. ) {
  1629. const name = getStaticPropertyName(item)
  1630. if (name) {
  1631. // find getter pair
  1632. if (
  1633. item.kind === 'set' &&
  1634. node.properties.some((item2) => {
  1635. if (item2.type === 'Property' && item2.kind === 'get') {
  1636. if (!usedGetter) {
  1637. usedGetter = new Set()
  1638. }
  1639. if (usedGetter.has(item2)) {
  1640. return false
  1641. }
  1642. const getterName = getStaticPropertyName(item2)
  1643. if (getterName === name) {
  1644. usedGetter.add(item2)
  1645. return true
  1646. }
  1647. }
  1648. return false
  1649. })
  1650. ) {
  1651. // has getter pair
  1652. continue
  1653. }
  1654. yield {
  1655. type: 'object',
  1656. name,
  1657. groupName,
  1658. node: key,
  1659. property: item
  1660. }
  1661. }
  1662. }
  1663. }
  1664. }
  1665. },
  1666. /**
  1667. * Return generator with all elements inside FunctionExpression
  1668. * @param {FunctionExpression} node Node to check
  1669. * @param {GroupName} groupName Name of parent group
  1670. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1671. */
  1672. *iterateFunctionExpression(node, groupName) {
  1673. if (node.body.type === 'BlockStatement') {
  1674. for (const item of node.body.body) {
  1675. if (
  1676. item.type === 'ReturnStatement' &&
  1677. item.argument &&
  1678. item.argument.type === 'ObjectExpression'
  1679. ) {
  1680. yield* this.iterateObjectExpression(item.argument, groupName)
  1681. }
  1682. }
  1683. }
  1684. },
  1685. /**
  1686. * Return generator with all elements inside ArrowFunctionExpression
  1687. * @param {ArrowFunctionExpression} node Node to check
  1688. * @param {GroupName} groupName Name of parent group
  1689. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1690. */
  1691. *iterateArrowFunctionExpression(node, groupName) {
  1692. const body = node.body
  1693. if (body.type === 'BlockStatement') {
  1694. for (const item of body.body) {
  1695. if (
  1696. item.type === 'ReturnStatement' &&
  1697. item.argument &&
  1698. item.argument.type === 'ObjectExpression'
  1699. ) {
  1700. yield* this.iterateObjectExpression(item.argument, groupName)
  1701. }
  1702. }
  1703. } else if (body.type === 'ObjectExpression') {
  1704. yield* this.iterateObjectExpression(body, groupName)
  1705. }
  1706. },
  1707. /**
  1708. * Find all functions which do not always return values
  1709. * @param {boolean} treatUndefinedAsUnspecified
  1710. * @param { (node: ArrowFunctionExpression | FunctionExpression | FunctionDeclaration) => void } cb Callback function
  1711. * @returns {RuleListener}
  1712. */
  1713. executeOnFunctionsWithoutReturn(treatUndefinedAsUnspecified, cb) {
  1714. /**
  1715. * @typedef {object} FuncInfo
  1716. * @property {FuncInfo | null} funcInfo
  1717. * @property {CodePath} codePath
  1718. * @property {boolean} hasReturn
  1719. * @property {boolean} hasReturnValue
  1720. * @property {ArrowFunctionExpression | FunctionExpression | FunctionDeclaration} node
  1721. * @property {CodePathSegment[]} currentSegments
  1722. */
  1723. /** @type {FuncInfo | null} */
  1724. let funcInfo = null
  1725. function isValidReturn() {
  1726. if (!funcInfo) {
  1727. return true
  1728. }
  1729. if (funcInfo.currentSegments.some((segment) => segment.reachable)) {
  1730. return false
  1731. }
  1732. return !treatUndefinedAsUnspecified || funcInfo.hasReturnValue
  1733. }
  1734. return {
  1735. /**
  1736. * @param {CodePath} codePath
  1737. * @param {ESNode} node
  1738. */
  1739. onCodePathStart(codePath, node) {
  1740. if (
  1741. node.type === 'ArrowFunctionExpression' ||
  1742. node.type === 'FunctionExpression' ||
  1743. node.type === 'FunctionDeclaration'
  1744. ) {
  1745. funcInfo = {
  1746. codePath,
  1747. currentSegments: [],
  1748. funcInfo,
  1749. hasReturn: false,
  1750. hasReturnValue: false,
  1751. node
  1752. }
  1753. }
  1754. },
  1755. onCodePathSegmentStart(segment) {
  1756. funcInfo?.currentSegments.push(segment)
  1757. },
  1758. onCodePathSegmentEnd() {
  1759. funcInfo?.currentSegments.pop()
  1760. },
  1761. onCodePathEnd() {
  1762. funcInfo = funcInfo && funcInfo.funcInfo
  1763. },
  1764. /** @param {ReturnStatement} node */
  1765. ReturnStatement(node) {
  1766. if (funcInfo) {
  1767. funcInfo.hasReturn = true
  1768. funcInfo.hasReturnValue = Boolean(node.argument)
  1769. }
  1770. },
  1771. /** @param {ArrowFunctionExpression} node */
  1772. 'ArrowFunctionExpression:exit'(node) {
  1773. if (funcInfo && !isValidReturn() && !node.expression) {
  1774. cb(funcInfo.node)
  1775. }
  1776. },
  1777. 'FunctionExpression:exit'() {
  1778. if (funcInfo && !isValidReturn()) {
  1779. cb(funcInfo.node)
  1780. }
  1781. }
  1782. }
  1783. },
  1784. /**
  1785. * Check whether the component is declared in a single line or not.
  1786. * @param {ASTNode} node
  1787. * @returns {boolean}
  1788. */
  1789. isSingleLine(node) {
  1790. return node.loc.start.line === node.loc.end.line
  1791. },
  1792. /**
  1793. * Check whether the templateBody of the program has invalid EOF or not.
  1794. * @param {Program} node The program node to check.
  1795. * @returns {boolean} `true` if it has invalid EOF.
  1796. */
  1797. hasInvalidEOF(node) {
  1798. const body = node.templateBody
  1799. if (body == null || body.errors == null) {
  1800. return false
  1801. }
  1802. return body.errors.some(
  1803. (error) => typeof error.code === 'string' && error.code.startsWith('eof-')
  1804. )
  1805. },
  1806. /**
  1807. * Get the chaining nodes of MemberExpression.
  1808. *
  1809. * @param {ESNode} node The node to parse
  1810. * @return {[ESNode, ...MemberExpression[]]} The chaining nodes
  1811. */
  1812. getMemberChaining(node) {
  1813. /** @type {MemberExpression[]} */
  1814. const nodes = []
  1815. let n = skipChainExpression(node)
  1816. while (n.type === 'MemberExpression') {
  1817. nodes.push(n)
  1818. n = skipChainExpression(n.object)
  1819. }
  1820. return [n, ...nodes.reverse()]
  1821. },
  1822. /**
  1823. * return two string editdistance
  1824. * @param {string} a string a to compare
  1825. * @param {string} b string b to compare
  1826. * @returns {number}
  1827. */
  1828. editDistance(a, b) {
  1829. if (a === b) {
  1830. return 0
  1831. }
  1832. const alen = a.length
  1833. const blen = b.length
  1834. const dp = Array.from({ length: alen + 1 }).map((_) =>
  1835. Array.from({ length: blen + 1 }).fill(0)
  1836. )
  1837. for (let i = 0; i <= alen; i++) {
  1838. dp[i][0] = i
  1839. }
  1840. for (let j = 0; j <= blen; j++) {
  1841. dp[0][j] = j
  1842. }
  1843. for (let i = 1; i <= alen; i++) {
  1844. for (let j = 1; j <= blen; j++) {
  1845. dp[i][j] =
  1846. a[i - 1] === b[j - 1]
  1847. ? dp[i - 1][j - 1]
  1848. : Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
  1849. }
  1850. }
  1851. return dp[alen][blen]
  1852. },
  1853. /**
  1854. * Checks whether the target node is within the given range.
  1855. * @param { [number, number] } range
  1856. * @param {ASTNode | Token} target
  1857. */
  1858. inRange(range, target) {
  1859. return range[0] <= target.range[0] && target.range[1] <= range[1]
  1860. },
  1861. /**
  1862. * Checks whether the given node is Property.
  1863. */
  1864. isProperty,
  1865. /**
  1866. * Checks whether the given node is AssignmentProperty.
  1867. */
  1868. isAssignmentProperty,
  1869. /**
  1870. * Checks whether the given node is VElement.
  1871. */
  1872. isVElement,
  1873. /**
  1874. * Finds the property with the given name from the given ObjectExpression node.
  1875. */
  1876. findProperty,
  1877. /**
  1878. * Finds the assignment property with the given name from the given ObjectPattern node.
  1879. */
  1880. findAssignmentProperty,
  1881. /**
  1882. * Checks if the given node is a property value.
  1883. * @param {Property} prop
  1884. * @param {Expression} node
  1885. */
  1886. isPropertyChain,
  1887. /**
  1888. * Retrieve `TSAsExpression#expression` value if the given node a `TSAsExpression` node. Otherwise, pass through it.
  1889. */
  1890. skipTSAsExpression,
  1891. /**
  1892. * Retrieve `AssignmentPattern#left` value if the given node a `AssignmentPattern` node. Otherwise, pass through it.
  1893. */
  1894. skipDefaultParamValue,
  1895. /**
  1896. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  1897. */
  1898. skipChainExpression,
  1899. /**
  1900. * Checks whether the given node is in a type annotation.
  1901. */
  1902. withinTypeNode,
  1903. findVariableByIdentifier,
  1904. getScope,
  1905. /**
  1906. * Marks a variable with the given name in the current scope as used. This affects the no-unused-vars rule.
  1907. */
  1908. markVariableAsUsed,
  1909. /**
  1910. * Checks whether the given node is in export default.
  1911. * @param {ASTNode} node
  1912. * @returns {boolean}
  1913. */
  1914. isInExportDefault,
  1915. /**
  1916. * Check whether the given node is `this` or variable that stores `this`.
  1917. * @param {ESNode} node The node to check
  1918. * @param {RuleContext} context The rule context to use parser services.
  1919. * @returns {boolean} `true` if the given node is `this`.
  1920. */
  1921. isThis(node, context) {
  1922. if (node.type === 'ThisExpression') {
  1923. return true
  1924. }
  1925. if (node.type !== 'Identifier') {
  1926. return false
  1927. }
  1928. const parent = node.parent
  1929. if (
  1930. (parent.type === 'MemberExpression' && parent.property === node) ||
  1931. (parent.type === 'Property' && parent.key === node && !parent.computed)
  1932. ) {
  1933. return false
  1934. }
  1935. const variable = findVariable(getScope(context, node), node)
  1936. if (variable != null && variable.defs.length === 1) {
  1937. const def = variable.defs[0]
  1938. if (
  1939. def.type === 'Variable' &&
  1940. def.parent.kind === 'const' &&
  1941. def.node.id.type === 'Identifier'
  1942. ) {
  1943. return Boolean(
  1944. def.node && def.node.init && def.node.init.type === 'ThisExpression'
  1945. )
  1946. }
  1947. }
  1948. return false
  1949. },
  1950. /**
  1951. * @param {MemberExpression|Identifier} props
  1952. * @returns { { kind: 'assignment' | 'update' | 'call' , node: ESNode, pathNodes: MemberExpression[] } | null }
  1953. */
  1954. findMutating(props) {
  1955. /** @type {MemberExpression[]} */
  1956. const pathNodes = []
  1957. /** @type {MemberExpression | Identifier | ChainExpression} */
  1958. let node = props
  1959. let target = node.parent
  1960. while (true) {
  1961. switch (target.type) {
  1962. case 'AssignmentExpression': {
  1963. if (target.left === node) {
  1964. // this.xxx <=|+=|-=>
  1965. return {
  1966. kind: 'assignment',
  1967. node: target,
  1968. pathNodes
  1969. }
  1970. }
  1971. break
  1972. }
  1973. case 'UpdateExpression': {
  1974. // this.xxx <++|-->
  1975. return {
  1976. kind: 'update',
  1977. node: target,
  1978. pathNodes
  1979. }
  1980. }
  1981. case 'UnaryExpression': {
  1982. if (target.operator === 'delete') {
  1983. return {
  1984. kind: 'update',
  1985. node: target,
  1986. pathNodes
  1987. }
  1988. }
  1989. break
  1990. }
  1991. case 'CallExpression': {
  1992. if (pathNodes.length > 0 && target.callee === node) {
  1993. const mem = pathNodes[pathNodes.length - 1]
  1994. const callName = getStaticPropertyName(mem)
  1995. if (
  1996. callName &&
  1997. /^(?:push|pop|shift|unshift|reverse|splice|sort|copyWithin|fill)$/u.test(
  1998. callName
  1999. )
  2000. ) {
  2001. // this.xxx.push()
  2002. pathNodes.pop()
  2003. return {
  2004. kind: 'call',
  2005. node: target,
  2006. pathNodes
  2007. }
  2008. }
  2009. }
  2010. break
  2011. }
  2012. case 'MemberExpression': {
  2013. if (target.object === node) {
  2014. pathNodes.push(target)
  2015. node = target
  2016. target = target.parent
  2017. continue // loop
  2018. }
  2019. break
  2020. }
  2021. case 'ChainExpression': {
  2022. node = target
  2023. target = target.parent
  2024. continue // loop
  2025. }
  2026. }
  2027. return null
  2028. }
  2029. },
  2030. /**
  2031. * Return generator with the all handler nodes defined in the given watcher property.
  2032. * @param {Property|Expression} property
  2033. * @returns {IterableIterator<Expression>}
  2034. */
  2035. iterateWatchHandlerValues,
  2036. /**
  2037. * Wraps composition API trace map in both 'vue' and '@vue/composition-api' imports, or '#imports' from unimport
  2038. * @param {import('@eslint-community/eslint-utils').TYPES.TraceMap} map
  2039. */
  2040. createCompositionApiTraceMap: (map) => ({
  2041. vue: map,
  2042. '@vue/composition-api': map,
  2043. '#imports': map
  2044. }),
  2045. /**
  2046. * Iterates all references in the given trace map.
  2047. * Take the third argument option to detect auto-imported references.
  2048. *
  2049. * @param {import('@eslint-community/eslint-utils').ReferenceTracker} tracker
  2050. * @param {import('@eslint-community/eslint-utils').TYPES.TraceMap} map
  2051. * @returns {ReturnType<import('@eslint-community/eslint-utils').ReferenceTracker['iterateEsmReferences']>}
  2052. */
  2053. *iterateReferencesTraceMap(tracker, map) {
  2054. const esmTraceMap = this.createCompositionApiTraceMap({
  2055. ...map,
  2056. [ReferenceTracker.ESM]: true
  2057. })
  2058. for (const ref of tracker.iterateEsmReferences(esmTraceMap)) {
  2059. yield ref
  2060. }
  2061. for (const ref of tracker.iterateGlobalReferences(map)) {
  2062. yield ref
  2063. }
  2064. },
  2065. /**
  2066. * Checks whether or not the tokens of two given nodes are same.
  2067. * @param {ASTNode} left A node 1 to compare.
  2068. * @param {ASTNode} right A node 2 to compare.
  2069. * @param {ParserServices.TokenStore | SourceCode} sourceCode The ESLint source code object.
  2070. * @returns {boolean} the source code for the given node.
  2071. */
  2072. equalTokens(left, right, sourceCode) {
  2073. const tokensL = sourceCode.getTokens(left)
  2074. const tokensR = sourceCode.getTokens(right)
  2075. if (tokensL.length !== tokensR.length) {
  2076. return false
  2077. }
  2078. return tokensL.every(
  2079. (token, i) =>
  2080. token.type === tokensR[i].type && token.value === tokensR[i].value
  2081. )
  2082. }
  2083. }
  2084. // ------------------------------------------------------------------------------
  2085. // Standard Helpers
  2086. // ------------------------------------------------------------------------------
  2087. /**
  2088. * Checks whether the given value is defined.
  2089. * @template T
  2090. * @param {T | null | undefined} v
  2091. * @returns {v is T}
  2092. */
  2093. function isDef(v) {
  2094. return v != null
  2095. }
  2096. /**
  2097. * Flattens arrays, objects and iterable objects.
  2098. * @template T
  2099. * @param {T | Iterable<T> | null | undefined} v
  2100. * @returns {T[]}
  2101. */
  2102. function flatten(v) {
  2103. /** @type {T[]} */
  2104. const result = []
  2105. if (v) {
  2106. if (isIterable(v)) {
  2107. result.push(...v)
  2108. } else {
  2109. result.push(v)
  2110. }
  2111. }
  2112. return result
  2113. }
  2114. /**
  2115. * @param {*} v
  2116. * @returns {v is Iterable<any>}
  2117. */
  2118. function isIterable(v) {
  2119. return v && Symbol.iterator in v
  2120. }
  2121. // ------------------------------------------------------------------------------
  2122. // Nodejs Helpers
  2123. // ------------------------------------------------------------------------------
  2124. /**
  2125. * @param {String} filename
  2126. */
  2127. function createRequire(filename) {
  2128. const Module = require('module')
  2129. const moduleCreateRequire =
  2130. // Added in v12.2.0
  2131. Module.createRequire ||
  2132. // Added in v10.12.0, but deprecated in v12.2.0.
  2133. Module.createRequireFromPath ||
  2134. // Polyfill - This is not executed on the tests on node@>=10.
  2135. /**
  2136. * @param {string} filename
  2137. */
  2138. function (filename) {
  2139. const mod = new Module(filename)
  2140. mod.filename = filename
  2141. // @ts-ignore
  2142. mod.paths = Module._nodeModulePaths(path.dirname(filename))
  2143. // @ts-ignore
  2144. mod._compile('module.exports = require;', filename)
  2145. return mod.exports
  2146. }
  2147. return moduleCreateRequire(filename)
  2148. }
  2149. // ------------------------------------------------------------------------------
  2150. // Rule Helpers
  2151. // ------------------------------------------------------------------------------
  2152. /**
  2153. * Register the given visitor to parser services.
  2154. * If the parser service of `vue-eslint-parser` was not found,
  2155. * this generates a warning.
  2156. *
  2157. * @param {RuleContext} context The rule context to use parser services.
  2158. * @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body.
  2159. * @param {RuleListener} [scriptVisitor] The visitor to traverse the script.
  2160. * @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options.
  2161. * @returns {RuleListener} The merged visitor.
  2162. */
  2163. function defineTemplateBodyVisitor(
  2164. context,
  2165. templateBodyVisitor,
  2166. scriptVisitor,
  2167. options
  2168. ) {
  2169. const sourceCode = context.getSourceCode()
  2170. if (sourceCode.parserServices.defineTemplateBodyVisitor == null) {
  2171. const filename = context.getFilename()
  2172. if (path.extname(filename) === '.vue') {
  2173. context.report({
  2174. loc: { line: 1, column: 0 },
  2175. message:
  2176. 'Use the latest vue-eslint-parser. See also https://eslint.vuejs.org/user-guide/#what-is-the-use-the-latest-vue-eslint-parser-error.'
  2177. })
  2178. }
  2179. return {}
  2180. }
  2181. return sourceCode.parserServices.defineTemplateBodyVisitor(
  2182. templateBodyVisitor,
  2183. scriptVisitor,
  2184. options
  2185. )
  2186. }
  2187. /**
  2188. * Register the given visitor to parser services.
  2189. * If the parser service of `vue-eslint-parser` was not found,
  2190. * this generates a warning.
  2191. *
  2192. * @param {RuleContext} context The rule context to use parser services.
  2193. * @param {TemplateListener} documentVisitor The visitor to traverse the document.
  2194. * @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options.
  2195. * @returns {RuleListener} The merged visitor.
  2196. */
  2197. function defineDocumentVisitor(context, documentVisitor, options) {
  2198. const sourceCode = context.getSourceCode()
  2199. if (sourceCode.parserServices.defineDocumentVisitor == null) {
  2200. const filename = context.getFilename()
  2201. if (path.extname(filename) === '.vue') {
  2202. context.report({
  2203. loc: { line: 1, column: 0 },
  2204. message:
  2205. 'Use the latest vue-eslint-parser. See also https://eslint.vuejs.org/user-guide/#what-is-the-use-the-latest-vue-eslint-parser-error.'
  2206. })
  2207. }
  2208. return {}
  2209. }
  2210. return sourceCode.parserServices.defineDocumentVisitor(
  2211. documentVisitor,
  2212. options
  2213. )
  2214. }
  2215. /**
  2216. * @template T
  2217. * @param {T} visitor
  2218. * @param {...(TemplateListener | RuleListener | NodeListener)} visitors
  2219. * @returns {T}
  2220. */
  2221. function compositingVisitors(visitor, ...visitors) {
  2222. for (const v of visitors) {
  2223. for (const key in v) {
  2224. // @ts-expect-error
  2225. if (visitor[key]) {
  2226. // @ts-expect-error
  2227. const o = visitor[key]
  2228. // @ts-expect-error
  2229. visitor[key] = (...args) => {
  2230. o(...args)
  2231. // @ts-expect-error
  2232. v[key](...args)
  2233. }
  2234. } else {
  2235. // @ts-expect-error
  2236. visitor[key] = v[key]
  2237. }
  2238. }
  2239. }
  2240. return visitor
  2241. }
  2242. // ------------------------------------------------------------------------------
  2243. // AST Helpers
  2244. // ------------------------------------------------------------------------------
  2245. /**
  2246. * Find the variable of a given identifier.
  2247. * @param {RuleContext} context The rule context
  2248. * @param {Identifier} node The variable name to find.
  2249. * @returns {Variable|null} The found variable or null.
  2250. */
  2251. function findVariableByIdentifier(context, node) {
  2252. return findVariable(getScope(context, node), node)
  2253. }
  2254. /**
  2255. * Finds the property with the given name from the given ObjectExpression node.
  2256. * @param {ObjectExpression} node
  2257. * @param {string} name
  2258. * @param { (p: Property) => boolean } [filter]
  2259. * @returns { (Property) | null}
  2260. */
  2261. function findProperty(node, name, filter) {
  2262. const predicate = filter
  2263. ? /**
  2264. * @param {Property | SpreadElement} prop
  2265. * @returns {prop is Property}
  2266. */
  2267. (prop) =>
  2268. isProperty(prop) && getStaticPropertyName(prop) === name && filter(prop)
  2269. : /**
  2270. * @param {Property | SpreadElement} prop
  2271. * @returns {prop is Property}
  2272. */
  2273. (prop) => isProperty(prop) && getStaticPropertyName(prop) === name
  2274. return node.properties.find(predicate) || null
  2275. }
  2276. /**
  2277. * Finds the assignment property with the given name from the given ObjectPattern node.
  2278. * @param {ObjectPattern} node
  2279. * @param {string} name
  2280. * @param { (p: AssignmentProperty) => boolean } [filter]
  2281. * @returns { (AssignmentProperty) | null}
  2282. */
  2283. function findAssignmentProperty(node, name, filter) {
  2284. const predicate = filter
  2285. ? /**
  2286. * @param {AssignmentProperty | RestElement} prop
  2287. * @returns {prop is AssignmentProperty}
  2288. */
  2289. (prop) =>
  2290. isAssignmentProperty(prop) &&
  2291. getStaticPropertyName(prop) === name &&
  2292. filter(prop)
  2293. : /**
  2294. * @param {AssignmentProperty | RestElement} prop
  2295. * @returns {prop is AssignmentProperty}
  2296. */
  2297. (prop) =>
  2298. isAssignmentProperty(prop) && getStaticPropertyName(prop) === name
  2299. return node.properties.find(predicate) || null
  2300. }
  2301. /**
  2302. * Checks whether the given node is Property.
  2303. * @param {Property | SpreadElement | AssignmentProperty} node
  2304. * @returns {node is Property}
  2305. */
  2306. function isProperty(node) {
  2307. if (node.type !== 'Property') {
  2308. return false
  2309. }
  2310. return !node.parent || node.parent.type === 'ObjectExpression'
  2311. }
  2312. /**
  2313. * Checks whether the given node is AssignmentProperty.
  2314. * @param {AssignmentProperty | RestElement} node
  2315. * @returns {node is AssignmentProperty}
  2316. */
  2317. function isAssignmentProperty(node) {
  2318. return node.type === 'Property'
  2319. }
  2320. /**
  2321. * Checks whether the given node is VElement.
  2322. * @param {VElement | VExpressionContainer | VText} node
  2323. * @returns {node is VElement}
  2324. */
  2325. function isVElement(node) {
  2326. return node.type === 'VElement'
  2327. }
  2328. /**
  2329. * Checks whether the given node is in export default.
  2330. * @param {ASTNode} node
  2331. * @returns {boolean}
  2332. */
  2333. function isInExportDefault(node) {
  2334. /** @type {ASTNode | null} */
  2335. let parent = node.parent
  2336. while (parent) {
  2337. if (parent.type === 'ExportDefaultDeclaration') {
  2338. return true
  2339. }
  2340. parent = parent.parent
  2341. }
  2342. return false
  2343. }
  2344. /**
  2345. * Retrieve `TSAsExpression#expression` value if the given node a `TSAsExpression` node. Otherwise, pass through it.
  2346. * @template T Node type
  2347. * @param {T | TSAsExpression} node The node to address.
  2348. * @returns {T} The `TSAsExpression#expression` value if the node is a `TSAsExpression` node. Otherwise, the node.
  2349. */
  2350. function skipTSAsExpression(node) {
  2351. if (!node) {
  2352. return node
  2353. }
  2354. // @ts-expect-error
  2355. if (node.type === 'TSAsExpression') {
  2356. // @ts-expect-error
  2357. return skipTSAsExpression(node.expression)
  2358. }
  2359. // @ts-expect-error
  2360. return node
  2361. }
  2362. /**
  2363. * Gets the parent node of the given node. This method returns a value ignoring `X as F`.
  2364. * @param {Expression} node
  2365. * @returns {ASTNode}
  2366. */
  2367. function getParent(node) {
  2368. let parent = node.parent
  2369. while (parent.type === 'TSAsExpression') {
  2370. parent = parent.parent
  2371. }
  2372. return parent
  2373. }
  2374. /**
  2375. * Checks if the given node is a property value.
  2376. * @param {Property} prop
  2377. * @param {Expression} node
  2378. */
  2379. function isPropertyChain(prop, node) {
  2380. let value = node
  2381. while (value.parent.type === 'TSAsExpression') {
  2382. value = value.parent
  2383. }
  2384. return prop === value.parent && prop.value === value
  2385. }
  2386. /**
  2387. * Retrieve `AssignmentPattern#left` value if the given node a `AssignmentPattern` node. Otherwise, pass through it.
  2388. * @template T Node type
  2389. * @param {T | AssignmentPattern} node The node to address.
  2390. * @return {T} The `AssignmentPattern#left` value if the node is a `AssignmentPattern` node. Otherwise, the node.
  2391. */
  2392. function skipDefaultParamValue(node) {
  2393. if (!node) {
  2394. return node
  2395. }
  2396. // @ts-expect-error
  2397. if (node.type === 'AssignmentPattern') {
  2398. // @ts-expect-error
  2399. return skipDefaultParamValue(node.left)
  2400. }
  2401. // @ts-expect-error
  2402. return node
  2403. }
  2404. /**
  2405. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  2406. * @template T Node type
  2407. * @param {T | ChainExpression} node The node to address.
  2408. * @returns {T} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
  2409. */
  2410. function skipChainExpression(node) {
  2411. if (!node) {
  2412. return node
  2413. }
  2414. // @ts-expect-error
  2415. if (node.type === 'ChainExpression') {
  2416. // @ts-expect-error
  2417. return skipChainExpression(node.expression)
  2418. }
  2419. // @ts-expect-error
  2420. return node
  2421. }
  2422. /**
  2423. * Checks whether the given node is in a type annotation.
  2424. * @param {ESNode} node
  2425. * @returns {boolean}
  2426. */
  2427. function withinTypeNode(node) {
  2428. /** @type {ASTNode | null} */
  2429. let target = node
  2430. while (target) {
  2431. if (isTypeNode(target)) {
  2432. return true
  2433. }
  2434. target = target.parent
  2435. }
  2436. return false
  2437. }
  2438. /**
  2439. * Gets the property name of a given node.
  2440. * @param {Property|AssignmentProperty|MethodDefinition|MemberExpression} node - The node to get.
  2441. * @return {string|null} The property name if static. Otherwise, null.
  2442. */
  2443. function getStaticPropertyName(node) {
  2444. if (node.type === 'Property' || node.type === 'MethodDefinition') {
  2445. if (!node.computed) {
  2446. const key = node.key
  2447. if (key.type === 'Identifier') {
  2448. return key.name
  2449. }
  2450. }
  2451. const key = node.key
  2452. // @ts-expect-error
  2453. return getStringLiteralValue(key)
  2454. } else if (node.type === 'MemberExpression') {
  2455. if (!node.computed) {
  2456. const property = node.property
  2457. if (property.type === 'Identifier') {
  2458. return property.name
  2459. }
  2460. return null
  2461. }
  2462. const property = node.property
  2463. // @ts-expect-error
  2464. return getStringLiteralValue(property)
  2465. }
  2466. return null
  2467. }
  2468. /**
  2469. * Gets the string of a given node.
  2470. * @param {Literal|TemplateLiteral} node - The node to get.
  2471. * @param {boolean} [stringOnly]
  2472. * @return {string|null} The string if static. Otherwise, null.
  2473. */
  2474. function getStringLiteralValue(node, stringOnly) {
  2475. if (node.type === 'Literal') {
  2476. if (node.value == null) {
  2477. if (!stringOnly && node.bigint != null) {
  2478. return node.bigint
  2479. }
  2480. return null
  2481. }
  2482. if (typeof node.value === 'string') {
  2483. return node.value
  2484. }
  2485. if (!stringOnly) {
  2486. return String(node.value)
  2487. }
  2488. return null
  2489. }
  2490. if (
  2491. node.type === 'TemplateLiteral' &&
  2492. node.expressions.length === 0 &&
  2493. node.quasis.length === 1
  2494. ) {
  2495. return node.quasis[0].value.cooked
  2496. }
  2497. return null
  2498. }
  2499. /**
  2500. * Gets the VExpressionContainer of a given node.
  2501. * @param {ASTNode} node - The node to get.
  2502. * @return {VExpressionContainer|null}
  2503. */
  2504. function getVExpressionContainer(node) {
  2505. /** @type {ASTNode | null} */
  2506. let n = node
  2507. while (n && n.type !== 'VExpressionContainer') {
  2508. n = n.parent
  2509. }
  2510. return n
  2511. }
  2512. /**
  2513. * @param {string} path
  2514. */
  2515. function isTypeScriptFile(path) {
  2516. return path.endsWith('.ts') || path.endsWith('.tsx') || path.endsWith('.mts')
  2517. }
  2518. // ------------------------------------------------------------------------------
  2519. // ESLint Helpers
  2520. // ------------------------------------------------------------------------------
  2521. /**
  2522. * Marks a variable with the given name in the current scope as used. This affects the no-unused-vars rule.
  2523. * @param {RuleContext} context
  2524. * @param {string} name
  2525. * @param {ASTNode} node The node to get the current scope.
  2526. */
  2527. function markVariableAsUsed(context, name, node) {
  2528. const sourceCode = context.getSourceCode()
  2529. if (sourceCode.markVariableAsUsed) {
  2530. sourceCode.markVariableAsUsed(name, node)
  2531. } else {
  2532. // This function does not use the given node, but the currently visited node.
  2533. // If we need to determine the scope of a given node, we need to implement it yourself.
  2534. context.markVariableAsUsed?.(name)
  2535. }
  2536. }
  2537. // ------------------------------------------------------------------------------
  2538. // Vue Helpers
  2539. // ------------------------------------------------------------------------------
  2540. /**
  2541. * @param {string} path
  2542. */
  2543. function isVueFile(path) {
  2544. return path.endsWith('.vue') || path.endsWith('.jsx') || path.endsWith('.tsx')
  2545. }
  2546. /**
  2547. * Checks whether the current file is uses `<script setup>`
  2548. * @param {RuleContext} context The ESLint rule context object.
  2549. */
  2550. function isScriptSetup(context) {
  2551. return Boolean(getScriptSetupElement(context))
  2552. }
  2553. /**
  2554. * Gets the element of `<script setup>`
  2555. * @param {RuleContext} context The ESLint rule context object.
  2556. * @returns {VElement | null} the element of `<script setup>`
  2557. */
  2558. function getScriptSetupElement(context) {
  2559. const sourceCode = context.getSourceCode()
  2560. const df =
  2561. sourceCode.parserServices.getDocumentFragment &&
  2562. sourceCode.parserServices.getDocumentFragment()
  2563. if (!df) {
  2564. return null
  2565. }
  2566. const scripts = df.children.filter(
  2567. /** @returns {e is VElement} */
  2568. (e) => isVElement(e) && e.name === 'script'
  2569. )
  2570. if (scripts.length === 2) {
  2571. return scripts.find((e) => hasAttribute(e, 'setup')) || null
  2572. } else {
  2573. const script = scripts[0]
  2574. if (script && hasAttribute(script, 'setup')) {
  2575. return script
  2576. }
  2577. }
  2578. return null
  2579. }
  2580. /**
  2581. * Check whether the given node is a Vue component based
  2582. * on the filename and default export type
  2583. * export default {} in .vue || .jsx
  2584. * @param {ESNode} node Node to check
  2585. * @param {string} path File name with extension
  2586. * @returns {boolean}
  2587. */
  2588. function isVueComponentFile(node, path) {
  2589. return (
  2590. isVueFile(path) &&
  2591. node.type === 'ExportDefaultDeclaration' &&
  2592. node.declaration.type === 'ObjectExpression'
  2593. )
  2594. }
  2595. /**
  2596. * Get the Vue component definition type from given node
  2597. * Vue.component('xxx', {}) || component('xxx', {})
  2598. * @param {ObjectExpression} node Node to check
  2599. * @returns {'component' | 'mixin' | 'extend' | 'createApp' | 'defineComponent' | null}
  2600. */
  2601. function getVueComponentDefinitionType(node) {
  2602. const parent = getParent(node)
  2603. if (parent.type === 'CallExpression') {
  2604. const callee = parent.callee
  2605. if (callee.type === 'MemberExpression') {
  2606. const calleeObject = skipTSAsExpression(callee.object)
  2607. if (calleeObject.type === 'Identifier') {
  2608. const propName = getStaticPropertyName(callee)
  2609. if (calleeObject.name === 'Vue') {
  2610. // for Vue.js 2.x
  2611. // Vue.component('xxx', {}) || Vue.mixin({}) || Vue.extend('xxx', {})
  2612. const maybeFullVueComponentForVue2 =
  2613. propName && isObjectArgument(parent)
  2614. return maybeFullVueComponentForVue2 &&
  2615. (propName === 'component' ||
  2616. propName === 'mixin' ||
  2617. propName === 'extend')
  2618. ? propName
  2619. : null
  2620. }
  2621. // for Vue.js 3.x
  2622. // app.component('xxx', {}) || app.mixin({})
  2623. const maybeFullVueComponent = propName && isObjectArgument(parent)
  2624. return maybeFullVueComponent &&
  2625. (propName === 'component' || propName === 'mixin')
  2626. ? propName
  2627. : null
  2628. }
  2629. }
  2630. if (callee.type === 'Identifier') {
  2631. if (callee.name === 'component') {
  2632. // for Vue.js 2.x
  2633. // component('xxx', {})
  2634. const isDestructedVueComponent = isObjectArgument(parent)
  2635. return isDestructedVueComponent ? 'component' : null
  2636. }
  2637. if (callee.name === 'createApp') {
  2638. // for Vue.js 3.x
  2639. // createApp({})
  2640. const isAppVueComponent = isObjectArgument(parent)
  2641. return isAppVueComponent ? 'createApp' : null
  2642. }
  2643. if (callee.name === 'defineComponent') {
  2644. // for Vue.js 3.x
  2645. // defineComponent({})
  2646. const isDestructedVueComponent = isObjectArgument(parent)
  2647. return isDestructedVueComponent ? 'defineComponent' : null
  2648. }
  2649. }
  2650. }
  2651. return null
  2652. }
  2653. /** @param {CallExpression} node */
  2654. function isObjectArgument(node) {
  2655. return (
  2656. node.arguments.length > 0 &&
  2657. skipTSAsExpression(node.arguments.slice(-1)[0]).type === 'ObjectExpression'
  2658. )
  2659. }
  2660. /**
  2661. * Check whether given node is new Vue instance
  2662. * new Vue({})
  2663. * @param {NewExpression} node Node to check
  2664. * @returns {boolean}
  2665. */
  2666. function isVueInstance(node) {
  2667. const callee = node.callee
  2668. return Boolean(
  2669. node.type === 'NewExpression' &&
  2670. callee.type === 'Identifier' &&
  2671. callee.name === 'Vue' &&
  2672. node.arguments.length > 0 &&
  2673. skipTSAsExpression(node.arguments[0]).type === 'ObjectExpression'
  2674. )
  2675. }
  2676. /**
  2677. * If the given object is a Vue component or instance, returns the Vue definition type.
  2678. * @param {RuleContext} context The ESLint rule context object.
  2679. * @param {ObjectExpression} node Node to check
  2680. * @returns { VueObjectType | null } The Vue definition type.
  2681. */
  2682. function getVueObjectType(context, node) {
  2683. if (node.type !== 'ObjectExpression') {
  2684. return null
  2685. }
  2686. const parent = getParent(node)
  2687. switch (parent.type) {
  2688. case 'ExportDefaultDeclaration': {
  2689. // export default {} in .vue || .jsx
  2690. const filePath = context.getFilename()
  2691. if (
  2692. isVueComponentFile(parent, filePath) &&
  2693. skipTSAsExpression(parent.declaration) === node
  2694. ) {
  2695. const scriptSetup = getScriptSetupElement(context)
  2696. if (
  2697. scriptSetup &&
  2698. scriptSetup.range[0] <= parent.range[0] &&
  2699. parent.range[1] <= scriptSetup.range[1]
  2700. ) {
  2701. // `export default` in `<script setup>`
  2702. return null
  2703. }
  2704. return 'export'
  2705. }
  2706. break
  2707. }
  2708. case 'CallExpression': {
  2709. // Vue.component('xxx', {}) || component('xxx', {})
  2710. if (
  2711. getVueComponentDefinitionType(node) != null &&
  2712. skipTSAsExpression(parent.arguments.slice(-1)[0]) === node
  2713. ) {
  2714. return 'definition'
  2715. }
  2716. break
  2717. }
  2718. case 'NewExpression': {
  2719. // new Vue({})
  2720. if (
  2721. isVueInstance(parent) &&
  2722. skipTSAsExpression(parent.arguments[0]) === node
  2723. ) {
  2724. return 'instance'
  2725. }
  2726. break
  2727. }
  2728. // No default
  2729. }
  2730. if (
  2731. getComponentComments(context).some(
  2732. (el) => el.loc.end.line === node.loc.start.line - 1
  2733. )
  2734. ) {
  2735. return 'mark'
  2736. }
  2737. return null
  2738. }
  2739. /**
  2740. * Checks whether the given object is an SFC definition.
  2741. * @param {RuleContext} context The ESLint rule context object.
  2742. * @param {ObjectExpression} node Node to check
  2743. * @returns { boolean } `true`, the given object is an SFC definition.
  2744. */
  2745. function isSFCObject(context, node) {
  2746. if (node.type !== 'ObjectExpression') {
  2747. return false
  2748. }
  2749. const filePath = context.getFilename()
  2750. const ext = path.extname(filePath)
  2751. if (ext !== '.vue' && ext) {
  2752. return false
  2753. }
  2754. return isSFC(node)
  2755. /**
  2756. * @param {Expression} node
  2757. * @returns {boolean}
  2758. */
  2759. function isSFC(node) {
  2760. const parent = getParent(node)
  2761. switch (parent.type) {
  2762. case 'ExportDefaultDeclaration': {
  2763. // export default {}
  2764. if (skipTSAsExpression(parent.declaration) !== node) {
  2765. return false
  2766. }
  2767. const scriptSetup = getScriptSetupElement(context)
  2768. if (
  2769. scriptSetup &&
  2770. scriptSetup.range[0] <= parent.range[0] &&
  2771. parent.range[1] <= scriptSetup.range[1]
  2772. ) {
  2773. // `export default` in `<script setup>`
  2774. return false
  2775. }
  2776. return true
  2777. }
  2778. case 'CallExpression': {
  2779. if (parent.arguments.every((arg) => skipTSAsExpression(arg) !== node)) {
  2780. return false
  2781. }
  2782. const { callee } = parent
  2783. if (
  2784. (callee.type === 'Identifier' && callee.name === 'defineComponent') ||
  2785. (callee.type === 'MemberExpression' &&
  2786. callee.object.type === 'Identifier' &&
  2787. callee.object.name === 'Vue' &&
  2788. callee.property.type === 'Identifier' &&
  2789. callee.property.name === 'extend')
  2790. ) {
  2791. return isSFC(parent)
  2792. }
  2793. return false
  2794. }
  2795. case 'VariableDeclarator': {
  2796. if (
  2797. skipTSAsExpression(parent.init) !== node ||
  2798. parent.id.type !== 'Identifier'
  2799. ) {
  2800. return false
  2801. }
  2802. const variable = findVariable(getScope(context, node), parent.id)
  2803. if (!variable) {
  2804. return false
  2805. }
  2806. return variable.references.some((ref) => isSFC(ref.identifier))
  2807. }
  2808. // No default
  2809. }
  2810. return false
  2811. }
  2812. }
  2813. /**
  2814. * Gets the component comments of a given context.
  2815. * @param {RuleContext} context The ESLint rule context object.
  2816. * @return {Token[]} The the component comments.
  2817. */
  2818. function getComponentComments(context) {
  2819. let tokens = componentComments.get(context)
  2820. if (tokens) {
  2821. return tokens
  2822. }
  2823. const sourceCode = context.getSourceCode()
  2824. tokens = sourceCode
  2825. .getAllComments()
  2826. .filter((comment) => /@vue\/component/g.test(comment.value))
  2827. componentComments.set(context, tokens)
  2828. return tokens
  2829. }
  2830. /**
  2831. * Return generator with the all handler nodes defined in the given watcher property.
  2832. * @param {Property|Expression} property
  2833. * @returns {IterableIterator<Expression>}
  2834. */
  2835. function* iterateWatchHandlerValues(property) {
  2836. const value = property.type === 'Property' ? property.value : property
  2837. if (value.type === 'ObjectExpression') {
  2838. const handler = findProperty(value, 'handler')
  2839. if (handler) {
  2840. yield handler.value
  2841. }
  2842. } else if (value.type === 'ArrayExpression') {
  2843. for (const element of value.elements.filter(isDef)) {
  2844. if (element.type !== 'SpreadElement') {
  2845. yield* iterateWatchHandlerValues(element)
  2846. }
  2847. }
  2848. } else {
  2849. yield value
  2850. }
  2851. }
  2852. /**
  2853. * Get the attribute which has the given name.
  2854. * @param {VElement} node The start tag node to check.
  2855. * @param {string} name The attribute name to check.
  2856. * @param {string} [value] The attribute value to check.
  2857. * @returns {VAttribute | null} The found attribute.
  2858. */
  2859. function getAttribute(node, name, value) {
  2860. return (
  2861. node.startTag.attributes.find(
  2862. /**
  2863. * @param {VAttribute | VDirective} node
  2864. * @returns {node is VAttribute}
  2865. */
  2866. (node) =>
  2867. !node.directive &&
  2868. node.key.name === name &&
  2869. (value === undefined ||
  2870. (node.value != null && node.value.value === value))
  2871. ) || null
  2872. )
  2873. }
  2874. /**
  2875. * Get the directive list which has the given name.
  2876. * @param {VElement | VStartTag} node The start tag node to check.
  2877. * @param {string} name The directive name to check.
  2878. * @returns {VDirective[]} The array of `v-slot` directives.
  2879. */
  2880. function getDirectives(node, name) {
  2881. const attributes =
  2882. node.type === 'VElement' ? node.startTag.attributes : node.attributes
  2883. return attributes.filter(
  2884. /**
  2885. * @param {VAttribute | VDirective} node
  2886. * @returns {node is VDirective}
  2887. */
  2888. (node) => node.directive && node.key.name.name === name
  2889. )
  2890. }
  2891. /**
  2892. * Get the directive which has the given name.
  2893. * @param {VElement} node The start tag node to check.
  2894. * @param {string} name The directive name to check.
  2895. * @param {string} [argument] The directive argument to check.
  2896. * @returns {VDirective | null} The found directive.
  2897. */
  2898. function getDirective(node, name, argument) {
  2899. return (
  2900. node.startTag.attributes.find(
  2901. /**
  2902. * @param {VAttribute | VDirective} node
  2903. * @returns {node is VDirective}
  2904. */
  2905. (node) =>
  2906. node.directive &&
  2907. node.key.name.name === name &&
  2908. (argument === undefined ||
  2909. (node.key.argument &&
  2910. node.key.argument.type === 'VIdentifier' &&
  2911. node.key.argument.name) === argument)
  2912. ) || null
  2913. )
  2914. }
  2915. /**
  2916. * Check whether the given start tag has specific directive.
  2917. * @param {VElement} node The start tag node to check.
  2918. * @param {string} name The attribute name to check.
  2919. * @param {string} [value] The attribute value to check.
  2920. * @returns {boolean} `true` if the start tag has the attribute.
  2921. */
  2922. function hasAttribute(node, name, value) {
  2923. return Boolean(getAttribute(node, name, value))
  2924. }
  2925. /**
  2926. * Check whether the given start tag has specific directive.
  2927. * @param {VElement} node The start tag node to check.
  2928. * @param {string} name The directive name to check.
  2929. * @param {string} [argument] The directive argument to check.
  2930. * @returns {boolean} `true` if the start tag has the directive.
  2931. */
  2932. function hasDirective(node, name, argument) {
  2933. return Boolean(getDirective(node, name, argument))
  2934. }
  2935. /**
  2936. * Check whether the given directive node is v-bind same-name shorthand.
  2937. * @param {VAttribute | VDirective} node The directive node to check.
  2938. * @returns {node is VDirective & { value: VExpressionContainer & { expression: Identifier } }} `true` if the directive node is v-bind same-name shorthand.
  2939. */
  2940. function isVBindSameNameShorthand(node) {
  2941. return (
  2942. node.directive &&
  2943. node.key.name.name === 'bind' &&
  2944. node.value?.expression?.type === 'Identifier' &&
  2945. node.key.range[0] <= node.value.range[0] &&
  2946. node.value.range[1] <= node.key.range[1]
  2947. )
  2948. }
  2949. /**
  2950. * Checks whether given defineProps call node has withDefaults.
  2951. * @param {CallExpression} node The node of defineProps
  2952. * @returns {node is CallExpression & { parent: CallExpression }}
  2953. */
  2954. function hasWithDefaults(node) {
  2955. return (
  2956. node.parent &&
  2957. node.parent.type === 'CallExpression' &&
  2958. node.parent.arguments[0] === node &&
  2959. node.parent.callee.type === 'Identifier' &&
  2960. node.parent.callee.name === 'withDefaults'
  2961. )
  2962. }
  2963. /**
  2964. * Get the withDefaults call node from given defineProps call node.
  2965. * @param {CallExpression} node The node of defineProps
  2966. * @returns {CallExpression | null}
  2967. */
  2968. function getWithDefaults(node) {
  2969. return hasWithDefaults(node) ? node.parent : null
  2970. }
  2971. /**
  2972. * Gets a map of the property nodes defined in withDefaults.
  2973. * @param {CallExpression} node The node of defineProps
  2974. * @returns { { [key: string]: Property | undefined } }
  2975. */
  2976. function getWithDefaultsProps(node) {
  2977. if (!hasWithDefaults(node)) {
  2978. return {}
  2979. }
  2980. const param = node.parent.arguments[1]
  2981. if (!param || param.type !== 'ObjectExpression') {
  2982. return {}
  2983. }
  2984. /** @type {Record<string, Property>} */
  2985. const result = {}
  2986. for (const prop of param.properties) {
  2987. if (prop.type !== 'Property') {
  2988. continue
  2989. }
  2990. const name = getStaticPropertyName(prop)
  2991. if (name != null) {
  2992. result[name] = prop
  2993. }
  2994. }
  2995. return result
  2996. }
  2997. /**
  2998. * Gets the props destructure property nodes for defineProp.
  2999. * @param {CallExpression} node The node of defineProps
  3000. * @returns { Record<string, AssignmentProperty | undefined> }
  3001. */
  3002. function getPropsDestructure(node) {
  3003. /** @type {ReturnType<typeof getPropsDestructure>} */
  3004. const result = Object.create(null)
  3005. const left = getLeftOfDefineProps(node)
  3006. if (!left || left.type !== 'ObjectPattern') {
  3007. return result
  3008. }
  3009. for (const prop of left.properties) {
  3010. if (prop.type !== 'Property') continue
  3011. const name = getStaticPropertyName(prop)
  3012. if (name != null) {
  3013. result[name] = prop
  3014. }
  3015. }
  3016. return result
  3017. }
  3018. /**
  3019. * Gets the default definition nodes for defineProp
  3020. * using the props destructure with assignment pattern.
  3021. * @param {CallExpression} node The node of defineProps
  3022. * @returns { Record<string, {prop: AssignmentProperty , expression: Expression} | undefined> }
  3023. */
  3024. function getDefaultPropExpressionsForPropsDestructure(node) {
  3025. /** @type {ReturnType<typeof getDefaultPropExpressionsForPropsDestructure>} */
  3026. const result = Object.create(null)
  3027. for (const [name, prop] of Object.entries(getPropsDestructure(node))) {
  3028. if (!prop) continue
  3029. const value = prop.value
  3030. if (value.type !== 'AssignmentPattern') continue
  3031. result[name] = { prop, expression: value.right }
  3032. }
  3033. return result
  3034. }
  3035. /**
  3036. * Gets the pattern of the left operand of defineProps.
  3037. * @param {CallExpression} node The node of defineProps
  3038. * @returns {Pattern | null} The pattern of the left operand of defineProps
  3039. */
  3040. function getLeftOfDefineProps(node) {
  3041. let target = node
  3042. if (hasWithDefaults(target)) {
  3043. target = target.parent
  3044. }
  3045. if (!target.parent) {
  3046. return null
  3047. }
  3048. if (
  3049. target.parent.type === 'VariableDeclarator' &&
  3050. target.parent.init === target
  3051. ) {
  3052. return target.parent.id
  3053. }
  3054. return null
  3055. }
  3056. /**
  3057. * Get all props from component options object.
  3058. * @param {ObjectExpression} componentObject Object with component definition
  3059. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  3060. */
  3061. function getComponentPropsFromOptions(componentObject) {
  3062. const propsNode = componentObject.properties.find(
  3063. /**
  3064. * @param {ESNode} p
  3065. * @returns {p is (Property & { key: Identifier & {name: 'props'} })}
  3066. */
  3067. (p) => p.type === 'Property' && getStaticPropertyName(p) === 'props'
  3068. )
  3069. if (!propsNode) {
  3070. return []
  3071. }
  3072. if (
  3073. propsNode.value.type !== 'ObjectExpression' &&
  3074. propsNode.value.type !== 'ArrayExpression'
  3075. ) {
  3076. return [
  3077. {
  3078. type: 'unknown',
  3079. propName: null,
  3080. node: propsNode.value
  3081. }
  3082. ]
  3083. }
  3084. return getComponentPropsFromDefine(propsNode.value)
  3085. }
  3086. /**
  3087. * Get all emits from component options object.
  3088. * @param {ObjectExpression} componentObject Object with component definition
  3089. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits
  3090. */
  3091. function getComponentEmitsFromOptions(componentObject) {
  3092. const emitsNode = componentObject.properties.find(
  3093. /**
  3094. * @param {ESNode} p
  3095. * @returns {p is (Property & { key: Identifier & {name: 'emits'} })}
  3096. */
  3097. (p) => p.type === 'Property' && getStaticPropertyName(p) === 'emits'
  3098. )
  3099. if (!emitsNode) {
  3100. return []
  3101. }
  3102. if (
  3103. emitsNode.value.type !== 'ObjectExpression' &&
  3104. emitsNode.value.type !== 'ArrayExpression'
  3105. ) {
  3106. return [
  3107. {
  3108. type: 'unknown',
  3109. emitName: null,
  3110. node: emitsNode.value
  3111. }
  3112. ]
  3113. }
  3114. return getComponentEmitsFromDefine(emitsNode.value)
  3115. }
  3116. /**
  3117. * Get all props from `defineProps` call expression.
  3118. * @param {RuleContext} context The rule context object.
  3119. * @param {CallExpression} node `defineProps` call expression
  3120. * @return {ComponentProp[]} Array of component props
  3121. */
  3122. function getComponentPropsFromDefineProps(context, node) {
  3123. if (node.arguments.length > 0) {
  3124. const defNode = getObjectOrArray(context, node.arguments[0])
  3125. if (defNode) {
  3126. return getComponentPropsFromDefine(defNode)
  3127. }
  3128. return [
  3129. {
  3130. type: 'unknown',
  3131. propName: null,
  3132. node: node.arguments[0]
  3133. }
  3134. ]
  3135. }
  3136. const typeArguments =
  3137. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3138. if (typeArguments && typeArguments.params.length > 0) {
  3139. return getComponentPropsFromTypeDefine(context, typeArguments.params[0])
  3140. }
  3141. return [
  3142. {
  3143. type: 'unknown',
  3144. propName: null,
  3145. node: null
  3146. }
  3147. ]
  3148. }
  3149. /**
  3150. * Get all emits from `defineEmits` call expression.
  3151. * @param {RuleContext} context The rule context object.
  3152. * @param {CallExpression} node `defineEmits` call expression
  3153. * @return {ComponentEmit[]} Array of component emits
  3154. */
  3155. function getComponentEmitsFromDefineEmits(context, node) {
  3156. if (node.arguments.length > 0) {
  3157. const defNode = getObjectOrArray(context, node.arguments[0])
  3158. if (defNode) {
  3159. return getComponentEmitsFromDefine(defNode)
  3160. }
  3161. return [
  3162. {
  3163. type: 'unknown',
  3164. emitName: null,
  3165. node: node.arguments[0]
  3166. }
  3167. ]
  3168. }
  3169. const typeArguments =
  3170. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3171. if (typeArguments && typeArguments.params.length > 0) {
  3172. return getComponentEmitsFromTypeDefine(context, typeArguments.params[0])
  3173. }
  3174. return [
  3175. {
  3176. type: 'unknown',
  3177. emitName: null,
  3178. node: null
  3179. }
  3180. ]
  3181. }
  3182. /**
  3183. * Get all slots from `defineSlots` call expression.
  3184. * @param {RuleContext} context The rule context object.
  3185. * @param {CallExpression} node `defineSlots` call expression
  3186. * @return {ComponentSlot[]} Array of component slots
  3187. */
  3188. function getComponentSlotsFromDefineSlots(context, node) {
  3189. const typeArguments =
  3190. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3191. if (typeArguments && typeArguments.params.length > 0) {
  3192. return getComponentSlotsFromTypeDefine(context, typeArguments.params[0])
  3193. }
  3194. return [
  3195. {
  3196. type: 'unknown',
  3197. slotName: null,
  3198. node: null
  3199. }
  3200. ]
  3201. }
  3202. /**
  3203. * Get model info from `defineModel` call expression.
  3204. * @param {RuleContext} _context The rule context object.
  3205. * @param {CallExpression} node `defineModel` call expression
  3206. * @return {ComponentModel} Object of component model
  3207. */
  3208. function getComponentModelFromDefineModel(_context, node) {
  3209. /** @type {ComponentModelName} */
  3210. let name = {
  3211. modelName: 'modelValue',
  3212. node: null
  3213. }
  3214. /** @type {Expression|null} */
  3215. let options =
  3216. node.arguments[0]?.type === 'SpreadElement' ? null : node.arguments[0]
  3217. if (node.arguments.length > 0) {
  3218. const nameNodeCandidate = skipTSAsExpression(node.arguments[0])
  3219. if (nameNodeCandidate.type === 'Literal') {
  3220. name = {
  3221. modelName: String(nameNodeCandidate.value),
  3222. node: nameNodeCandidate
  3223. }
  3224. options =
  3225. node.arguments[1]?.type === 'SpreadElement' ? null : node.arguments[1]
  3226. }
  3227. }
  3228. const typeArguments =
  3229. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3230. if (typeArguments && typeArguments.params.length > 0) {
  3231. return {
  3232. name,
  3233. options,
  3234. typeNode: typeArguments.params[0]
  3235. }
  3236. }
  3237. return {
  3238. name,
  3239. options,
  3240. typeNode: null
  3241. }
  3242. }
  3243. /**
  3244. * Get all props by looking at all component's properties
  3245. * @param {ObjectExpression|ArrayExpression} propsNode Object with props definition
  3246. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  3247. */
  3248. function getComponentPropsFromDefine(propsNode) {
  3249. if (propsNode.type === 'ObjectExpression') {
  3250. return propsNode.properties.map(
  3251. /** @returns {ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp} */
  3252. (prop) => {
  3253. if (!isProperty(prop)) {
  3254. return {
  3255. type: 'unknown',
  3256. propName: null,
  3257. node: prop
  3258. }
  3259. }
  3260. const propName = getStaticPropertyName(prop)
  3261. if (propName != null) {
  3262. return {
  3263. type: 'object',
  3264. key: prop.key,
  3265. propName,
  3266. value: skipTSAsExpression(prop.value),
  3267. node: prop
  3268. }
  3269. }
  3270. return {
  3271. type: 'object',
  3272. key: null,
  3273. propName: null,
  3274. value: skipTSAsExpression(prop.value),
  3275. node: prop
  3276. }
  3277. }
  3278. )
  3279. }
  3280. return propsNode.elements.filter(isDef).map((prop) => {
  3281. if (prop.type === 'Literal' || prop.type === 'TemplateLiteral') {
  3282. const propName = getStringLiteralValue(prop)
  3283. if (propName != null) {
  3284. return {
  3285. type: 'array',
  3286. key: prop,
  3287. propName,
  3288. value: null,
  3289. node: prop
  3290. }
  3291. }
  3292. }
  3293. return {
  3294. type: 'array',
  3295. key: null,
  3296. propName: null,
  3297. value: null,
  3298. node: prop
  3299. }
  3300. })
  3301. }
  3302. /**
  3303. * Get all emits by looking at all component's properties
  3304. * @param {ObjectExpression|ArrayExpression} emitsNode Object with emits definition
  3305. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits.
  3306. */
  3307. function getComponentEmitsFromDefine(emitsNode) {
  3308. if (emitsNode.type === 'ObjectExpression') {
  3309. return emitsNode.properties.map((prop) => {
  3310. if (!isProperty(prop)) {
  3311. return {
  3312. type: 'unknown',
  3313. key: null,
  3314. emitName: null,
  3315. value: null,
  3316. node: prop
  3317. }
  3318. }
  3319. const emitName = getStaticPropertyName(prop)
  3320. if (emitName != null) {
  3321. return {
  3322. type: 'object',
  3323. key: prop.key,
  3324. emitName,
  3325. value: skipTSAsExpression(prop.value),
  3326. node: prop
  3327. }
  3328. }
  3329. return {
  3330. type: 'object',
  3331. key: null,
  3332. emitName: null,
  3333. value: skipTSAsExpression(prop.value),
  3334. node: prop
  3335. }
  3336. })
  3337. }
  3338. return emitsNode.elements.filter(isDef).map((emit) => {
  3339. if (emit.type === 'Literal' || emit.type === 'TemplateLiteral') {
  3340. const emitName = getStringLiteralValue(emit)
  3341. if (emitName != null) {
  3342. return {
  3343. type: 'array',
  3344. key: emit,
  3345. emitName,
  3346. value: null,
  3347. node: emit
  3348. }
  3349. }
  3350. }
  3351. return {
  3352. type: 'array',
  3353. key: null,
  3354. emitName: null,
  3355. value: null,
  3356. node: emit
  3357. }
  3358. })
  3359. }
  3360. /**
  3361. * @param {RuleContext} context The rule context object.
  3362. * @param {ESNode} node
  3363. * @returns {ObjectExpression | ArrayExpression | null}
  3364. */
  3365. function getObjectOrArray(context, node) {
  3366. if (node.type === 'ObjectExpression') {
  3367. return node
  3368. }
  3369. if (node.type === 'ArrayExpression') {
  3370. return node
  3371. }
  3372. if (node.type === 'Identifier') {
  3373. const variable = findVariable(getScope(context, node), node)
  3374. if (variable != null && variable.defs.length === 1) {
  3375. const def = variable.defs[0]
  3376. if (
  3377. def.type === 'Variable' &&
  3378. def.parent.kind === 'const' &&
  3379. def.node.id.type === 'Identifier' &&
  3380. def.node.init
  3381. ) {
  3382. return getObjectOrArray(context, def.node.init)
  3383. }
  3384. }
  3385. }
  3386. return null
  3387. }