@tcy/eslint-rules 1.12.0 → 1.13.0
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/README.md +64 -11
- package/coverage/clover.xml +339 -120
- package/coverage/coverage-final.json +2 -1
- package/coverage/lcov-report/index.html +19 -19
- package/coverage/lcov-report/src/array-elements-per-line.js.html +1 -1
- package/coverage/lcov-report/src/back/back.js.html +1 -1
- package/coverage/lcov-report/src/back/http.js.html +1 -1
- package/coverage/lcov-report/src/back/index.html +1 -1
- package/coverage/lcov-report/src/back/recommended.js.html +1 -1
- package/coverage/lcov-report/src/bin/eslint-cache-guard.js.html +1 -1
- package/coverage/lcov-report/src/bin/index.html +1 -1
- package/coverage/lcov-report/src/client/client.js.html +5 -2
- package/coverage/lcov-report/src/client/index.html +1 -1
- package/coverage/lcov-report/src/client/recommended.js.html +1 -1
- package/coverage/lcov-report/src/consistent-const-scoping.js.html +1 -1
- package/coverage/lcov-report/src/decorator-type-enforcement.js.html +1 -1
- package/coverage/lcov-report/src/enforce-tailwind-important.js.html +1 -1
- package/coverage/lcov-report/src/export-specifiers-per-line.js.html +1 -1
- package/coverage/lcov-report/src/import-specifiers-per-line.js.html +1 -1
- package/coverage/lcov-report/src/index.html +34 -19
- package/coverage/lcov-report/src/index.js.html +1 -1
- package/coverage/lcov-report/src/jsx-boolean-shorthand.js.html +1 -1
- package/coverage/lcov-report/src/jsx-expression-string-literals.js.html +1 -1
- package/coverage/lcov-report/src/jsx-ref-string-exists.js.html +1 -1
- package/coverage/lcov-report/src/jsx-ref-type-match.js.html +865 -0
- package/coverage/lcov-report/src/no-static-key-in-map.js.html +1 -1
- package/coverage/lcov-report/src/no-unused-setup-return.js.html +725 -50
- package/coverage/lcov-report/src/no-v-model-on-prop.js.html +1 -1
- package/coverage/lcov-report/src/plugin.js.html +8 -2
- package/coverage/lcov-report/src/recommended.js.html +1 -1
- package/coverage/lcov-report/src/require-fragment-key.js.html +1 -1
- package/coverage/lcov-report/src/route-dto-required.js.html +1 -1
- package/coverage/lcov-report/src/v-model-name-match.js.html +1 -1
- package/coverage/lcov-report/src/vuejs-define-component.js.html +1 -1
- package/coverage/lcov-report/src/vuejs-define-workspace.js.html +1 -1
- package/coverage/lcov.info +761 -267
- package/decl/back/back.d.ts +20 -0
- package/decl/client/client.d.ts +21 -0
- package/decl/jsx-ref-type-match.d.ts +34 -0
- package/decl/no-unused-setup-return.d.ts +9 -0
- package/decl/plugin.d.ts +20 -0
- package/package.json +1 -1
- package/src/client/client.js +1 -0
- package/src/jsx-ref-type-match.js +260 -0
- package/src/no-unused-setup-return.js +235 -10
- package/src/plugin.js +2 -0
- package/tests/jsx-ref-type-match.spec.js +118 -0
- package/tests/no-unused-setup-return.spec.js +65 -1
|
@@ -15,7 +15,13 @@
|
|
|
15
15
|
// The check is by name, on purpose: it can miss an unused key sharing its name with something else,
|
|
16
16
|
// but never reports a used one. `ref="name"` is a use too.
|
|
17
17
|
//
|
|
18
|
+
// A key read from outside the component, through a typed ref (`cmp.value?.focus()` with
|
|
19
|
+
// `ref<VInputCheckboxBoolean>()`), is used too: with type information, the program is searched for an
|
|
20
|
+
// identifier resolving to the returned property. A key read by another app (the public API of a
|
|
21
|
+
// library) can't be found: mark it `/** @public */ focus,` (or `focus, // @public`).
|
|
22
|
+
//
|
|
18
23
|
// The directory is skipped when:
|
|
24
|
+
// - the composable is imported by a file of another directory (a component reusing it)
|
|
19
25
|
// - it has no `Component.ts` (a file calling `defineComponent`) importing the composable:
|
|
20
26
|
// a composable shared by many components, or used through inject / by a parent
|
|
21
27
|
// - a render file spreads (`...c`), or passes the whole context to a function (`foo(c)`) that
|
|
@@ -31,7 +37,8 @@ export default {
|
|
|
31
37
|
description: 'Disallow a key returned by a composable that is not used by the component (render or other compositions).',
|
|
32
38
|
},
|
|
33
39
|
messages: {
|
|
34
|
-
unused: '"{{name}}" is returned by the setup but not used by the render or by another composition of the component.'
|
|
40
|
+
unused: '"{{name}}" is returned by the setup but not used by the render or by another composition of the component. '
|
|
41
|
+
+ 'If it is public API read through a component ref, mark it `/** @public */`.',
|
|
35
42
|
},
|
|
36
43
|
schema: [{
|
|
37
44
|
type: 'object',
|
|
@@ -59,6 +66,9 @@ export default {
|
|
|
59
66
|
// otherwise it is shared (inject, parent, ...) and the keys are read from elsewhere
|
|
60
67
|
const base = path.basename(filename).replace(EXT, '');
|
|
61
68
|
if (isComposable) {
|
|
69
|
+
// used by a component of another directory: its keys are read there
|
|
70
|
+
if (isImportedElsewhere(filename)) return {};
|
|
71
|
+
|
|
62
72
|
const component = siblings.find((s) => !s.inner && isComponentFile(s));
|
|
63
73
|
if (!component || !new RegExp(`from\\s+['"]\\./${escapeRegExp(base)}['"]`).test(component.text)) return {};
|
|
64
74
|
} else if (!/\bdefineComponent\s*\(/.test(context.sourceCode.text)) {
|
|
@@ -66,6 +76,16 @@ export default {
|
|
|
66
76
|
}
|
|
67
77
|
const isTarget = (fn, names) => (isComposable ? isExported(fn, names) : isSetup(fn));
|
|
68
78
|
|
|
79
|
+
// the render can be shared and live elsewhere (`import render from '../useXxxRender'`)
|
|
80
|
+
const componentText = isComposable
|
|
81
|
+
? siblings.find((s) => !s.inner && isComponentFile(s))?.text
|
|
82
|
+
: context.sourceCode.text;
|
|
83
|
+
for (const text of readImportedRenders(componentText ?? '', path.dirname(filename))) {
|
|
84
|
+
siblings.push({
|
|
85
|
+
name: 'render', inner: false, isRender: true, isComposable: false, text,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
69
89
|
const texts = siblings.map((s) => s.text);
|
|
70
90
|
|
|
71
91
|
// the render passes its whole context: `...c` hides the keys that are read, `foo(c)` is
|
|
@@ -90,6 +110,10 @@ export default {
|
|
|
90
110
|
|
|
91
111
|
const exportedNames = new Set();
|
|
92
112
|
|
|
113
|
+
const isPublic = (prop) => hasPublicTag(context.sourceCode, prop);
|
|
114
|
+
const isReadThroughType = makeTypeUsage(context.sourceCode.parserServices);
|
|
115
|
+
const options = { ignore, isPublic, isReadThroughType };
|
|
116
|
+
|
|
93
117
|
return {
|
|
94
118
|
Program(program) {
|
|
95
119
|
for (const node of program.body) {
|
|
@@ -107,7 +131,7 @@ export default {
|
|
|
107
131
|
enter(node);
|
|
108
132
|
// `=> ({ a, b })`
|
|
109
133
|
if (node.body.type === 'ObjectExpression' && isTarget(node, exportedNames)) {
|
|
110
|
-
check(context, node.body, texts,
|
|
134
|
+
check(context, node.body, texts, options);
|
|
111
135
|
}
|
|
112
136
|
},
|
|
113
137
|
'ArrowFunctionExpression:exit': leave,
|
|
@@ -116,7 +140,7 @@ export default {
|
|
|
116
140
|
if (node.argument?.type !== 'ObjectExpression') return;
|
|
117
141
|
const fn = stack[stack.length - 1];
|
|
118
142
|
if (!fn || !isTarget(fn, exportedNames)) return;
|
|
119
|
-
check(context, node.argument, texts,
|
|
143
|
+
check(context, node.argument, texts, options);
|
|
120
144
|
},
|
|
121
145
|
};
|
|
122
146
|
},
|
|
@@ -153,6 +177,94 @@ const readSiblings = (filename) => {
|
|
|
153
177
|
|
|
154
178
|
const MAX_DEPTH = 4;
|
|
155
179
|
|
|
180
|
+
// ─── importers of a composable, in the whole project ────────────────────────
|
|
181
|
+
|
|
182
|
+
const IMPORT_RE = /(?:from|import)\s*\(?\s*['"]([^'"\n]+)['"]/g;
|
|
183
|
+
const SKIP_DIRS = new Set(['node_modules', 'dist', 'dist_types', 'coverage', '.git', 'decl']);
|
|
184
|
+
const INDEX_TTL = 5000;
|
|
185
|
+
|
|
186
|
+
const fileImports = new Map(); // file → { mtimeMs, specs }
|
|
187
|
+
const indexes = new Map(); // root → { time, byBase: Map<basename, [{ file, spec }]> }
|
|
188
|
+
|
|
189
|
+
const findRoot = (dir) => {
|
|
190
|
+
let d = dir;
|
|
191
|
+
while (true) {
|
|
192
|
+
if (fs.existsSync(path.join(d, 'package.json'))) return d;
|
|
193
|
+
const up = path.dirname(d);
|
|
194
|
+
if (up === d) return dir;
|
|
195
|
+
d = up;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const collectFiles = (dir, out) => {
|
|
200
|
+
let entries;
|
|
201
|
+
try {
|
|
202
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
203
|
+
} catch {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
for (const e of entries) {
|
|
207
|
+
if (e.isDirectory()) {
|
|
208
|
+
if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) collectFiles(path.join(dir, e.name), out);
|
|
209
|
+
} else if (EXT.test(e.name)) {
|
|
210
|
+
out.push(path.join(dir, e.name));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const getIndex = (root) => {
|
|
216
|
+
const hit = indexes.get(root);
|
|
217
|
+
if (hit && Date.now() - hit.time < INDEX_TTL) return hit.byBase;
|
|
218
|
+
|
|
219
|
+
const src = path.join(root, 'src');
|
|
220
|
+
const files = [];
|
|
221
|
+
collectFiles(fs.existsSync(src) ? src : root, files);
|
|
222
|
+
|
|
223
|
+
const byBase = new Map();
|
|
224
|
+
for (const file of files) {
|
|
225
|
+
let specs;
|
|
226
|
+
try {
|
|
227
|
+
const { mtimeMs } = fs.statSync(file);
|
|
228
|
+
const cached = fileImports.get(file);
|
|
229
|
+
if (cached?.mtimeMs === mtimeMs) {
|
|
230
|
+
specs = cached.specs;
|
|
231
|
+
} else {
|
|
232
|
+
specs = [...fs.readFileSync(file, 'utf8').matchAll(IMPORT_RE)].map((m) => m[1]);
|
|
233
|
+
fileImports.set(file, { mtimeMs, specs });
|
|
234
|
+
}
|
|
235
|
+
} catch {
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
for (const spec of specs) {
|
|
240
|
+
const base = path.basename(spec).replace(EXT, '');
|
|
241
|
+
if (!byBase.has(base)) byBase.set(base, []);
|
|
242
|
+
byBase.get(base).push({ file, spec });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
indexes.set(root, { time: Date.now(), byBase });
|
|
247
|
+
return byBase;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* The composable is imported by a file of another directory: relative specifiers must resolve to
|
|
252
|
+
* it, other ones (`@/...`) are matched by file name
|
|
253
|
+
*/
|
|
254
|
+
export const isImportedElsewhere = (filename) => {
|
|
255
|
+
const dir = path.dirname(filename);
|
|
256
|
+
const base = path.basename(filename).replace(EXT, '');
|
|
257
|
+
const importers = getIndex(findRoot(dir)).get(base) ?? [];
|
|
258
|
+
const target = path.join(dir, base);
|
|
259
|
+
|
|
260
|
+
return importers.some(({ file, spec }) => {
|
|
261
|
+
if (path.dirname(file) === dir) return false;
|
|
262
|
+
if (!spec.startsWith('.')) return true;
|
|
263
|
+
return path.resolve(path.dirname(file), spec).replace(EXT, '') === target;
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
// `inner` depends on the directory being linted, so it is not part of the cached file
|
|
156
268
|
// files of the directory, `inner` the ones of its sub-directories: a child component can read
|
|
157
269
|
// the keys through the context type
|
|
158
270
|
const walk = (dir, self, depth, result) => {
|
|
@@ -178,19 +290,18 @@ const walk = (dir, self, depth, result) => {
|
|
|
178
290
|
const { mtimeMs } = fs.statSync(file);
|
|
179
291
|
const hit = cache.get(file);
|
|
180
292
|
if (hit?.mtimeMs === mtimeMs) {
|
|
181
|
-
result.push(hit.sibling);
|
|
293
|
+
result.push({ ...hit.sibling, inner: depth > 0 });
|
|
182
294
|
continue;
|
|
183
295
|
}
|
|
184
296
|
|
|
185
297
|
const sibling = {
|
|
186
298
|
name,
|
|
187
|
-
inner: depth > 0,
|
|
188
299
|
isRender: /^useRender\./.test(name),
|
|
189
300
|
isComposable: /^use[A-Z]/.test(name),
|
|
190
301
|
text: stripComments(fs.readFileSync(file, 'utf8')),
|
|
191
302
|
};
|
|
192
303
|
cache.set(file, { mtimeMs, sibling });
|
|
193
|
-
result.push(sibling);
|
|
304
|
+
result.push({ ...sibling, inner: depth > 0 });
|
|
194
305
|
} catch {
|
|
195
306
|
// unreadable file, ignored
|
|
196
307
|
}
|
|
@@ -225,7 +336,7 @@ export const getWholeContextUsage = (text) => {
|
|
|
225
336
|
if (!ctx?.name) return { spread: false, callees: [] };
|
|
226
337
|
|
|
227
338
|
const n = escapeRegExp(ctx.name);
|
|
228
|
-
if (new RegExp(`\\.\\.\\.${n}(?![\\w
|
|
339
|
+
if (new RegExp(`\\.\\.\\.${n}(?![\\w$.\\[?])`).test(ctx.rest)) return { spread: true, callees: [] };
|
|
229
340
|
|
|
230
341
|
const callees = [];
|
|
231
342
|
const call = new RegExp(`([\\w$]+)\\s*\\(([^()]*,\\s*)?${n}\\s*[,)]`, 'g');
|
|
@@ -242,6 +353,16 @@ export const usesWholeContext = (text) => {
|
|
|
242
353
|
return spread || callees.length > 0;
|
|
243
354
|
};
|
|
244
355
|
|
|
356
|
+
/** Files imported as `render` (or `renderXxx`) by relative path */
|
|
357
|
+
export const readImportedRenders = (text, dir) => {
|
|
358
|
+
const result = [];
|
|
359
|
+
for (const m of text.matchAll(/import\s+(render\w*)\s+from\s+['"](\.[^'"]*)['"]/gi)) {
|
|
360
|
+
const content = readImported(m[1], text, dir);
|
|
361
|
+
if (content !== null) result.push(content);
|
|
362
|
+
}
|
|
363
|
+
return result;
|
|
364
|
+
};
|
|
365
|
+
|
|
245
366
|
const RESOLVE_EXT = ['.ts', '.tsx', '.js', '/index.ts', '/index.tsx', '/index.js'];
|
|
246
367
|
|
|
247
368
|
/** Text of the file imported as `name` with a relative path, `null` if not resolvable */
|
|
@@ -296,13 +417,117 @@ export const getKeyName = (prop) => {
|
|
|
296
417
|
return null;
|
|
297
418
|
};
|
|
298
419
|
|
|
299
|
-
const check = (context, objectNode, texts, ignore) => {
|
|
420
|
+
const check = (context, objectNode, texts, { ignore, isPublic, isReadThroughType }) => {
|
|
300
421
|
for (const prop of objectNode.properties) {
|
|
301
422
|
const name = getKeyName(prop);
|
|
302
|
-
if (!name || ignore.includes(name)) continue;
|
|
423
|
+
if (!name || ignore.includes(name) || isPublic(prop)) continue;
|
|
303
424
|
|
|
304
|
-
|
|
425
|
+
// by name first (cheap), then through the types (a component ref in another directory)
|
|
426
|
+
if (!isUsed(name, texts) && !isReadThroughType(objectNode, prop, name)) {
|
|
305
427
|
context.report({ node: prop, messageId: 'unused', data: { name } });
|
|
306
428
|
}
|
|
307
429
|
}
|
|
308
430
|
};
|
|
431
|
+
|
|
432
|
+
// ─── @public ────────────────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
const PUBLIC_TAG = /(?:^|[\s*])@public(?=[\s*]|$)/;
|
|
435
|
+
|
|
436
|
+
/** A comment text marks a key as public */
|
|
437
|
+
export const isPublicComment = (text) => PUBLIC_TAG.test(text);
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* `/** @public *\/ focus,` (comment before the key) or `focus, // @public` (comment after it,
|
|
441
|
+
* on the same line, the comma between)
|
|
442
|
+
*/
|
|
443
|
+
const hasPublicTag = (sourceCode, prop) => {
|
|
444
|
+
// `a, // @public` then `b` on the next line: the comment belongs to `a`, not to `b`
|
|
445
|
+
const before = sourceCode.getTokenBefore(prop);
|
|
446
|
+
const trailsPrevious = (c) => before?.value === ','
|
|
447
|
+
&& c.loc.start.line === before.loc.end.line
|
|
448
|
+
&& c.loc.end.line < prop.loc.start.line;
|
|
449
|
+
|
|
450
|
+
if (sourceCode.getCommentsBefore(prop).some((c) => !trailsPrevious(c) && isPublicComment(c.value))) return true;
|
|
451
|
+
|
|
452
|
+
let token = sourceCode.getTokenAfter(prop, { includeComments: true });
|
|
453
|
+
if (token?.type === 'Punctuator' && token.value === ',') {
|
|
454
|
+
token = sourceCode.getTokenAfter(token, { includeComments: true });
|
|
455
|
+
}
|
|
456
|
+
if (!token || (token.type !== 'Line' && token.type !== 'Block')) return false;
|
|
457
|
+
if (token.loc.start.line !== prop.loc.end.line || !isPublicComment(token.value)) return false;
|
|
458
|
+
|
|
459
|
+
// the comment ends the line, else it leads the next key: `h, /** @public */ i,`
|
|
460
|
+
const next = sourceCode.getTokenAfter(token, { includeComments: true });
|
|
461
|
+
return !next || next.loc.start.line > token.loc.end.line;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
// ─── read through the types ─────────────────────────────────────────────────
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* `(objectNode, prop, name) => boolean`: an identifier of the program resolves to the returned
|
|
468
|
+
* property, e.g. `cmp.value?.focus()` with `cmp = ref<Cmp>()` and `type Cmp = Context<typeof setup>`
|
|
469
|
+
* (a mapped type keeps the declaration of the original property). Without type information, `false`.
|
|
470
|
+
*/
|
|
471
|
+
const makeTypeUsage = (services) => {
|
|
472
|
+
if (!services?.program || !services.esTreeNodeToTSNodeMap) return () => false;
|
|
473
|
+
|
|
474
|
+
const { program } = services;
|
|
475
|
+
const checker = program.getTypeChecker();
|
|
476
|
+
|
|
477
|
+
return (objectNode, prop, name) => {
|
|
478
|
+
const tsObject = services.esTreeNodeToTSNodeMap.get(objectNode);
|
|
479
|
+
const tsProp = services.esTreeNodeToTSNodeMap.get(prop);
|
|
480
|
+
if (!tsObject || !tsProp) return false;
|
|
481
|
+
|
|
482
|
+
const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(tsObject), name);
|
|
483
|
+
if (!symbol) return false;
|
|
484
|
+
|
|
485
|
+
for (const id of findIdentifiers(program, name)) {
|
|
486
|
+
// the key itself
|
|
487
|
+
if (id.parent === tsProp) continue;
|
|
488
|
+
|
|
489
|
+
const used = checker.getSymbolAtLocation(id);
|
|
490
|
+
if (used && isSameProperty(checker, used, symbol, tsProp)) return true;
|
|
491
|
+
}
|
|
492
|
+
return false;
|
|
493
|
+
};
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
/** `used` is `target`, or a symbol derived from it (mapped / union / intersection type) */
|
|
497
|
+
const isSameProperty = (checker, used, target, tsProp) => {
|
|
498
|
+
if (used === target) return true;
|
|
499
|
+
const roots = [used, ...(checker.getRootSymbols?.(used) ?? [])];
|
|
500
|
+
return roots.some((s) => s === target || s.declarations?.includes(tsProp));
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
const identifiersCache = new WeakMap(); // program → Map<name, identifiers>
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Identifiers named `name` in the source files of the program (not `.d.ts`, not node_modules).
|
|
507
|
+
* Matched on `escapedText`, not on `SyntaxKind`: the rule doesn't import `typescript`, and
|
|
508
|
+
* the enum values change between TS versions.
|
|
509
|
+
*/
|
|
510
|
+
const findIdentifiers = (program, name) => {
|
|
511
|
+
let byName = identifiersCache.get(program);
|
|
512
|
+
if (!byName) {
|
|
513
|
+
byName = new Map();
|
|
514
|
+
identifiersCache.set(program, byName);
|
|
515
|
+
}
|
|
516
|
+
if (byName.has(name)) return byName.get(name);
|
|
517
|
+
|
|
518
|
+
const result = [];
|
|
519
|
+
const visit = (node) => {
|
|
520
|
+
if (node.escapedText === name) result.push(node);
|
|
521
|
+
node.forEachChild(visit);
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
for (const sf of program.getSourceFiles()) {
|
|
525
|
+
if (sf.isDeclarationFile || sf.fileName.includes('/node_modules/')) continue;
|
|
526
|
+
// cheap filter before walking the tree
|
|
527
|
+
if (!sf.text.includes(name)) continue;
|
|
528
|
+
visit(sf);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
byName.set(name, result);
|
|
532
|
+
return result;
|
|
533
|
+
};
|
package/src/plugin.js
CHANGED
|
@@ -4,6 +4,7 @@ import exportSpecifiersPerLineRule from './export-specifiers-per-line.js';
|
|
|
4
4
|
import jsxBooleanShorthand from './jsx-boolean-shorthand.js'
|
|
5
5
|
import jsxExpressionStringLiterals from './jsx-expression-string-literals.js';
|
|
6
6
|
import jsxRefStringExists from './jsx-ref-string-exists.js';
|
|
7
|
+
import jsxRefTypeMatch from './jsx-ref-type-match.js';
|
|
7
8
|
import enforceTailwindImportant from './enforce-tailwind-important.js';
|
|
8
9
|
import vModelNameMatch from './v-model-name-match.js';
|
|
9
10
|
import decoratorTypeEnforcement from './decorator-type-enforcement.js'
|
|
@@ -23,6 +24,7 @@ export default {
|
|
|
23
24
|
'jsx-boolean-shorthand': jsxBooleanShorthand,
|
|
24
25
|
'jsx-expression-string-literals': jsxExpressionStringLiterals,
|
|
25
26
|
'jsx-ref-string-exists': jsxRefStringExists,
|
|
27
|
+
'jsx-ref-type-match': jsxRefTypeMatch,
|
|
26
28
|
'enforce-tailwind-important': enforceTailwindImportant,
|
|
27
29
|
'v-model-name-match': vModelNameMatch,
|
|
28
30
|
'decorator-type-enforcement': decoratorTypeEnforcement,
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { parse } from '@babel/parser';
|
|
2
|
+
import {
|
|
3
|
+
getInstanceTypeNames, getTagName, isAnyOrUnknown, isIntrinsicTag, isStringRef, isUntyped,
|
|
4
|
+
} from '../src/jsx-ref-type-match';
|
|
5
|
+
|
|
6
|
+
// ─── helpers ────────────────────────────────────────────────────────────────
|
|
7
|
+
|
|
8
|
+
const openingOf = (jsx) => {
|
|
9
|
+
const ast = parse(jsx, { sourceType: 'module', plugins: ['jsx', 'typescript'] });
|
|
10
|
+
return ast.program.body[0].expression.openingElement;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// babel uses `StringLiteral`, ESTree (typescript-eslint) uses `Literal`
|
|
14
|
+
const toEstree = (attr) => (attr.value?.type === 'StringLiteral'
|
|
15
|
+
? { ...attr, value: { ...attr.value, type: 'Literal' } }
|
|
16
|
+
: attr);
|
|
17
|
+
|
|
18
|
+
// minimal checker / types: intrinsic types are recognized by their printed name
|
|
19
|
+
const checker = {
|
|
20
|
+
typeToString: (t) => (t.isUnion() ? t.types.map((u) => u.name).join(' | ') : t.name),
|
|
21
|
+
};
|
|
22
|
+
const single = (name) => ({ name, isUnion: () => false });
|
|
23
|
+
const type = (...names) => (names.length === 1
|
|
24
|
+
? single(names[0])
|
|
25
|
+
: { isUnion: () => true, types: names.map(single) });
|
|
26
|
+
|
|
27
|
+
// ─── isStringRef ────────────────────────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
describe('GIVEN "jsx-ref-type-match" / isStringRef', () => {
|
|
30
|
+
it.each([
|
|
31
|
+
['<div ref="root" />', true],
|
|
32
|
+
['<div ref={root} />', false],
|
|
33
|
+
['<div ref={"root"} />', false],
|
|
34
|
+
['<div id="root" />', false],
|
|
35
|
+
])('THEN %s → %s', (jsx, expected) => {
|
|
36
|
+
expect(isStringRef(toEstree(openingOf(jsx).attributes[0]))).toBe(expected);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// ─── getTagName ─────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe('GIVEN "jsx-ref-type-match" / getTagName', () => {
|
|
43
|
+
it.each([
|
|
44
|
+
['<div />', 'div'],
|
|
45
|
+
['<BaseInput />', 'BaseInput'],
|
|
46
|
+
['<Foo.Bar />', 'Foo.Bar'],
|
|
47
|
+
['<A.B.C />', 'A.B.C'],
|
|
48
|
+
['<svg:rect />', null],
|
|
49
|
+
])('THEN %s → %s', (jsx, expected) => {
|
|
50
|
+
expect(getTagName(openingOf(jsx))).toBe(expected);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// ─── isIntrinsicTag ─────────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
describe('GIVEN "jsx-ref-type-match" / isIntrinsicTag', () => {
|
|
57
|
+
it.each([
|
|
58
|
+
['div', true],
|
|
59
|
+
['svg', true],
|
|
60
|
+
['my-element', true],
|
|
61
|
+
['BaseInput', false],
|
|
62
|
+
['Component', false],
|
|
63
|
+
['icons.Check', false],
|
|
64
|
+
])('THEN %s → %s', (tag, expected) => {
|
|
65
|
+
expect(isIntrinsicTag(tag)).toBe(expected);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// ─── getInstanceTypeNames ───────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
describe('GIVEN "jsx-ref-type-match" / getInstanceTypeNames', () => {
|
|
72
|
+
it.each([
|
|
73
|
+
// `export default defineComponent(...)` in BaseInput.ts
|
|
74
|
+
['default', '/src/form/BaseInput.ts', 'BaseInput', ['BaseInput']],
|
|
75
|
+
// imported under another name: the file name wins over the tag
|
|
76
|
+
['default', '/src/form/BaseInput.ts', 'Input', ['BaseInput', 'Input']],
|
|
77
|
+
// named export
|
|
78
|
+
['VDropdown', '/src/dropdown/index.ts', 'VDropdown', ['VDropdown', 'index']],
|
|
79
|
+
['default', '/src/a/Foo.tsx', 'Foo', ['Foo']],
|
|
80
|
+
['default', '/src/a/Foo.d.ts', 'Foo', ['Foo']],
|
|
81
|
+
['default', '/src/a/Foo.ts', 'NS.Foo', ['Foo']],
|
|
82
|
+
])('THEN (%s, %s, %s) → %j', (exportName, fileName, tag, expected) => {
|
|
83
|
+
expect(getInstanceTypeNames(exportName, fileName, tag)).toEqual(expected);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// ─── isUntyped ──────────────────────────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
describe('GIVEN "jsx-ref-type-match" / isUntyped', () => {
|
|
90
|
+
it.each([
|
|
91
|
+
[['any'], true], // ref()
|
|
92
|
+
[['unknown'], true],
|
|
93
|
+
[['null'], true], // ref(null)
|
|
94
|
+
[['undefined'], true],
|
|
95
|
+
[['null', 'undefined'], true],
|
|
96
|
+
[['void'], true],
|
|
97
|
+
[['HTMLDivElement'], false], // ref<HTMLDivElement>() unwrapped
|
|
98
|
+
[['HTMLDivElement', 'undefined'], false],
|
|
99
|
+
[['BaseInput', 'null'], false],
|
|
100
|
+
[['string'], false],
|
|
101
|
+
[['anything'], false], // the name must match exactly
|
|
102
|
+
])('THEN %j → %s', (names, expected) => {
|
|
103
|
+
expect(isUntyped(type(...names), checker)).toBe(expected);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// ─── isAnyOrUnknown ─────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
describe('GIVEN "jsx-ref-type-match" / isAnyOrUnknown', () => {
|
|
110
|
+
it.each([
|
|
111
|
+
['any', true],
|
|
112
|
+
['unknown', true],
|
|
113
|
+
['null', false],
|
|
114
|
+
['VDropdown', false],
|
|
115
|
+
])('THEN %s → %s', (name, expected) => {
|
|
116
|
+
expect(isAnyOrUnknown(single(name), checker)).toBe(expected);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
1
4
|
import {
|
|
2
|
-
getKeyName, getWholeContextUsage, isComponentFileName, isComposableFile, isUsed, stripComments, usesWholeContext,
|
|
5
|
+
getKeyName, getWholeContextUsage, isComponentFileName, isComposableFile, isImportedElsewhere, isPublicComment, readImportedRenders, isUsed, stripComments, usesWholeContext,
|
|
3
6
|
} from '../src/no-unused-setup-return';
|
|
4
7
|
|
|
5
8
|
describe('GIVEN "no-unused-setup-return" / isComposableFile', () => {
|
|
@@ -69,6 +72,7 @@ describe('GIVEN "no-unused-setup-return" / getWholeContextUsage', () => {
|
|
|
69
72
|
['export default function (c: Foo) { return <A>{render(c)}</A>; }', { spread: false, callees: ['render'] }],
|
|
70
73
|
['export default function (c: Foo) { return <A>{f(value, row, c)}</A>; }', { spread: false, callees: ['f'] }],
|
|
71
74
|
['export default function (c: Foo) { return <A v={c.a} />; }', { spread: false, callees: [] }],
|
|
75
|
+
['export default function (c: Foo) { return <A {...c.$attrs} {...c?.b} {...c[k]} />; }', { spread: false, callees: [] }],
|
|
72
76
|
])('THEN %s → %j', (text, expected) => {
|
|
73
77
|
expect(getWholeContextUsage(text)).toEqual(expected);
|
|
74
78
|
});
|
|
@@ -86,3 +90,63 @@ describe('GIVEN "no-unused-setup-return" / isComponentFileName', () => {
|
|
|
86
90
|
expect(isComponentFileName(file)).toBe(expected);
|
|
87
91
|
});
|
|
88
92
|
});
|
|
93
|
+
|
|
94
|
+
describe('GIVEN "no-unused-setup-return" / isImportedElsewhere', () => {
|
|
95
|
+
let dir;
|
|
96
|
+
beforeAll(() => {
|
|
97
|
+
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nusr-'));
|
|
98
|
+
const w = (f, t) => { fs.mkdirSync(path.dirname(path.join(dir, f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), t); };
|
|
99
|
+
w('package.json', '{}');
|
|
100
|
+
w('src/a/useA.ts', 'export default () => ({})');
|
|
101
|
+
w('src/a/A.ts', "import setup from './useA';");
|
|
102
|
+
w('src/b/B.ts', "import useA from '../a/useA';");
|
|
103
|
+
w('src/c/useC.ts', 'export default () => ({})');
|
|
104
|
+
w('src/c/C.ts', "import setup from './useC';");
|
|
105
|
+
w('src/d/useD.ts', 'export default () => ({})');
|
|
106
|
+
w('src/e/E.ts', "import useD from '../x/useD';");
|
|
107
|
+
});
|
|
108
|
+
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
109
|
+
|
|
110
|
+
it('THEN imported by another directory → true', () => {
|
|
111
|
+
expect(isImportedElsewhere(path.join(dir, 'src/a/useA.ts'))).toBe(true);
|
|
112
|
+
});
|
|
113
|
+
it('THEN imported only by its own directory → false', () => {
|
|
114
|
+
expect(isImportedElsewhere(path.join(dir, 'src/c/useC.ts'))).toBe(false);
|
|
115
|
+
});
|
|
116
|
+
it('THEN a relative import resolving elsewhere is ignored → false', () => {
|
|
117
|
+
expect(isImportedElsewhere(path.join(dir, 'src/d/useD.ts'))).toBe(false);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe('GIVEN "no-unused-setup-return" / readImportedRenders', () => {
|
|
122
|
+
it('THEN reads a shared render of the parent directory', () => {
|
|
123
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nusr-r-'));
|
|
124
|
+
fs.mkdirSync(path.join(dir, 'child'));
|
|
125
|
+
fs.writeFileSync(path.join(dir, 'useShared.tsx'), '// c.nope\nexport default (c) => c.formTitle;');
|
|
126
|
+
const texts = readImportedRenders("import render from '../useShared';\nimport other from './x';", path.join(dir, 'child'));
|
|
127
|
+
expect(texts).toHaveLength(1);
|
|
128
|
+
expect(isUsed('formTitle', texts)).toBe(true);
|
|
129
|
+
expect(isUsed('nope', texts)).toBe(false);
|
|
130
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('THEN an alias import is ignored', () => {
|
|
134
|
+
expect(readImportedRenders("import render from '@/x/render';", '/tmp')).toEqual([]);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
describe('GIVEN "no-unused-setup-return" / isPublicComment', () => {
|
|
139
|
+
it.each([
|
|
140
|
+
// comment values, as given by ESLint (without the delimiters)
|
|
141
|
+
['* @public ', true], // /** @public */
|
|
142
|
+
[' @public', true], // // @public
|
|
143
|
+
[' @public called by the parent', true],
|
|
144
|
+
['*\n * Focus the input\n * @public\n ', true], // multi-line JSDoc
|
|
145
|
+
[' public', false],
|
|
146
|
+
[' @publicApi', false],
|
|
147
|
+
[' not @public-ish', false],
|
|
148
|
+
[' foo@public', false],
|
|
149
|
+
])('THEN %j → %s', (text, expected) => {
|
|
150
|
+
expect(isPublicComment(text)).toBe(expected);
|
|
151
|
+
});
|
|
152
|
+
});
|