@tanstack/eslint-plugin-query 5.91.4 → 5.94.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +5 -6
  2. package/src/rules/exhaustive-deps/exhaustive-deps.rule.ts +14 -14
  3. package/src/rules/exhaustive-deps/exhaustive-deps.utils.ts +159 -0
  4. package/src/utils/ast-utils.ts +13 -1
  5. package/build/legacy/chunk-MUQBIZ2R.js +0 -1027
  6. package/build/legacy/chunk-MUQBIZ2R.js.map +0 -1
  7. package/build/legacy/index.cjs +0 -1096
  8. package/build/legacy/index.cjs.map +0 -1
  9. package/build/legacy/index.d.cts +0 -52
  10. package/build/legacy/index.d.ts +0 -52
  11. package/build/legacy/index.js +0 -50
  12. package/build/legacy/index.js.map +0 -1
  13. package/build/legacy/rules.cjs +0 -1053
  14. package/build/legacy/rules.cjs.map +0 -1
  15. package/build/legacy/rules.d.cts +0 -6
  16. package/build/legacy/rules.d.ts +0 -6
  17. package/build/legacy/rules.js +0 -7
  18. package/build/legacy/rules.js.map +0 -1
  19. package/build/legacy/types.cjs +0 -19
  20. package/build/legacy/types.cjs.map +0 -1
  21. package/build/legacy/types.d.cts +0 -5
  22. package/build/legacy/types.d.ts +0 -5
  23. package/build/legacy/types.js +0 -1
  24. package/build/legacy/types.js.map +0 -1
  25. package/build/modern/chunk-2FPOGBVA.js +0 -1019
  26. package/build/modern/chunk-2FPOGBVA.js.map +0 -1
  27. package/build/modern/index.cjs +0 -1089
  28. package/build/modern/index.cjs.map +0 -1
  29. package/build/modern/index.d.cts +0 -52
  30. package/build/modern/index.d.ts +0 -52
  31. package/build/modern/index.js +0 -50
  32. package/build/modern/index.js.map +0 -1
  33. package/build/modern/rules.cjs +0 -1046
  34. package/build/modern/rules.cjs.map +0 -1
  35. package/build/modern/rules.d.cts +0 -6
  36. package/build/modern/rules.d.ts +0 -6
  37. package/build/modern/rules.js +0 -7
  38. package/build/modern/rules.js.map +0 -1
  39. package/build/modern/types.cjs +0 -20
  40. package/build/modern/types.cjs.map +0 -1
  41. package/build/modern/types.d.cts +0 -5
  42. package/build/modern/types.d.ts +0 -5
  43. package/build/modern/types.js +0 -1
  44. package/build/modern/types.js.map +0 -1
