@blumintinc/eslint-plugin-blumint 1.20.23 → 1.20.25
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.
package/lib/index.js
CHANGED
|
@@ -55,6 +55,21 @@ function isArrayOrPrimitive(checker, esTreeNode, nodeMap) {
|
|
|
55
55
|
return false;
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
|
+
function renderPathSegments(baseName, segments) {
|
|
59
|
+
let path = baseName;
|
|
60
|
+
for (const segment of segments) {
|
|
61
|
+
if (segment.computed) {
|
|
62
|
+
// why: an optional computed access must render as `?.[` — a bare `?`
|
|
63
|
+
// before `[` parses as a conditional expression, so `state?[0]` is a
|
|
64
|
+
// syntax error while `state?.[0]` is the valid optional element access.
|
|
65
|
+
path += segment.optional ? `?.${segment.text}` : segment.text;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
path += segment.optional ? `?.${segment.text}` : `.${segment.text}`;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return path;
|
|
72
|
+
}
|
|
58
73
|
function unwrapExpression(expr) {
|
|
59
74
|
let current = expr;
|
|
60
75
|
while (current.type === utils_1.AST_NODE_TYPES.TSAsExpression ||
|
|
@@ -67,6 +82,10 @@ function unwrapExpression(expr) {
|
|
|
67
82
|
}
|
|
68
83
|
function getObjectUsagesInHook(hookBody, objectName) {
|
|
69
84
|
const usages = new Map(); // Track usage and its position
|
|
85
|
+
// why: derived dependency paths (first-optional intermediate, array base)
|
|
86
|
+
// must be re-rendered from structured links — string surgery on the
|
|
87
|
+
// rendered path cannot place `?.` markers correctly.
|
|
88
|
+
const pathSegments = new Map();
|
|
70
89
|
const visited = new Set();
|
|
71
90
|
let needsEntireObject = false;
|
|
72
91
|
let isUsed = false;
|
|
@@ -123,23 +142,33 @@ function getObjectUsagesInHook(hookBody, objectName) {
|
|
|
123
142
|
'includes',
|
|
124
143
|
]);
|
|
125
144
|
function buildAccessPath(node) {
|
|
126
|
-
|
|
145
|
+
// why: optionality belongs to individual links, not the whole chain.
|
|
146
|
+
// Rendering from per-link segments keeps `?.` markers at their real
|
|
147
|
+
// position (a.b?.[0] stays a.b?.[0], not a?.b[0]) and forms the mandatory
|
|
148
|
+
// `?.[` for optional computed access (state?.[0], never state?[0]).
|
|
149
|
+
const segments = [];
|
|
127
150
|
let current = node;
|
|
128
|
-
|
|
129
|
-
// Collect all parts from leaf to root
|
|
151
|
+
// Collect all links from leaf to root
|
|
130
152
|
while (current.type === utils_1.AST_NODE_TYPES.MemberExpression) {
|
|
131
153
|
const memberExpr = current;
|
|
132
154
|
// Handle computed properties (like array indices)
|
|
133
155
|
if (memberExpr.computed) {
|
|
134
|
-
// why: only a *literal* computed key (obj[0],
|
|
135
|
-
// narrows to a single, stable field. EVERY other
|
|
136
|
-
// Identifier (obj[i]), CallExpression
|
|
137
|
-
//
|
|
138
|
-
// TSAsExpression (obj[k as K]), TemplateLiteral
|
|
139
|
-
// — is a dynamic access that can read
|
|
140
|
-
//
|
|
141
|
-
//
|
|
142
|
-
|
|
156
|
+
// why: only a *literal* string/number computed key (obj[0],
|
|
157
|
+
// obj['special-key']) narrows to a single, stable field. EVERY other
|
|
158
|
+
// computed key — Identifier (obj[i]), CallExpression
|
|
159
|
+
// (obj[assertSafe(i)]), BinaryExpression (obj[i+1]), MemberExpression
|
|
160
|
+
// (obj[keys[j]]), TSAsExpression (obj[k as K]), TemplateLiteral
|
|
161
|
+
// (obj[`row-${i}`]), etc. — is a dynamic access that can read
|
|
162
|
+
// arbitrary elements across an iteration. Remaining literal kinds
|
|
163
|
+
// (boolean/null/regex/bigint keys) have no rendering the fixer can
|
|
164
|
+
// guarantee round-trips, so they decline narrowing too rather than
|
|
165
|
+
// emit unreliable text. In every declined case the whole object is a
|
|
166
|
+
// legitimate dependency: resolve the base and mark it accordingly.
|
|
167
|
+
const literalValue = memberExpr.property.type === utils_1.AST_NODE_TYPES.Literal
|
|
168
|
+
? memberExpr.property.value
|
|
169
|
+
: undefined;
|
|
170
|
+
if (typeof literalValue !== 'number' &&
|
|
171
|
+
typeof literalValue !== 'string') {
|
|
143
172
|
// Check if this is accessing our target object
|
|
144
173
|
let currentBase = unwrapExpression(memberExpr.object);
|
|
145
174
|
while (currentBase.type === utils_1.AST_NODE_TYPES.MemberExpression) {
|
|
@@ -147,24 +176,18 @@ function getObjectUsagesInHook(hookBody, objectName) {
|
|
|
147
176
|
}
|
|
148
177
|
if (currentBase.type === utils_1.AST_NODE_TYPES.Identifier &&
|
|
149
178
|
currentBase.name === objectName) {
|
|
150
|
-
//
|
|
151
|
-
// so we need the entire object (no narrowable field exists).
|
|
179
|
+
// No narrowable field exists, so the entire object is required.
|
|
152
180
|
needsEntireObject = true;
|
|
153
181
|
}
|
|
154
182
|
return null;
|
|
155
183
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
// For other literal computed properties (e.g. boolean/null), wildcard
|
|
166
|
-
parts.unshift('[*]');
|
|
167
|
-
}
|
|
184
|
+
segments.unshift({
|
|
185
|
+
text: typeof literalValue === 'number'
|
|
186
|
+
? `[${literalValue}]`
|
|
187
|
+
: `[${JSON.stringify(literalValue)}]`,
|
|
188
|
+
computed: true,
|
|
189
|
+
optional: memberExpr.optional,
|
|
190
|
+
});
|
|
168
191
|
}
|
|
169
192
|
else {
|
|
170
193
|
// Regular property access
|
|
@@ -175,57 +198,37 @@ function getObjectUsagesInHook(hookBody, objectName) {
|
|
|
175
198
|
if (memberExpr.property.name &&
|
|
176
199
|
(ARRAY_METHODS.has(memberExpr.property.name) ||
|
|
177
200
|
STRING_METHODS.has(memberExpr.property.name))) {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
if (
|
|
186
|
-
pathParts.unshift(currentMember.property.name);
|
|
187
|
-
}
|
|
188
|
-
if (currentMember.optional) {
|
|
189
|
-
hasOptionalChainingInMethod = true;
|
|
190
|
-
}
|
|
191
|
-
currentBase = unwrapExpression(currentMember.object);
|
|
192
|
-
}
|
|
193
|
-
if (currentBase.type === utils_1.AST_NODE_TYPES.Identifier &&
|
|
194
|
-
currentBase.name === objectName) {
|
|
195
|
-
if (pathParts.length === 0) {
|
|
196
|
-
// Direct method call on the object (e.g., userData.map(...))
|
|
197
|
-
needsEntireObject = true;
|
|
198
|
-
}
|
|
199
|
-
else {
|
|
200
|
-
// Method call on a property (e.g., userData.items.map(...) or userData?.items?.map(...))
|
|
201
|
-
let path = objectName + (hasOptionalChainingInMethod ? '?' : '');
|
|
202
|
-
path += '.' + pathParts.join('.');
|
|
201
|
+
const methodTarget = unwrapExpression(memberExpr.object);
|
|
202
|
+
if (methodTarget.type === utils_1.AST_NODE_TYPES.MemberExpression) {
|
|
203
|
+
// Method call on a property (e.g., userData.items.map(...) or
|
|
204
|
+
// userData?.items?.map(...)): depend on that property's own path,
|
|
205
|
+
// rendered with the same per-link optional markers as any other
|
|
206
|
+
// access.
|
|
207
|
+
const path = buildAccessPath(methodTarget);
|
|
208
|
+
if (path) {
|
|
203
209
|
usages.set(path, memberExpr.range?.[0] || 0);
|
|
204
210
|
}
|
|
205
211
|
}
|
|
212
|
+
else if (methodTarget.type === utils_1.AST_NODE_TYPES.Identifier &&
|
|
213
|
+
methodTarget.name === objectName) {
|
|
214
|
+
// Direct method call on the object (e.g., userData.map(...))
|
|
215
|
+
needsEntireObject = true;
|
|
216
|
+
}
|
|
206
217
|
return null;
|
|
207
218
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
219
|
+
segments.unshift({
|
|
220
|
+
text: memberExpr.property.name,
|
|
221
|
+
computed: false,
|
|
222
|
+
optional: memberExpr.optional,
|
|
223
|
+
});
|
|
212
224
|
}
|
|
213
225
|
current = unwrapExpression(memberExpr.object);
|
|
214
226
|
}
|
|
215
227
|
// Check if we reached the target identifier
|
|
216
228
|
const base = unwrapExpression(current);
|
|
217
229
|
if (base.type === utils_1.AST_NODE_TYPES.Identifier && base.name === objectName) {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
// Add each part with proper formatting (dot notation or bracket notation)
|
|
221
|
-
for (const part of parts) {
|
|
222
|
-
if (part.startsWith('[')) {
|
|
223
|
-
path += part; // Already formatted as bracket notation
|
|
224
|
-
}
|
|
225
|
-
else {
|
|
226
|
-
path += '.' + part; // Dot notation
|
|
227
|
-
}
|
|
228
|
-
}
|
|
230
|
+
const path = renderPathSegments(objectName, segments);
|
|
231
|
+
pathSegments.set(path, segments);
|
|
229
232
|
return path;
|
|
230
233
|
}
|
|
231
234
|
return null;
|
|
@@ -446,29 +449,24 @@ function getObjectUsagesInHook(hookBody, objectName) {
|
|
|
446
449
|
paths.forEach((path) => {
|
|
447
450
|
// Always include the main path
|
|
448
451
|
finalPaths.add(path);
|
|
449
|
-
|
|
450
|
-
if (
|
|
451
|
-
|
|
452
|
-
// For userData?.profile.settings.theme.primary, we want to include userData?.profile
|
|
453
|
-
const firstOptionalIndex = path.indexOf('?.');
|
|
454
|
-
if (firstOptionalIndex !== -1) {
|
|
455
|
-
// Find the end of the first property after the optional chaining
|
|
456
|
-
const afterOptional = path.substring(firstOptionalIndex + 2);
|
|
457
|
-
const nextDotIndex = afterOptional.indexOf('.');
|
|
458
|
-
if (nextDotIndex !== -1) {
|
|
459
|
-
// There are more properties after the first optional property
|
|
460
|
-
const firstOptionalPath = path.substring(0, firstOptionalIndex + 2 + nextDotIndex);
|
|
461
|
-
finalPaths.add(firstOptionalPath);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
452
|
+
const segments = pathSegments.get(path);
|
|
453
|
+
if (!segments) {
|
|
454
|
+
return;
|
|
464
455
|
}
|
|
465
|
-
//
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
456
|
+
// Include the FIRST optional link as an intermediate dependency when more
|
|
457
|
+
// links follow it: for userData?.profile.settings.theme.primary we also
|
|
458
|
+
// want userData?.profile.
|
|
459
|
+
const firstOptionalIndex = segments.findIndex((segment) => segment.optional);
|
|
460
|
+
if (firstOptionalIndex !== -1 && firstOptionalIndex < segments.length - 1) {
|
|
461
|
+
finalPaths.add(renderPathSegments(objectName, segments.slice(0, firstOptionalIndex + 1)));
|
|
462
|
+
}
|
|
463
|
+
// For array access, include the array property itself: for
|
|
464
|
+
// userData.items[0] we also want userData.items. A bracket directly on
|
|
465
|
+
// the base (state[0], state?.[0]) adds nothing — its "array" is the
|
|
466
|
+
// entire object dependency this rule exists to narrow away.
|
|
467
|
+
const firstComputedIndex = segments.findIndex((segment) => segment.computed);
|
|
468
|
+
if (firstComputedIndex > 0) {
|
|
469
|
+
finalPaths.add(renderPathSegments(objectName, segments.slice(0, firstComputedIndex)));
|
|
472
470
|
}
|
|
473
471
|
});
|
|
474
472
|
// Convert to array for sorting
|
|
@@ -477,9 +475,11 @@ function getObjectUsagesInHook(hookBody, objectName) {
|
|
|
477
475
|
// Exception: keep array paths with optional chaining as they represent different dependencies
|
|
478
476
|
const filteredPaths = pathsArray.filter((path) => {
|
|
479
477
|
// Skip array paths if we're accessing specific indices, unless it's optional chaining
|
|
478
|
+
// why: an optional bracket renders as `?.[`, so the specific-index probe
|
|
479
|
+
// must accept both `base[0]` and `base?.[0]` shapes.
|
|
480
480
|
const isArrayWithSpecificIndices = pathsArray.some((otherPath) => otherPath !== path &&
|
|
481
481
|
(otherPath.startsWith(path + '[') ||
|
|
482
|
-
otherPath.
|
|
482
|
+
otherPath.startsWith(path + '?.[')));
|
|
483
483
|
// Keep array paths with optional chaining even if specific indices are accessed
|
|
484
484
|
if (isArrayWithSpecificIndices && path.includes('?.')) {
|
|
485
485
|
return true;
|
|
@@ -50,6 +50,18 @@ const FUNCTION_TYPES = new Set([
|
|
|
50
50
|
utils_1.AST_NODE_TYPES.FunctionExpression,
|
|
51
51
|
utils_1.AST_NODE_TYPES.FunctionDeclaration,
|
|
52
52
|
]);
|
|
53
|
+
/**
|
|
54
|
+
* Function/constructor/conditional type notation must be parenthesized to
|
|
55
|
+
* appear as a `|` union member, or the emitted annotation does not parse
|
|
56
|
+
* ("Function type notation must be parenthesized when used in a union type").
|
|
57
|
+
* Over-wrapping is harmless — a parenthesized type is valid in any type
|
|
58
|
+
* position — so this tests the printed text conservatively instead of
|
|
59
|
+
* re-deriving the printer's precedence rules.
|
|
60
|
+
*/
|
|
61
|
+
function parenthesizeForUnion(text) {
|
|
62
|
+
const needsParens = text.includes('=>') || /^new\b/.test(text) || /\bextends\b/.test(text);
|
|
63
|
+
return needsParens ? `(${text})` : text;
|
|
64
|
+
}
|
|
53
65
|
exports.preferMapOverConditionalDispatch = (0, createRule_1.createRule)({
|
|
54
66
|
name: 'prefer-map-over-conditional-dispatch',
|
|
55
67
|
meta: {
|
|
@@ -194,7 +206,13 @@ exports.preferMapOverConditionalDispatch = (0, createRule_1.createRule)({
|
|
|
194
206
|
parts.push(text);
|
|
195
207
|
}
|
|
196
208
|
}
|
|
197
|
-
|
|
209
|
+
if (parts.length === 0) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
if (parts.length === 1) {
|
|
213
|
+
return parts[0];
|
|
214
|
+
}
|
|
215
|
+
return parts.map(parenthesizeForUnion).join(' | ');
|
|
198
216
|
}
|
|
199
217
|
function discriminantTypeText(type, discriminant) {
|
|
200
218
|
try {
|
|
@@ -209,6 +227,94 @@ exports.preferMapOverConditionalDispatch = (0, createRule_1.createRule)({
|
|
|
209
227
|
return null;
|
|
210
228
|
}
|
|
211
229
|
}
|
|
230
|
+
/**
|
|
231
|
+
* `checker.typeToString()` prints a symbol's bare name with no regard for
|
|
232
|
+
* whether that name resolves at the fix site (an unimported helper type
|
|
233
|
+
* prints the same as an imported one), and exotic printer output can be
|
|
234
|
+
* invalid in an annotation position. Shipping such an annotation breaks
|
|
235
|
+
* the build, so the fix is gated on the synthesized text (a) parsing
|
|
236
|
+
* standalone and (b) referencing only names in scope where the Record is
|
|
237
|
+
* inserted. Failing the gate downgrades to the report-only path — the
|
|
238
|
+
* plugin prefers a skipped fix over one that does not compile.
|
|
239
|
+
*/
|
|
240
|
+
function validateAnnotation(annotationText, fixSite) {
|
|
241
|
+
const sourceFile = ts.createSourceFile('__annotation__.ts', `type __T = ${annotationText};`, ts.ScriptTarget.Latest, true);
|
|
242
|
+
// parseDiagnostics is absent from the public SourceFile type but always
|
|
243
|
+
// populated at runtime; a diagnostic here means the annotation cannot
|
|
244
|
+
// ship (e.g. printer truncation, or an unparenthesized member shape the
|
|
245
|
+
// union-wrapping heuristic does not recognize).
|
|
246
|
+
const parseDiagnostics = sourceFile.parseDiagnostics;
|
|
247
|
+
if (!parseDiagnostics || parseDiagnostics.length > 0) {
|
|
248
|
+
return 'unparseable';
|
|
249
|
+
}
|
|
250
|
+
const typeReferenceRoots = new Set();
|
|
251
|
+
const typeQueryRoots = new Set();
|
|
252
|
+
let hasImportType = false;
|
|
253
|
+
const rootNameOf = (name) => {
|
|
254
|
+
let current = name;
|
|
255
|
+
while (ts.isQualifiedName(current)) {
|
|
256
|
+
current = current.left;
|
|
257
|
+
}
|
|
258
|
+
return current.text;
|
|
259
|
+
};
|
|
260
|
+
const collect = (node) => {
|
|
261
|
+
if (ts.isTypeReferenceNode(node)) {
|
|
262
|
+
typeReferenceRoots.add(rootNameOf(node.typeName));
|
|
263
|
+
}
|
|
264
|
+
else if (ts.isTypeQueryNode(node)) {
|
|
265
|
+
typeQueryRoots.add(rootNameOf(node.exprName));
|
|
266
|
+
}
|
|
267
|
+
else if (ts.isImportTypeNode(node)) {
|
|
268
|
+
// `import("...").T` paths printed by the checker are absolute or
|
|
269
|
+
// resolver-relative — never portable source text.
|
|
270
|
+
hasImportType = true;
|
|
271
|
+
}
|
|
272
|
+
ts.forEachChild(node, collect);
|
|
273
|
+
};
|
|
274
|
+
collect(sourceFile);
|
|
275
|
+
if (hasImportType) {
|
|
276
|
+
return 'unresolvable';
|
|
277
|
+
}
|
|
278
|
+
// `Record` is the wrapper this rule itself emits — a TS lib global that
|
|
279
|
+
// is present in any real project. The isolated single-file program a
|
|
280
|
+
// RuleTester builds loads no lib files at all, so requiring it in scope
|
|
281
|
+
// would falsely downgrade every fix under test.
|
|
282
|
+
typeReferenceRoots.delete('Record');
|
|
283
|
+
if (typeReferenceRoots.size === 0 && typeQueryRoots.size === 0) {
|
|
284
|
+
return 'ok';
|
|
285
|
+
}
|
|
286
|
+
const tsFixSite = esTreeNodeToTSNodeMap.get(fixSite);
|
|
287
|
+
if (!tsFixSite) {
|
|
288
|
+
return 'unresolvable';
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
const namesInScope = (meaning) => new Set(checker
|
|
292
|
+
.getSymbolsInScope(tsFixSite, meaning)
|
|
293
|
+
.map((symbol) => symbol.name));
|
|
294
|
+
if (typeReferenceRoots.size > 0) {
|
|
295
|
+
const typeNames = namesInScope(ts.SymbolFlags.Type |
|
|
296
|
+
ts.SymbolFlags.Namespace |
|
|
297
|
+
ts.SymbolFlags.Alias);
|
|
298
|
+
for (const root of typeReferenceRoots) {
|
|
299
|
+
if (!typeNames.has(root)) {
|
|
300
|
+
return 'unresolvable';
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (typeQueryRoots.size > 0) {
|
|
305
|
+
const valueNames = namesInScope(ts.SymbolFlags.Value | ts.SymbolFlags.Alias);
|
|
306
|
+
for (const root of typeQueryRoots) {
|
|
307
|
+
if (!valueNames.has(root)) {
|
|
308
|
+
return 'unresolvable';
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
return 'unresolvable';
|
|
315
|
+
}
|
|
316
|
+
return 'ok';
|
|
317
|
+
}
|
|
212
318
|
// ---- AST helpers --------------------------------------------------------
|
|
213
319
|
/** Whether a discriminant expression is an identifier or a call-free,
|
|
214
320
|
* non-optional member chain (safe to collapse repeated evaluations). */
|
|
@@ -500,6 +606,19 @@ exports.preferMapOverConditionalDispatch = (0, createRule_1.createRule)({
|
|
|
500
606
|
});
|
|
501
607
|
return;
|
|
502
608
|
}
|
|
609
|
+
const verdict = validateAnnotation(`Record<${dText}, ${vText}>`, discriminantOf(node));
|
|
610
|
+
if (verdict !== 'ok') {
|
|
611
|
+
context.report({
|
|
612
|
+
node,
|
|
613
|
+
messageId: 'preferMapManual',
|
|
614
|
+
data: {
|
|
615
|
+
reason: verdict === 'unparseable'
|
|
616
|
+
? 'the branch value type does not print as a parseable annotation — write the Record with an explicit type manually'
|
|
617
|
+
: 'the annotation would name types that are not in scope at the fix site — import them or write the Record manually',
|
|
618
|
+
},
|
|
619
|
+
});
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
503
622
|
context.report({
|
|
504
623
|
node,
|
|
505
624
|
messageId: 'preferMap',
|
|
@@ -197,10 +197,21 @@ exports.useLatestCallback = (0, createRule_1.createRule)({
|
|
|
197
197
|
return;
|
|
198
198
|
}
|
|
199
199
|
const specifiers = useCallbackSpecifiersOf(statement);
|
|
200
|
+
// A conversion nested inside another conversion cannot join the atomic
|
|
201
|
+
// batch: the outer replacement re-emits the inner call's original text,
|
|
202
|
+
// so fixing both at once would produce overlapping edits. The inner
|
|
203
|
+
// call is reported without a fix; because its callee then counts as a
|
|
204
|
+
// surviving reference, the react import is preserved and a later pass
|
|
205
|
+
// converts it against the rewritten text.
|
|
206
|
+
const isNestedConversion = (candidate) => conversions.some((other) => other.node !== candidate.node &&
|
|
207
|
+
other.node.range[0] <= candidate.node.range[0] &&
|
|
208
|
+
candidate.node.range[1] <= other.node.range[1]);
|
|
209
|
+
const batchedConversions = conversions.filter((conversion) => !isNestedConversion(conversion));
|
|
210
|
+
const deferredConversions = conversions.filter(isNestedConversion);
|
|
200
211
|
// A reference the fix does not rewrite (a JSX-returning call, an
|
|
201
212
|
// argument-less call, or `useCallback` used as a value) keeps needing
|
|
202
213
|
// react's binding, so the import must be preserved verbatim.
|
|
203
|
-
const convertedCallees = new Set(
|
|
214
|
+
const convertedCallees = new Set(batchedConversions
|
|
204
215
|
.map((conversion) => conversion.callee)
|
|
205
216
|
.filter((callee) => !!callee));
|
|
206
217
|
const hasSurvivingReference = context
|
|
@@ -231,7 +242,84 @@ exports.useLatestCallback = (0, createRule_1.createRule)({
|
|
|
231
242
|
: useCallbackLocalName === 'useCallback'
|
|
232
243
|
? 'useLatestCallback'
|
|
233
244
|
: useCallbackLocalName;
|
|
234
|
-
|
|
245
|
+
const importText = `import ${recommendedHook} from 'use-latest-callback';`;
|
|
246
|
+
// The react import statement participates in the change set only when
|
|
247
|
+
// it binds useCallback or anchors a React.useCallback member call.
|
|
248
|
+
const touchesImport = specifiers.length > 0 || hasReactMemberUseCallback;
|
|
249
|
+
const importFixes = (fixer) => {
|
|
250
|
+
if (!touchesImport) {
|
|
251
|
+
return [];
|
|
252
|
+
}
|
|
253
|
+
// A surviving reference (or a member-only file) leaves the react
|
|
254
|
+
// import untouched; only the new import is added when missing.
|
|
255
|
+
if (hasSurvivingReference || specifiers.length === 0) {
|
|
256
|
+
if (hasUseLatestCallbackImport) {
|
|
257
|
+
return [];
|
|
258
|
+
}
|
|
259
|
+
return [fixer.insertTextBefore(statement, `${importText}\n`)];
|
|
260
|
+
}
|
|
261
|
+
const defaultOrNamespace = statement.specifiers.find((s) => s.type === utils_1.AST_NODE_TYPES.ImportDefaultSpecifier ||
|
|
262
|
+
s.type === utils_1.AST_NODE_TYPES.ImportNamespaceSpecifier);
|
|
263
|
+
const remainingNamed = statement.specifiers.filter((s) => s.type === utils_1.AST_NODE_TYPES.ImportSpecifier &&
|
|
264
|
+
s.imported.type === utils_1.AST_NODE_TYPES.Identifier &&
|
|
265
|
+
s.imported.name !== 'useCallback');
|
|
266
|
+
const prefix = statement.importKind && statement.importKind !== 'value'
|
|
267
|
+
? 'import type'
|
|
268
|
+
: 'import';
|
|
269
|
+
if (remainingNamed.length === 0 && !defaultOrNamespace) {
|
|
270
|
+
if (!hasUseLatestCallbackImport) {
|
|
271
|
+
return [fixer.replaceText(statement, importText)];
|
|
272
|
+
}
|
|
273
|
+
return [fixer.remove(statement)];
|
|
274
|
+
}
|
|
275
|
+
const parts = [];
|
|
276
|
+
if (defaultOrNamespace) {
|
|
277
|
+
parts.push(sourceCode.getText(defaultOrNamespace));
|
|
278
|
+
}
|
|
279
|
+
if (remainingNamed.length > 0) {
|
|
280
|
+
parts.push(`{ ${remainingNamed
|
|
281
|
+
.map((s) => sourceCode.getText(s))
|
|
282
|
+
.join(', ')} }`);
|
|
283
|
+
}
|
|
284
|
+
const replacement = `${prefix} ${parts.join(', ')} from 'react';`;
|
|
285
|
+
const fixes = [];
|
|
286
|
+
if (!hasUseLatestCallbackImport) {
|
|
287
|
+
fixes.push(fixer.insertTextBefore(statement, `${importText}\n`));
|
|
288
|
+
}
|
|
289
|
+
fixes.push(fixer.replaceText(statement, replacement));
|
|
290
|
+
return fixes;
|
|
291
|
+
};
|
|
292
|
+
const conversionFix = (fixer, conversion) => {
|
|
293
|
+
const callbackText = sourceCode.getText(conversion.node.arguments[0]);
|
|
294
|
+
const typeParams = conversion.node.typeParameters
|
|
295
|
+
? sourceCode.getText(conversion.node.typeParameters)
|
|
296
|
+
: '';
|
|
297
|
+
// Replace useCallback with useLatestCallback and remove the dependency array
|
|
298
|
+
return fixer.replaceText(conversion.node, `${recommendedHook}${typeParams}(${callbackText})`);
|
|
299
|
+
};
|
|
300
|
+
// Every call-site conversion and the import rewrite ride on ONE fix
|
|
301
|
+
// from ONE report. ESLint discards a multi-part fix wholesale when any
|
|
302
|
+
// part conflicts with another rule's fix and retries it on the next
|
|
303
|
+
// pass against the updated text, whereas fixes split across reports
|
|
304
|
+
// land piecemeal: the disjoint import rewrite would apply even when
|
|
305
|
+
// the call-site conversion is deferred, permanently stranding a
|
|
306
|
+
// `useCallback(...)` call with no import (issue #1400).
|
|
307
|
+
const [fixOwner, ...followers] = batchedConversions;
|
|
308
|
+
context.report({
|
|
309
|
+
node: fixOwner.node,
|
|
310
|
+
messageId: 'useLatestCallback',
|
|
311
|
+
data: {
|
|
312
|
+
currentHook: fixOwner.currentHook,
|
|
313
|
+
recommendedHook,
|
|
314
|
+
},
|
|
315
|
+
fix(fixer) {
|
|
316
|
+
return [
|
|
317
|
+
...batchedConversions.map((conversion) => conversionFix(fixer, conversion)),
|
|
318
|
+
...importFixes(fixer),
|
|
319
|
+
];
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
for (const conversion of [...followers, ...deferredConversions]) {
|
|
235
323
|
context.report({
|
|
236
324
|
node: conversion.node,
|
|
237
325
|
messageId: 'useLatestCallback',
|
|
@@ -239,34 +327,13 @@ exports.useLatestCallback = (0, createRule_1.createRule)({
|
|
|
239
327
|
currentHook: conversion.currentHook,
|
|
240
328
|
recommendedHook,
|
|
241
329
|
},
|
|
242
|
-
fix(fixer) {
|
|
243
|
-
const callbackText = sourceCode.getText(conversion.node.arguments[0]);
|
|
244
|
-
const typeParams = conversion.node.typeParameters
|
|
245
|
-
? sourceCode.getText(conversion.node.typeParameters)
|
|
246
|
-
: '';
|
|
247
|
-
// Replace useCallback with useLatestCallback and remove the dependency array
|
|
248
|
-
return fixer.replaceText(conversion.node, `${recommendedHook}${typeParams}(${callbackText})`);
|
|
249
|
-
},
|
|
250
330
|
});
|
|
251
331
|
}
|
|
252
|
-
if (
|
|
332
|
+
if (!touchesImport) {
|
|
253
333
|
return;
|
|
254
334
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (hasUseLatestCallbackImport) {
|
|
258
|
-
return; // The react import stays as is and the new import exists
|
|
259
|
-
}
|
|
260
|
-
context.report({
|
|
261
|
-
node: statement,
|
|
262
|
-
messageId: 'useLatestCallback',
|
|
263
|
-
data: {
|
|
264
|
-
currentHook: useCallbackLocalName,
|
|
265
|
-
recommendedHook,
|
|
266
|
-
},
|
|
267
|
-
fix: (fixer) => fixer.insertTextBefore(statement, `${importText}\n`),
|
|
268
|
-
});
|
|
269
|
-
return;
|
|
335
|
+
if (hasSurvivingReference && hasUseLatestCallbackImport) {
|
|
336
|
+
return; // The react import stays as is and the new import exists
|
|
270
337
|
}
|
|
271
338
|
context.report({
|
|
272
339
|
node: statement,
|
|
@@ -275,43 +342,6 @@ exports.useLatestCallback = (0, createRule_1.createRule)({
|
|
|
275
342
|
currentHook: useCallbackLocalName,
|
|
276
343
|
recommendedHook,
|
|
277
344
|
},
|
|
278
|
-
fix(fixer) {
|
|
279
|
-
if (specifiers.length === 0) {
|
|
280
|
-
if (hasUseLatestCallbackImport)
|
|
281
|
-
return null;
|
|
282
|
-
return fixer.insertTextBefore(statement, `${importText}\n`);
|
|
283
|
-
}
|
|
284
|
-
const defaultOrNamespace = statement.specifiers.find((s) => s.type === utils_1.AST_NODE_TYPES.ImportDefaultSpecifier ||
|
|
285
|
-
s.type === utils_1.AST_NODE_TYPES.ImportNamespaceSpecifier);
|
|
286
|
-
const remainingNamed = statement.specifiers.filter((s) => s.type === utils_1.AST_NODE_TYPES.ImportSpecifier &&
|
|
287
|
-
s.imported.type === utils_1.AST_NODE_TYPES.Identifier &&
|
|
288
|
-
s.imported.name !== 'useCallback');
|
|
289
|
-
const prefix = statement.importKind && statement.importKind !== 'value'
|
|
290
|
-
? 'import type'
|
|
291
|
-
: 'import';
|
|
292
|
-
if (remainingNamed.length === 0 && !defaultOrNamespace) {
|
|
293
|
-
if (!hasUseLatestCallbackImport) {
|
|
294
|
-
return fixer.replaceText(statement, importText);
|
|
295
|
-
}
|
|
296
|
-
return fixer.remove(statement);
|
|
297
|
-
}
|
|
298
|
-
const parts = [];
|
|
299
|
-
if (defaultOrNamespace) {
|
|
300
|
-
parts.push(sourceCode.getText(defaultOrNamespace));
|
|
301
|
-
}
|
|
302
|
-
if (remainingNamed.length > 0) {
|
|
303
|
-
parts.push(`{ ${remainingNamed
|
|
304
|
-
.map((s) => sourceCode.getText(s))
|
|
305
|
-
.join(', ')} }`);
|
|
306
|
-
}
|
|
307
|
-
const replacement = `${prefix} ${parts.join(', ')} from 'react';`;
|
|
308
|
-
const fixes = [];
|
|
309
|
-
if (!hasUseLatestCallbackImport) {
|
|
310
|
-
fixes.push(fixer.insertTextBefore(statement, `${importText}\n`));
|
|
311
|
-
}
|
|
312
|
-
fixes.push(fixer.replaceText(statement, replacement));
|
|
313
|
-
return fixes;
|
|
314
|
-
},
|
|
315
345
|
});
|
|
316
346
|
},
|
|
317
347
|
};
|
package/package.json
CHANGED
package/release-manifest.json
CHANGED
|
@@ -1,4 +1,40 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "1.20.25",
|
|
4
|
+
"date": "2026-07-30T02:59:17.229Z",
|
|
5
|
+
"rules": [
|
|
6
|
+
{
|
|
7
|
+
"name": "no-entire-object-hook-deps",
|
|
8
|
+
"changeType": "fix",
|
|
9
|
+
"issues": [
|
|
10
|
+
1401
|
|
11
|
+
],
|
|
12
|
+
"summary": "render optional links per segment (closes #1401)"
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"name": "prefer-map-over-conditional-dispatch",
|
|
16
|
+
"changeType": "fix",
|
|
17
|
+
"issues": [
|
|
18
|
+
1402
|
|
19
|
+
],
|
|
20
|
+
"summary": "validate the synthesized Record annotation (closes #1402)"
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"version": "1.20.24",
|
|
26
|
+
"date": "2026-07-30T02:00:54.523Z",
|
|
27
|
+
"rules": [
|
|
28
|
+
{
|
|
29
|
+
"name": "use-latest-callback",
|
|
30
|
+
"changeType": "fix",
|
|
31
|
+
"issues": [
|
|
32
|
+
1400
|
|
33
|
+
],
|
|
34
|
+
"summary": "apply the import rewrite and call conversions atomically (closes #1400)"
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
},
|
|
2
38
|
{
|
|
3
39
|
"version": "1.20.23",
|
|
4
40
|
"date": "2026-07-30T01:37:58.854Z",
|