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