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 node.importKind === 'value' &&
59 node.source.value.startsWith('@tanstack/') &&
60 node.source.value.endsWith('-query')
61 ) {
62 tanstackQueryImportSpecifiers.push(...node.specifiers)
63 }
64 },
65 }
66β
67 // Call original rule definition
68 const ruleInstructions = create(context, optionsWithDefault, helpers)
69 const enhancedRuleInstructions: TSESLint.RuleListener = {}
70β
71 const allKeys = new Set(
72 Object.keys(detectionInstructions).concat(Object.keys(ruleInstructions)),
73 )
74β
75 // Iterate over ALL instructions keys so we can override original rule instructions
76 // to prevent their execution if conditions to report errors are not met.
77 allKeys.forEach((instruction) => {
78 enhancedRuleInstructions[instruction] = (node) => {
79 if (instruction in detectionInstructions) {
80 detectionInstructions[instruction]?.(node)
81 }
82β
83 // TODO: canReportErrors()
84 if (ruleInstructions[instruction]) {
85 return ruleInstructions[instruction]?.(node)
86 }
87β
88 return undefined
89 }
90 })
91β
92 return enhancedRuleInstructions
93 }
94}