66
77const utils = require ( '../utils' )
88
9- /** @param expression {Expression | null} */
10- function expressionIsRef ( expression ) {
11- return (
9+ /**
10+ * @typedef ScriptRef
11+ * @type {{node: Expression, ref: string} }
12+ */
13+
14+ /**
15+ * @param declarator {VariableDeclarator}
16+ * @returns {ScriptRef }
17+ * */
18+ function convertDeclaratorToScriptRef ( declarator ) {
19+ return {
20+ // @ts -ignore
21+ node : declarator . init ,
1222 // @ts -ignore
13- expression ?. callee ?. name === 'ref' ||
23+ ref : declarator . id . name
24+ }
25+ }
26+
27+ /**
28+ * @param body {(Statement | ModuleDeclaration)[]}
29+ * @returns {ScriptRef[] }
30+ * */
31+ function getScriptRefsFromSetupFunction ( body ) {
32+ /** @type {VariableDeclaration[] } */
33+ const variableDeclarations = body . filter (
34+ ( child ) => child . type === 'VariableDeclaration'
35+ )
36+ const variableDeclarators = variableDeclarations . map (
37+ ( declaration ) => declaration . declarations [ 0 ]
38+ )
39+ const refDeclarators = variableDeclarators . filter (
1440 // @ts -ignore
15- expression ?. callee ?. name === 'shallowRef '
41+ ( declarator ) => declarator . init ?. callee ?. name === 'ref '
1642 )
43+
44+ return refDeclarators . map ( convertDeclaratorToScriptRef )
1745}
1846
1947/** @type {import("eslint").Rule.RuleModule } */
@@ -36,40 +64,33 @@ module.exports = {
3664 /** @type Set<string> */
3765 const templateRefs = new Set ( )
3866
39- /**
40- * @typedef ScriptRef
41- * @type {{node: Expression, ref: string} }
42- */
43-
4467 /**
4568 * @type ScriptRef[] */
4669 const scriptRefs = [ ]
4770
4871 return utils . compositingVisitors (
49- utils . defineTemplateBodyVisitor (
50- context ,
51- {
52- 'VAttribute[directive=false]' ( node ) {
53- if ( node . key . name === 'ref' && node . value ?. value ) {
54- templateRefs . add ( node . value . value )
55- }
72+ utils . defineTemplateBodyVisitor ( context , {
73+ 'VAttribute[directive=false]' ( node ) {
74+ if ( node . key . name === 'ref' && node . value ?. value ) {
75+ templateRefs . add ( node . value . value )
5676 }
57- } ,
58- {
59- VariableDeclarator ( declarator ) {
60- if ( ! expressionIsRef ( declarator . init ) ) {
61- return
62- }
77+ }
78+ } ) ,
79+ utils . defineVueVisitor ( context , {
80+ onSetupFunctionEnter ( node ) {
81+ // @ts -ignore
82+ const newScriptRefs = getScriptRefsFromSetupFunction ( node . body . body )
6383
64- scriptRefs . push ( {
65- // @ts -ignore
66- node : declarator . init ,
67- // @ts -ignore
68- ref : declarator . id . name
69- } )
70- }
84+ scriptRefs . push ( ...newScriptRefs )
85+ }
86+ } ) ,
87+ utils . defineScriptSetupVisitor ( context , {
88+ Program ( node ) {
89+ const newScriptRefs = getScriptRefsFromSetupFunction ( node . body )
90+
91+ scriptRefs . push ( ...newScriptRefs )
7192 }
72- ) ,
93+ } ) ,
7394 {
7495 'Program:exit' ( ) {
7596 for ( const templateRef of templateRefs ) {
0 commit comments