Open History to see the last commit
1import { TSESTree } from '@typescript-eslint/utils'
2import type { ESLintUtils, TSESLint } from '@typescript-eslint/utils'
3β
4type Create = Parameters<
5 ReturnType<typeof ESLintUtils.RuleCreator>
6>[0]['create']
7β
8type Context = Parameters<Create>[0]
9type Options = Parameters<Create>[1]
10type Helpers = {
11 isSpecificTanstackQueryImport: (
12 node: TSESTree.Identifier,
13 source: string,
14 ) => boolean
15 isTanstackQueryImport: (node: TSESTree.Identifier) => boolean
16}
17β
18type EnhancedCreate = (
19 context: Context,
20 options: Options,
21 helpers: Helpers,
22) => ReturnType<Create>
23β
24export function detectTanstackQueryImports(create: EnhancedCreate): Create {
25 return (context, optionsWithDefault) => {
26 const tanstackQueryImportSpecifiers: Array<TSESTree.ImportClause> = []
27β
28 const helpers: Helpers = {
29 isSpecificTanstackQueryImport(node, source) {
30 return !!tanstackQueryImportSpecifiers.find((specifier) => {
31 if (
32 specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier &&
33 specifier.parent.type ===
34 TSESTree.AST_NODE_TYPES.ImportDeclaration &&
35 specifier.parent.source.value === source
36 ) {
37 return node.name === specifier.local.name
38 }
39β
40 return false
41 })
42 },
43 isTanstackQueryImport(node) {
44 return !!tanstackQueryImportSpecifiers.find((specifier) => {
45 if (specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier) {
46 return node.name === specifier.local.name
47 }
48β
49 return false
50 })
51 },
52 }
53β
54 const detectionInstructions: TSESLint.RuleListener = {
55 ImportDeclaration(node) {
56 if (
57 node.specifiers.length > 0 &&
58 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
59 (node.importKind === 'value' || node.importKind === undefined) &&
60 node.source.value.startsWith('@tanstack/') &&
61 node.source.value.endsWith('-query')
62 ) {
63 tanstackQueryImportSpecifiers.push(...node.specifiers)
64 }
65 },
66 }
67β
68 // Call original rule definition
69 const ruleInstructions = create(context, optionsWithDefault, helpers)
70 const enhancedRuleInstructions: TSESLint.RuleListener = {}
71β
72 const allKeys = new Set(
73 Object.keys(detectionInstructions).concat(Object.keys(ruleInstructions)),
74 )
75β
76 // Iterate over ALL instructions keys so we can override original rule instructions
77 // to prevent their execution if conditions to report errors are not met.
78 allKeys.forEach((instruction) => {
79 enhancedRuleInstructions[instruction] = (node) => {
80 if (instruction in detectionInstructions) {
81 detectionInstructions[instruction]?.(node)
82 }
83β
84 const ruleInstruction = ruleInstructions[instruction]
85β
86 // TODO: canReportErrors()
87 if (ruleInstruction) {
88 return ruleInstruction(node)
89 }
90β
91 return undefined
92 }
93 })
94β
95 return enhancedRuleInstructions
96 }
97}