@@ -1,1046 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name8 in all)
8
- __defProp(target, name8, { get: all[name8], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/rules.ts
21
- var rules_exports = {};
22
- __export(rules_exports, {
23
- rules: () => rules
24
- });
25
- module.exports = __toCommonJS(rules_exports);
26
-
27
- // src/rules/exhaustive-deps/exhaustive-deps.rule.ts
28
- var import_utils4 = require("@typescript-eslint/utils");
29
-
30
- // src/utils/ast-utils.ts
31
- var import_utils = require("@typescript-eslint/utils");
32
-
33
- // src/utils/unique-by.ts
34
- function uniqueBy(arr, fn) {
35
- return arr.filter((x, i, a) => a.findIndex((y) => fn(x) === fn(y)) === i);
36
- }
37
-
38
- // src/utils/ast-utils.ts
39
- var ASTUtils = {
40
- isNodeOfOneOf(node, types) {
41
- return types.includes(node.type);
42
- },
43
- isIdentifier(node) {
44
- return node.type === import_utils.AST_NODE_TYPES.Identifier;
45
- },
46
- isIdentifierWithName(node, name8) {
47
- return ASTUtils.isIdentifier(node) && node.name === name8;
48
- },
49
- isIdentifierWithOneOfNames(node, name8) {
50
- return ASTUtils.isIdentifier(node) && name8.includes(node.name);
51
- },
52
- isProperty(node) {
53
- return node.type === import_utils.AST_NODE_TYPES.Property;
54
- },
55
- isObjectExpression(node) {
56
- return node.type === import_utils.AST_NODE_TYPES.ObjectExpression;
57
- },
58
- isPropertyWithIdentifierKey(node, key) {
59
- return ASTUtils.isProperty(node) && ASTUtils.isIdentifierWithName(node.key, key);
60
- },
61
- findPropertyWithIdentifierKey(properties, key) {
62
- return properties.find(
63
- (x) => ASTUtils.isPropertyWithIdentifierKey(x, key)
64
- );
65
- },
66
- getNestedIdentifiers(node) {
67
- const identifiers = [];
68
- if (ASTUtils.isIdentifier(node)) {
69
- identifiers.push(node);
70
- }
71
- if ("arguments" in node) {
72
- node.arguments.forEach((x) => {
73
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
74
- });
75
- }
76
- if ("elements" in node) {
77
- node.elements.forEach((x) => {
78
- if (x !== null) {
79
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
80
- }
81
- });
82
- }
83
- if ("properties" in node) {
84
- node.properties.forEach((x) => {
85
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
86
- });
87
- }
88
- if ("expressions" in node) {
89
- node.expressions.forEach((x) => {
90
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
91
- });
92
- }
93
- if ("left" in node) {
94
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.left));
95
- }
96
- if ("right" in node) {
97
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.right));
98
- }
99
- if (node.type === import_utils.AST_NODE_TYPES.Property) {
100
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.value));
101
- }
102
- if (node.type === import_utils.AST_NODE_TYPES.SpreadElement) {
103
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
104
- }
105
- if (node.type === import_utils.AST_NODE_TYPES.MemberExpression) {
106
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.object));
107
- }
108
- if (node.type === import_utils.AST_NODE_TYPES.UnaryExpression) {
109
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
110
- }
111
- if (node.type === import_utils.AST_NODE_TYPES.ChainExpression) {
112
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression));
113
- }
114
- if (node.type === import_utils.AST_NODE_TYPES.TSNonNullExpression) {
115
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression));
116
- }
117
- if (node.type === import_utils.AST_NODE_TYPES.ArrowFunctionExpression) {
118
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.body));
119
- }
120
- if (node.type === import_utils.AST_NODE_TYPES.FunctionExpression) {
121
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.body));
122
- }
123
- if (node.type === import_utils.AST_NODE_TYPES.BlockStatement) {
124
- identifiers.push(
125
- ...node.body.map((body) => ASTUtils.getNestedIdentifiers(body)).flat()
126
- );
127
- }
128
- if (node.type === import_utils.AST_NODE_TYPES.ReturnStatement && node.argument) {
129
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
130
- }
131
- return identifiers;
132
- },
133
- isAncestorIsCallee(identifier) {
134
- let previousNode = identifier;
135
- let currentNode = identifier.parent;
136
- while (currentNode !== void 0) {
137
- if (currentNode.type === import_utils.AST_NODE_TYPES.CallExpression && currentNode.callee === previousNode) {
138
- return true;
139
- }
140
- if (currentNode.type !== import_utils.AST_NODE_TYPES.MemberExpression) {
141
- return false;
142
- }
143
- previousNode = currentNode;
144
- currentNode = currentNode.parent;
145
- }
146
- return false;
147
- },
148
- traverseUpOnly(identifier, allowedNodeTypes) {
149
- const parent = identifier.parent;
150
- if (parent !== void 0 && allowedNodeTypes.includes(parent.type)) {
151
- return ASTUtils.traverseUpOnly(parent, allowedNodeTypes);
152
- }
153
- return identifier;
154
- },
155
- isDeclaredInNode(params) {
156
- const { functionNode, reference, scopeManager } = params;
157
- const scope = scopeManager.acquire(functionNode);
158
- if (scope === null) {
159
- return false;
160
- }
161
- return scope.set.has(reference.identifier.name);
162
- },
163
- getExternalRefs(params) {
164
- const { scopeManager, sourceCode, node } = params;
165
- const scope = scopeManager.acquire(node);
166
- if (scope === null) {
167
- return [];
168
- }
169
- const references = scope.references.filter((x) => x.isRead() && !scope.set.has(x.identifier.name)).map((x) => {
170
- const referenceNode = ASTUtils.traverseUpOnly(x.identifier, [
171
- import_utils.AST_NODE_TYPES.MemberExpression,
172
- import_utils.AST_NODE_TYPES.Identifier
173
- ]);
174
- return {
175
- variable: x,
176
- node: referenceNode,
177
- text: sourceCode.getText(referenceNode)
178
- };
179
- });
180
- const localRefIds = new Set(
181
- [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0]))
182
- );
183
- const externalRefs = references.filter(
184
- (x) => x.variable.resolved === null || !localRefIds.has(x.text)
185
- );
186
- return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable);
187
- },
188
- mapKeyNodeToText(node, sourceCode) {
189
- return sourceCode.getText(
190
- ASTUtils.traverseUpOnly(node, [
191
- import_utils.AST_NODE_TYPES.MemberExpression,
192
- import_utils.AST_NODE_TYPES.TSNonNullExpression,
193
- import_utils.AST_NODE_TYPES.Identifier
194
- ])
195
- );
196
- },
197
- mapKeyNodeToBaseText(node, sourceCode) {
198
- return ASTUtils.mapKeyNodeToText(node, sourceCode).replace(
199
- /(?:\?(\.)|!)/g,
200
- "$1"
201
- );
202
- },
203
- isValidReactComponentOrHookName(identifier) {
204
- return identifier !== null && identifier !== void 0 && /^(use|[A-Z])/.test(identifier.name);
205
- },
206
- getFunctionAncestor(sourceCode, node) {
207
- for (const ancestor of sourceCode.getAncestors(node)) {
208
- if (ASTUtils.isNodeOfOneOf(ancestor, [
209
- import_utils.AST_NODE_TYPES.FunctionDeclaration,
210
- import_utils.AST_NODE_TYPES.FunctionExpression,
211
- import_utils.AST_NODE_TYPES.ArrowFunctionExpression
212
- ])) {
213
- return ancestor;
214
- }
215
- if (ancestor.parent?.type === import_utils.AST_NODE_TYPES.VariableDeclarator && ancestor.parent.id.type === import_utils.AST_NODE_TYPES.Identifier && ASTUtils.isNodeOfOneOf(ancestor, [
216
- import_utils.AST_NODE_TYPES.FunctionDeclaration,
217
- import_utils.AST_NODE_TYPES.FunctionExpression,
218
- import_utils.AST_NODE_TYPES.ArrowFunctionExpression
219
- ])) {
220
- return ancestor;
221
- }
222
- }
223
- return void 0;
224
- },
225
- getReferencedExpressionByIdentifier(params) {
226
- const { node, context } = params;
227
- const sourceCode = context.sourceCode ?? context.getSourceCode();
228
- const scope = context.sourceCode.getScope(node) ? sourceCode.getScope(node) : context.getScope();
229
- const resolvedNode = scope.references.find((ref) => ref.identifier === node)?.resolved?.defs[0]?.node;
230
- if (resolvedNode?.type !== import_utils.AST_NODE_TYPES.VariableDeclarator) {
231
- return null;
232
- }
233
- return resolvedNode.init;
234
- },
235
- getClosestVariableDeclarator(node) {
236
- let currentNode = node;
237
- while (currentNode.type !== import_utils.AST_NODE_TYPES.Program) {
238
- if (currentNode.type === import_utils.AST_NODE_TYPES.VariableDeclarator) {
239
- return currentNode;
240
- }
241
- currentNode = currentNode.parent;
242
- }
243
- return void 0;
244
- },
245
- getNestedReturnStatements(node) {
246
- const returnStatements = [];
247
- if (node.type === import_utils.AST_NODE_TYPES.ReturnStatement) {
248
- returnStatements.push(node);
249
- }
250
- if ("body" in node && node.body !== void 0 && node.body !== null) {
251
- Array.isArray(node.body) ? node.body.forEach((x) => {
252
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
253
- }) : returnStatements.push(
254
- ...ASTUtils.getNestedReturnStatements(node.body)
255
- );
256
- }
257
- if ("consequent" in node) {
258
- Array.isArray(node.consequent) ? node.consequent.forEach((x) => {
259
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
260
- }) : returnStatements.push(
261
- ...ASTUtils.getNestedReturnStatements(node.consequent)
262
- );
263
- }
264
- if ("alternate" in node && node.alternate !== null) {
265
- Array.isArray(node.alternate) ? node.alternate.forEach((x) => {
266
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
267
- }) : returnStatements.push(
268
- ...ASTUtils.getNestedReturnStatements(node.alternate)
269
- );
270
- }
271
- if ("cases" in node) {
272
- node.cases.forEach((x) => {
273
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
274
- });
275
- }
276
- if ("block" in node) {
277
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block));
278
- }
279
- if ("handler" in node && node.handler !== null) {
280
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler));
281
- }
282
- if ("finalizer" in node && node.finalizer !== null) {
283
- returnStatements.push(
284
- ...ASTUtils.getNestedReturnStatements(node.finalizer)
285
- );
286
- }
287
- if ("expression" in node && node.expression !== true && node.expression !== false) {
288
- returnStatements.push(
289
- ...ASTUtils.getNestedReturnStatements(node.expression)
290
- );
291
- }
292
- if ("test" in node && node.test !== null) {
293
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test));
294
- }
295
- return returnStatements;
296
- }
297
- };
298
-
299
- // src/utils/get-docs-url.ts
300
- var getDocsUrl = (ruleName) => `https://tanstack.com/query/latest/docs/eslint/${ruleName}`;
301
-
302
- // src/utils/detect-react-query-imports.ts
303
- var import_utils2 = require("@typescript-eslint/utils");
304
- function detectTanstackQueryImports(create) {
305
- return (context, optionsWithDefault) => {
306
- const tanstackQueryImportSpecifiers = [];
307
- const helpers = {
308
- isSpecificTanstackQueryImport(node, source) {
309
- return !!tanstackQueryImportSpecifiers.find((specifier) => {
310
- if (specifier.type === import_utils2.TSESTree.AST_NODE_TYPES.ImportSpecifier && specifier.parent.type === import_utils2.TSESTree.AST_NODE_TYPES.ImportDeclaration && specifier.parent.source.value === source) {
311
- return node.name === specifier.local.name;
312
- }
313
- return false;
314
- });
315
- },
316
- isTanstackQueryImport(node) {
317
- return !!tanstackQueryImportSpecifiers.find((specifier) => {
318
- if (specifier.type === import_utils2.TSESTree.AST_NODE_TYPES.ImportSpecifier) {
319
- return node.name === specifier.local.name;
320
- }
321
- return false;
322
- });
323
- }
324
- };
325
- const detectionInstructions = {
326
- ImportDeclaration(node) {
327
- if (node.specifiers.length > 0 && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
328
- (node.importKind === "value" || node.importKind === void 0) && node.source.value.startsWith("@tanstack/") && node.source.value.endsWith("-query")) {
329
- tanstackQueryImportSpecifiers.push(...node.specifiers);
330
- }
331
- }
332
- };
333
- const ruleInstructions = create(context, optionsWithDefault, helpers);
334
- const enhancedRuleInstructions = {};
335
- const allKeys = new Set(
336
- Object.keys(detectionInstructions).concat(Object.keys(ruleInstructions))
337
- );
338
- allKeys.forEach((instruction) => {
339
- enhancedRuleInstructions[instruction] = (node) => {
340
- if (instruction in detectionInstructions) {
341
- detectionInstructions[instruction]?.(node);
342
- }
343
- const ruleInstruction = ruleInstructions[instruction];
344
- if (ruleInstruction) {
345
- return ruleInstruction(node);
346
- }
347
- return void 0;
348
- };
349
- });
350
- return enhancedRuleInstructions;
351
- };
352
- }
353
-
354
- // src/rules/exhaustive-deps/exhaustive-deps.utils.ts
355
- var import_utils3 = require("@typescript-eslint/utils");
356
- var ExhaustiveDepsUtils = {
357
- isRelevantReference(params) {
358
- const { sourceCode, reference, scopeManager, node, filename } = params;
359
- const component = ASTUtils.getFunctionAncestor(sourceCode, node);
360
- if (component !== void 0) {
361
- if (!ASTUtils.isDeclaredInNode({
362
- scopeManager,
363
- reference,
364
- functionNode: component
365
- })) {
366
- return false;
367
- }
368
- } else {
369
- const isVueFile = filename.endsWith(".vue");
370
- if (!isVueFile) {
371
- return false;
372
- }
373
- const definition = reference.resolved?.defs[0];
374
- const isGlobalVariable = definition === void 0;
375
- const isImport = definition?.type === "ImportBinding";
376
- if (isGlobalVariable || isImport) {
377
- return false;
378
- }
379
- }
380
- return reference.identifier.name !== "undefined" && reference.identifier.parent.type !== import_utils3.AST_NODE_TYPES.NewExpression && !ExhaustiveDepsUtils.isInstanceOfKind(reference.identifier.parent);
381
- },
382
- isInstanceOfKind(node) {
383
- return node.type === import_utils3.AST_NODE_TYPES.BinaryExpression && node.operator === "instanceof";
384
- }
385
- };
386
-
387
- // src/rules/exhaustive-deps/exhaustive-deps.rule.ts
388
- var QUERY_KEY = "queryKey";
389
- var QUERY_FN = "queryFn";
390
- var name = "exhaustive-deps";
391
- var createRule = import_utils4.ESLintUtils.RuleCreator(getDocsUrl);
392
- var rule = createRule({
393
- name,
394
- meta: {
395
- type: "problem",
396
- docs: {
397
- description: "Exhaustive deps rule for useQuery",
398
- recommended: "error"
399
- },
400
- messages: {
401
- missingDeps: `The following dependencies are missing in your queryKey: {{deps}}`,
402
- fixTo: "Fix to {{result}}"
403
- },
404
- hasSuggestions: true,
405
- fixable: "code",
406
- schema: []
407
- },
408
- defaultOptions: [],
409
- create: detectTanstackQueryImports((context) => {
410
- return {
411
- Property: (node) => {
412
- if (!ASTUtils.isObjectExpression(node.parent) || !ASTUtils.isIdentifierWithName(node.key, QUERY_KEY)) {
413
- return;
414
- }
415
- const scopeManager = context.sourceCode.scopeManager;
416
- const queryKey = ASTUtils.findPropertyWithIdentifierKey(
417
- node.parent.properties,
418
- QUERY_KEY
419
- );
420
- const queryFn = ASTUtils.findPropertyWithIdentifierKey(
421
- node.parent.properties,
422
- QUERY_FN
423
- );
424
- if (scopeManager === null || queryKey === void 0 || queryFn === void 0 || !ASTUtils.isNodeOfOneOf(queryFn.value, [
425
- import_utils4.AST_NODE_TYPES.ArrowFunctionExpression,
426
- import_utils4.AST_NODE_TYPES.FunctionExpression,
427
- import_utils4.AST_NODE_TYPES.ConditionalExpression
428
- ])) {
429
- return;
430
- }
431
- const queryKeyNode = dereferenceVariablesAndTypeAssertions(
432
- queryKey.value,
433
- context
434
- );
435
- const externalRefs = ASTUtils.getExternalRefs({
436
- scopeManager,
437
- sourceCode: context.sourceCode,
438
- node: getQueryFnRelevantNode(queryFn)
439
- });
440
- const relevantRefs = externalRefs.filter(
441
- (reference) => ExhaustiveDepsUtils.isRelevantReference({
442
- sourceCode: context.sourceCode,
443
- reference,
444
- scopeManager,
445
- node: getQueryFnRelevantNode(queryFn),
446
- filename: context.filename
447
- })
448
- );
449
- const existingKeys = ASTUtils.getNestedIdentifiers(queryKeyNode).map(
450
- (identifier) => ASTUtils.mapKeyNodeToBaseText(identifier, context.sourceCode)
451
- );
452
- const missingRefs = relevantRefs.map((ref) => ({
453
- ref,
454
- text: ASTUtils.mapKeyNodeToBaseText(
455
- ref.identifier,
456
- context.sourceCode
457
- )
458
- })).filter(({ ref, text }) => {
459
- return !ref.isTypeReference && !ASTUtils.isAncestorIsCallee(ref.identifier) && !existingKeys.some((existingKey) => existingKey === text) && !existingKeys.includes(text.split(/[?.]/)[0] ?? "");
460
- }).map(({ ref, text }) => ({
461
- identifier: ref.identifier,
462
- text
463
- }));
464
- const uniqueMissingRefs = uniqueBy(missingRefs, (x) => x.text);
465
- if (uniqueMissingRefs.length > 0) {
466
- const missingAsText = uniqueMissingRefs.map(
467
- (ref) => ASTUtils.mapKeyNodeToText(ref.identifier, context.sourceCode)
468
- ).join(", ");
469
- const queryKeyValue = context.sourceCode.getText(queryKeyNode);
470
- const existingWithMissing = queryKeyValue === "[]" ? `[${missingAsText}]` : queryKeyValue.replace(/\]$/, `, ${missingAsText}]`);
471
- const suggestions = [];
472
- if (queryKeyNode.type === import_utils4.AST_NODE_TYPES.ArrayExpression) {
473
- suggestions.push({
474
- messageId: "fixTo",
475
- data: { result: existingWithMissing },
476
- fix(fixer) {
477
- return fixer.replaceText(queryKeyNode, existingWithMissing);
478
- }
479
- });
480
- }
481
- context.report({
482
- node,
483
- messageId: "missingDeps",
484
- data: {
485
- deps: uniqueMissingRefs.map((ref) => ref.text).join(", ")
486
- },
487
- suggest: suggestions
488
- });
489
- }
490
- }
491
- };
492
- })
493
- });
494
- function getQueryFnRelevantNode(queryFn) {
495
- if (queryFn.value.type !== import_utils4.AST_NODE_TYPES.ConditionalExpression) {
496
- return queryFn.value;
497
- }
498
- if (queryFn.value.consequent.type === import_utils4.AST_NODE_TYPES.Identifier && queryFn.value.consequent.name === "skipToken") {
499
- return queryFn.value.alternate;
500
- }
501
- return queryFn.value.consequent;
502
- }
503
- function dereferenceVariablesAndTypeAssertions(queryKeyNode, context) {
504
- const visitedNodes = /* @__PURE__ */ new Set();
505
- for (let i = 0; i < 1 << 8; ++i) {
506
- if (visitedNodes.has(queryKeyNode)) {
507
- return queryKeyNode;
508
- }
509
- visitedNodes.add(queryKeyNode);
510
- switch (queryKeyNode.type) {
511
- case import_utils4.AST_NODE_TYPES.TSAsExpression:
512
- queryKeyNode = queryKeyNode.expression;
513
- break;
514
- case import_utils4.AST_NODE_TYPES.Identifier: {
515
- const expression = ASTUtils.getReferencedExpressionByIdentifier({
516
- context,
517
- node: queryKeyNode
518
- });
519
- if (expression == null) {
520
- return queryKeyNode;
521
- }
522
- queryKeyNode = expression;
523
- break;
524
- }
525
- default:
526
- return queryKeyNode;
527
- }
528
- }
529
- return queryKeyNode;
530
- }
531
-
532
- // src/rules/stable-query-client/stable-query-client.rule.ts
533
- var import_utils5 = require("@typescript-eslint/utils");
534
- var name2 = "stable-query-client";
535
- var createRule2 = import_utils5.ESLintUtils.RuleCreator(getDocsUrl);
536
- var rule2 = createRule2({
537
- name: name2,
538
- meta: {
539
- type: "problem",
540
- docs: {
541
- description: "Makes sure that QueryClient is stable",
542
- recommended: "error"
543
- },
544
- messages: {
545
- unstable: [
546
- "QueryClient is not stable. It should be either extracted from the component or wrapped in React.useState.",
547
- "See https://tkdodo.eu/blog/react-query-fa-qs#2-the-queryclient-is-not-stable"
548
- ].join("\n"),
549
- fixTo: "Fix to {{result}}"
550
- },
551
- hasSuggestions: true,
552
- fixable: "code",
553
- schema: []
554
- },
555
- defaultOptions: [],
556
- create: detectTanstackQueryImports((context, _, helpers) => {
557
- return {
558
- NewExpression: (node) => {
559
- if (node.callee.type !== import_utils5.AST_NODE_TYPES.Identifier || node.callee.name !== "QueryClient" || node.parent.type !== import_utils5.AST_NODE_TYPES.VariableDeclarator || !helpers.isSpecificTanstackQueryImport(
560
- node.callee,
561
- "@tanstack/react-query"
562
- )) {
563
- return;
564
- }
565
- const fnAncestor = ASTUtils.getFunctionAncestor(
566
- context.sourceCode,
567
- node
568
- );
569
- const isReactServerComponent = fnAncestor?.async === true;
570
- if (!ASTUtils.isValidReactComponentOrHookName(fnAncestor?.id) || isReactServerComponent) {
571
- return;
572
- }
573
- context.report({
574
- node: node.parent,
575
- messageId: "unstable",
576
- fix: (() => {
577
- const { parent } = node;
578
- if (parent.id.type !== import_utils5.AST_NODE_TYPES.Identifier) {
579
- return;
580
- }
581
- const sourceCode = context.sourceCode ?? context.getSourceCode();
582
- const nodeText = sourceCode.getText(node);
583
- const variableName = parent.id.name;
584
- return (fixer) => {
585
- return fixer.replaceTextRange(
586
- [parent.range[0], parent.range[1]],
587
- `[${variableName}] = React.useState(() => ${nodeText})`
588
- );
589
- };
590
- })()
591
- });
592
- }
593
- };
594
- })
595
- });
596
-
597
- // src/rules/no-rest-destructuring/no-rest-destructuring.rule.ts
598
- var import_utils7 = require("@typescript-eslint/utils");
599
-
600
- // src/rules/no-rest-destructuring/no-rest-destructuring.utils.ts
601
- var import_utils6 = require("@typescript-eslint/utils");
602
- var NoRestDestructuringUtils = {
603
- isObjectRestDestructuring(node) {
604
- if (node.type !== import_utils6.AST_NODE_TYPES.ObjectPattern) {
605
- return false;
606
- }
607
- return node.properties.some((p) => p.type === import_utils6.AST_NODE_TYPES.RestElement);
608
- }
609
- };
610
-
611
- // src/rules/no-rest-destructuring/no-rest-destructuring.rule.ts
612
- var name3 = "no-rest-destructuring";
613
- var queryHooks = [
614
- "useQuery",
615
- "useQueries",
616
- "useInfiniteQuery",
617
- "useSuspenseQuery",
618
- "useSuspenseQueries",
619
- "useSuspenseInfiniteQuery"
620
- ];
621
- var createRule3 = import_utils7.ESLintUtils.RuleCreator(getDocsUrl);
622
- var rule3 = createRule3({
623
- name: name3,
624
- meta: {
625
- type: "problem",
626
- docs: {
627
- description: "Disallows rest destructuring in queries",
628
- recommended: "warn"
629
- },
630
- messages: {
631
- objectRestDestructure: `Object rest destructuring on a query will observe all changes to the query, leading to excessive re-renders.`
632
- },
633
- schema: []
634
- },
635
- defaultOptions: [],
636
- create: detectTanstackQueryImports((context, _, helpers) => {
637
- const queryResultVariables = /* @__PURE__ */ new Set();
638
- return {
639
- CallExpression: (node) => {
640
- if (!ASTUtils.isIdentifierWithOneOfNames(node.callee, queryHooks) || node.parent.type !== import_utils7.AST_NODE_TYPES.VariableDeclarator || !helpers.isTanstackQueryImport(node.callee)) {
641
- return;
642
- }
643
- const returnValue = node.parent.id;
644
- if (node.callee.name !== "useQueries" && node.callee.name !== "useSuspenseQueries") {
645
- if (NoRestDestructuringUtils.isObjectRestDestructuring(returnValue)) {
646
- return context.report({
647
- node: node.parent,
648
- messageId: "objectRestDestructure"
649
- });
650
- }
651
- if (returnValue.type === import_utils7.AST_NODE_TYPES.Identifier) {
652
- queryResultVariables.add(returnValue.name);
653
- }
654
- return;
655
- }
656
- if (returnValue.type !== import_utils7.AST_NODE_TYPES.ArrayPattern) {
657
- if (returnValue.type === import_utils7.AST_NODE_TYPES.Identifier) {
658
- queryResultVariables.add(returnValue.name);
659
- }
660
- return;
661
- }
662
- returnValue.elements.forEach((queryResult) => {
663
- if (queryResult === null) {
664
- return;
665
- }
666
- if (NoRestDestructuringUtils.isObjectRestDestructuring(queryResult)) {
667
- context.report({
668
- node: queryResult,
669
- messageId: "objectRestDestructure"
670
- });
671
- }
672
- });
673
- },
674
- VariableDeclarator: (node) => {
675
- if (node.init?.type === import_utils7.AST_NODE_TYPES.Identifier && queryResultVariables.has(node.init.name) && NoRestDestructuringUtils.isObjectRestDestructuring(node.id)) {
676
- context.report({
677
- node,
678
- messageId: "objectRestDestructure"
679
- });
680
- }
681
- },
682
- SpreadElement: (node) => {
683
- if (node.argument.type === import_utils7.AST_NODE_TYPES.Identifier && queryResultVariables.has(node.argument.name)) {
684
- context.report({
685
- node,
686
- messageId: "objectRestDestructure"
687
- });
688
- }
689
- }
690
- };
691
- })
692
- });
693
-
694
- // src/rules/no-unstable-deps/no-unstable-deps.rule.ts
695
- var import_utils8 = require("@typescript-eslint/utils");
696
- var name4 = "no-unstable-deps";
697
- var reactHookNames = ["useEffect", "useCallback", "useMemo"];
698
- var useQueryHookNames = [
699
- "useQuery",
700
- "useSuspenseQuery",
701
- "useQueries",
702
- "useSuspenseQueries",
703
- "useInfiniteQuery",
704
- "useSuspenseInfiniteQuery"
705
- ];
706
- var allHookNames = ["useMutation", ...useQueryHookNames];
707
- var createRule4 = import_utils8.ESLintUtils.RuleCreator(getDocsUrl);
708
- var rule4 = createRule4({
709
- name: name4,
710
- meta: {
711
- type: "problem",
712
- docs: {
713
- description: "Disallow putting the result of query hooks directly in a React hook dependency array",
714
- recommended: "error"
715
- },
716
- messages: {
717
- noUnstableDeps: `The result of {{queryHook}} is not referentially stable, so don't pass it directly into the dependencies array of {{reactHook}}. Instead, destructure the return value of {{queryHook}} and pass the destructured values into the dependency array of {{reactHook}}.`
718
- },
719
- schema: []
720
- },
721
- defaultOptions: [],
722
- create: detectTanstackQueryImports((context, _options, helpers) => {
723
- const trackedVariables = {};
724
- const hookAliasMap = {};
725
- function getReactHook(node) {
726
- if (node.callee.type === "Identifier") {
727
- const calleeName = node.callee.name;
728
- if (reactHookNames.includes(calleeName) || calleeName in hookAliasMap) {
729
- return calleeName;
730
- }
731
- } else if (node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "React" && node.callee.property.type === "Identifier" && reactHookNames.includes(node.callee.property.name)) {
732
- return node.callee.property.name;
733
- }
734
- return void 0;
735
- }
736
- function collectVariableNames(pattern, queryHook) {
737
- if (pattern.type === import_utils8.AST_NODE_TYPES.Identifier) {
738
- trackedVariables[pattern.name] = queryHook;
739
- }
740
- }
741
- function hasCombineProperty(callExpression) {
742
- if (callExpression.arguments.length === 0) return false;
743
- const firstArg = callExpression.arguments[0];
744
- if (!firstArg || firstArg.type !== import_utils8.AST_NODE_TYPES.ObjectExpression)
745
- return false;
746
- return firstArg.properties.some(
747
- (prop) => prop.type === import_utils8.AST_NODE_TYPES.Property && prop.key.type === import_utils8.AST_NODE_TYPES.Identifier && prop.key.name === "combine"
748
- );
749
- }
750
- return {
751
- ImportDeclaration(node) {
752
- if (node.specifiers.length > 0 && node.importKind === "value" && node.source.value === "React") {
753
- node.specifiers.forEach((specifier) => {
754
- if (specifier.type === import_utils8.AST_NODE_TYPES.ImportSpecifier && specifier.imported.type === import_utils8.AST_NODE_TYPES.Identifier && reactHookNames.includes(specifier.imported.name)) {
755
- hookAliasMap[specifier.local.name] = specifier.imported.name;
756
- }
757
- });
758
- }
759
- },
760
- VariableDeclarator(node) {
761
- if (node.init !== null && node.init.type === import_utils8.AST_NODE_TYPES.CallExpression && node.init.callee.type === import_utils8.AST_NODE_TYPES.Identifier && allHookNames.includes(node.init.callee.name) && helpers.isTanstackQueryImport(node.init.callee)) {
762
- if (node.init.callee.name === "useQueries" && hasCombineProperty(node.init)) {
763
- return;
764
- }
765
- collectVariableNames(node.id, node.init.callee.name);
766
- }
767
- },
768
- CallExpression: (node) => {
769
- const reactHook = getReactHook(node);
770
- if (reactHook !== void 0 && node.arguments.length > 1 && node.arguments[1]?.type === import_utils8.AST_NODE_TYPES.ArrayExpression) {
771
- const depsArray = node.arguments[1].elements;
772
- depsArray.forEach((dep) => {
773
- if (dep !== null && dep.type === import_utils8.AST_NODE_TYPES.Identifier && trackedVariables[dep.name] !== void 0) {
774
- const queryHook = trackedVariables[dep.name];
775
- context.report({
776
- node: dep,
777
- messageId: "noUnstableDeps",
778
- data: {
779
- queryHook,
780
- reactHook
781
- }
782
- });
783
- }
784
- });
785
- }
786
- }
787
- };
788
- })
789
- });
790
-
791
- // src/utils/create-property-order-rule.ts
792
- var import_utils9 = require("@typescript-eslint/utils");
793
-
794
- // src/utils/sort-data-by-order.ts
795
- function sortDataByOrder(data, orderRules, key) {
796
- const getSubsetIndex = (item, subsets) => {
797
- for (let i = 0; i < subsets.length; i++) {
798
- if (subsets[i]?.includes(item)) {
799
- return i;
800
- }
801
- }
802
- return null;
803
- };
804
- const orderSets = orderRules.reduce(
805
- (sets, [A, B]) => [...sets, A, B],
806
- []
807
- );
808
- const inOrderArray = data.filter(
809
- (item) => getSubsetIndex(item[key], orderSets) !== null
810
- );
811
- let wasResorted = false;
812
- const sortedArray = inOrderArray.sort((a, b) => {
813
- const aKey = a[key], bKey = b[key];
814
- const aSubsetIndex = getSubsetIndex(aKey, orderSets);
815
- const bSubsetIndex = getSubsetIndex(bKey, orderSets);
816
- if (aSubsetIndex !== null && bSubsetIndex !== null && aSubsetIndex !== bSubsetIndex) {
817
- return aSubsetIndex - bSubsetIndex;
818
- }
819
- return 0;
820
- });
821
- const inOrderIterator = sortedArray.values();
822
- const result = data.map((item) => {
823
- if (getSubsetIndex(item[key], orderSets) !== null) {
824
- const sortedItem = inOrderIterator.next().value;
825
- if (sortedItem[key] !== item[key]) {
826
- wasResorted = true;
827
- }
828
- return sortedItem;
829
- }
830
- return item;
831
- });
832
- if (!wasResorted) {
833
- return null;
834
- }
835
- return result;
836
- }
837
-
838
- // src/utils/create-property-order-rule.ts
839
- var createRule5 = import_utils9.ESLintUtils.RuleCreator(getDocsUrl);
840
- function createPropertyOrderRule(options, targetFunctions, orderRules) {
841
- const targetFunctionSet = new Set(targetFunctions);
842
- function isTargetFunction(node) {
843
- return targetFunctionSet.has(node);
844
- }
845
- return createRule5({
846
- ...options,
847
- create: detectTanstackQueryImports((context) => {
848
- return {
849
- CallExpression(node) {
850
- if (node.callee.type !== import_utils9.AST_NODE_TYPES.Identifier) {
851
- return;
852
- }
853
- const functions = node.callee.name;
854
- if (!isTargetFunction(functions)) {
855
- return;
856
- }
857
- const argument = node.arguments[0];
858
- if (argument === void 0 || argument.type !== "ObjectExpression") {
859
- return;
860
- }
861
- const allProperties = argument.properties;
862
- if (allProperties.length < 2) {
863
- return;
864
- }
865
- const properties = allProperties.flatMap((p, index) => {
866
- if (p.type === import_utils9.AST_NODE_TYPES.Property && p.key.type === import_utils9.AST_NODE_TYPES.Identifier) {
867
- return { name: p.key.name, property: p };
868
- } else return { name: `_property_${index}`, property: p };
869
- });
870
- const sortedProperties = sortDataByOrder(
871
- properties,
872
- orderRules,
873
- "name"
874
- );
875
- if (sortedProperties === null) {
876
- return;
877
- }
878
- context.report({
879
- node: argument,
880
- data: { function: node.callee.name },
881
- messageId: "invalidOrder",
882
- fix(fixer) {
883
- const sourceCode = context.sourceCode;
884
- const reorderedText = sortedProperties.reduce(
885
- (sourceText, specifier, index) => {
886
- let textBetweenProperties = "";
887
- if (index < allProperties.length - 1) {
888
- textBetweenProperties = sourceCode.getText().slice(
889
- allProperties[index].range[1],
890
- allProperties[index + 1].range[0]
891
- );
892
- }
893
- return sourceText + sourceCode.getText(specifier.property) + textBetweenProperties;
894
- },
895
- ""
896
- );
897
- return fixer.replaceTextRange(
898
- [allProperties[0].range[0], allProperties.at(-1).range[1]],
899
- reorderedText
900
- );
901
- }
902
- });
903
- }
904
- };
905
- })
906
- });
907
- }
908
-
909
- // src/rules/infinite-query-property-order/constants.ts
910
- var infiniteQueryFunctions = [
911
- "infiniteQueryOptions",
912
- "useInfiniteQuery",
913
- "useSuspenseInfiniteQuery"
914
- ];
915
- var sortRules = [
916
- [["queryFn"], ["getPreviousPageParam", "getNextPageParam"]]
917
- ];
918
-
919
- // src/rules/infinite-query-property-order/infinite-query-property-order.rule.ts
920
- var name5 = "infinite-query-property-order";
921
- var rule5 = createPropertyOrderRule(
922
- {
923
- name: name5,
924
- meta: {
925
- type: "problem",
926
- docs: {
927
- description: "Ensure correct order of inference sensitive properties for infinite queries",
928
- recommended: "error"
929
- },
930
- messages: {
931
- invalidOrder: "Invalid order of properties for `{{function}}`."
932
- },
933
- schema: [],
934
- hasSuggestions: true,
935
- fixable: "code"
936
- },
937
- defaultOptions: []
938
- },
939
- infiniteQueryFunctions,
940
- sortRules
941
- );
942
-
943
- // src/rules/no-void-query-fn/no-void-query-fn.rule.ts
944
- var import_utils10 = require("@typescript-eslint/utils");
945
- var TypeFlags = {
946
- Void: 16384,
947
- Undefined: 32768
948
- };
949
- var name6 = "no-void-query-fn";
950
- var createRule6 = import_utils10.ESLintUtils.RuleCreator(getDocsUrl);
951
- var rule6 = createRule6({
952
- name: name6,
953
- meta: {
954
- type: "problem",
955
- docs: {
956
- description: "Ensures queryFn returns a non-undefined value",
957
- recommended: "error"
958
- },
959
- messages: {
960
- noVoidReturn: "queryFn must return a non-undefined value"
961
- },
962
- schema: []
963
- },
964
- defaultOptions: [],
965
- create: detectTanstackQueryImports((context) => {
966
- return {
967
- Property(node) {
968
- if (!ASTUtils.isObjectExpression(node.parent) || !ASTUtils.isIdentifierWithName(node.key, "queryFn")) {
969
- return;
970
- }
971
- const parserServices = context.sourceCode.parserServices;
972
- if (!parserServices || !parserServices.esTreeNodeToTSNodeMap || !parserServices.program) {
973
- return;
974
- }
975
- const checker = parserServices.program.getTypeChecker();
976
- const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.value);
977
- const type = checker.getTypeAtLocation(tsNode);
978
- if (type.getCallSignatures().length > 0) {
979
- const returnType = type.getCallSignatures()[0]?.getReturnType();
980
- if (!returnType) {
981
- return;
982
- }
983
- if (isIllegalReturn(checker, returnType)) {
984
- context.report({
985
- node: node.value,
986
- messageId: "noVoidReturn"
987
- });
988
- }
989
- }
990
- }
991
- };
992
- })
993
- });
994
- function isIllegalReturn(checker, type) {
995
- const awaited = checker.getAwaitedType(type);
996
- if (!awaited) return false;
997
- if (awaited.isUnion()) {
998
- return awaited.types.some((t) => isIllegalReturn(checker, t));
999
- }
1000
- return awaited.flags & (TypeFlags.Void | TypeFlags.Undefined) ? true : false;
1001
- }
1002
-
1003
- // src/rules/mutation-property-order/constants.ts
1004
- var mutationFunctions = ["useMutation"];
1005
- var sortRules2 = [[["onMutate"], ["onError", "onSettled"]]];
1006
-
1007
- // src/rules/mutation-property-order/mutation-property-order.rule.ts
1008
- var name7 = "mutation-property-order";
1009
- var rule7 = createPropertyOrderRule(
1010
- {
1011
- name: name7,
1012
- meta: {
1013
- type: "problem",
1014
- docs: {
1015
- description: "Ensure correct order of inference-sensitive properties in useMutation()",
1016
- recommended: "error"
1017
- },
1018
- messages: {
1019
- invalidOrder: "Invalid order of properties for `{{function}}`."
1020
- },
1021
- schema: [],
1022
- hasSuggestions: true,
1023
- fixable: "code"
1024
- },
1025
- defaultOptions: []
1026
- },
1027
- mutationFunctions,
1028
- sortRules2
1029
- );
1030
-
1031
- // src/rules.ts
1032
- var rules = {
1033
- [name]: rule,
1034
- [name2]: rule2,
1035
- [name3]: rule3,
1036
- [name4]: rule4,
1037
- [name5]: rule5,
1038
- [name6]: rule6,
1039
- [name7]: rule7
1040
- };
1041
- // Annotate the CommonJS export names for ESM import in node:
1042
- 0 && (module.exports = {
1043
- rules
1044
- });
1045
- module.exports = module.exports.default
1046
- //# sourceMappingURL=rules.cjs.map