@tcy/eslint-rules 1.9.2 → 1.10.0-beta.2

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 (43) hide show
  1. package/README.md +540 -6
  2. package/coverage/clover.xml +93 -4
  3. package/coverage/coverage-final.json +1 -0
  4. package/coverage/lcov-report/index.html +19 -19
  5. package/coverage/lcov-report/src/array-elements-per-line.js.html +1 -1
  6. package/coverage/lcov-report/src/back/back.js.html +5 -2
  7. package/coverage/lcov-report/src/back/http.js.html +1 -1
  8. package/coverage/lcov-report/src/back/index.html +1 -1
  9. package/coverage/lcov-report/src/back/recommended.js.html +1 -1
  10. package/coverage/lcov-report/src/bin/eslint-cache-guard.js.html +1 -1
  11. package/coverage/lcov-report/src/bin/index.html +1 -1
  12. package/coverage/lcov-report/src/client/client.js.html +5 -2
  13. package/coverage/lcov-report/src/client/index.html +1 -1
  14. package/coverage/lcov-report/src/client/recommended.js.html +1 -1
  15. package/coverage/lcov-report/src/consistent-const-scoping.js.html +928 -0
  16. package/coverage/lcov-report/src/decorator-type-enforcement.js.html +1 -1
  17. package/coverage/lcov-report/src/enforce-tailwind-important.js.html +1 -1
  18. package/coverage/lcov-report/src/export-specifiers-per-line.js.html +1 -1
  19. package/coverage/lcov-report/src/import-specifiers-per-line.js.html +1 -1
  20. package/coverage/lcov-report/src/index.html +24 -9
  21. package/coverage/lcov-report/src/index.js.html +1 -1
  22. package/coverage/lcov-report/src/jsx-boolean-shorthand.js.html +1 -1
  23. package/coverage/lcov-report/src/jsx-expression-string-literals.js.html +1 -1
  24. package/coverage/lcov-report/src/jsx-ref-string-exists.js.html +1 -1
  25. package/coverage/lcov-report/src/no-static-key-in-map.js.html +1 -1
  26. package/coverage/lcov-report/src/plugin.js.html +8 -2
  27. package/coverage/lcov-report/src/recommended.js.html +1 -1
  28. package/coverage/lcov-report/src/require-fragment-key.js.html +1 -1
  29. package/coverage/lcov-report/src/route-dto-required.js.html +1 -1
  30. package/coverage/lcov-report/src/v-model-name-match.js.html +1 -1
  31. package/coverage/lcov-report/src/vuejs-define-component.js.html +1 -1
  32. package/coverage/lcov-report/src/vuejs-define-workspace.js.html +1 -1
  33. package/coverage/lcov.info +264 -0
  34. package/decl/back/back.d.ts +30 -0
  35. package/decl/client/client.d.ts +30 -0
  36. package/decl/consistent-const-scoping.d.ts +99 -0
  37. package/decl/plugin.d.ts +29 -0
  38. package/package.json +6 -6
  39. package/src/back/back.js +1 -0
  40. package/src/client/client.js +1 -0
  41. package/src/consistent-const-scoping.js +281 -0
  42. package/src/plugin.js +2 -0
  43. package/tests/consistent-const-scoping.spec.js +102 -0
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @fileoverview consistent-const-scoping
3
+ *
4
+ * Reports a `const` declared inside a function when its initializer does not
5
+ * depend on anything from that function (or any function nesting it) — no
6
+ * parameter, no local variable, no `this` / `super` / `arguments`:
7
+ *
8
+ * function makeGreeter() {
9
+ * const hello = () => console.log('hello'); // ✗ recreated every call
10
+ * return { hello };
11
+ * }
12
+ *
13
+ * // ✓
14
+ * const hello = () => console.log('hello');
15
+ * function makeGreeter() {
16
+ * return { hello };
17
+ * }
18
+ *
19
+ * A value with no runtime input to the function is identical on every call,
20
+ * so declaring it inside the function just rebuilds the same thing each
21
+ * time for no benefit and buries a module-level concern inside call-time
22
+ * code.
23
+ *
24
+ * Only a *pure* initializer is flagged — a literal, a template literal /
25
+ * array / object built from pure values, or a function / arrow expression.
26
+ * A `CallExpression`, `NewExpression`, `await`, `yield`, tagged template, or
27
+ * any other expression that can run a side effect or produce a different
28
+ * result depending on *when* it runs is deliberately left alone: unlike a
29
+ * function definition (which does not execute until called), moving one of
30
+ * those changes it from running once per call to running once at module
31
+ * load — that is a behavior change, not just a relocation, and this rule
32
+ * never suggests it.
33
+ *
34
+ * It stays silent when:
35
+ *
36
+ * - the `const` is already at module scope — nothing to hoist past
37
+ * - the id is a destructuring pattern (`const { a } = …`) — out of scope
38
+ * for this rule
39
+ * - the initializer reads a parameter, an outer local, `this`, `super`,
40
+ * or `arguments` — moving it would change what it reads
41
+ * - the initializer is not provably side-effect-free (see above)
42
+ *
43
+ * Which *shape* of initializer gets flagged is configurable via the `types`
44
+ * option, so different parts of a codebase can opt into different strictness
45
+ * levels (e.g. only arrow functions in most folders, arrow functions +
46
+ * primitives in a folder that wants to be stricter):
47
+ *
48
+ * 'consistent-const-scoping': ['error', { types: ['arrow-function', 'primitive'] }]
49
+ *
50
+ * Recognized values: 'primitive', 'template-literal', 'expression' (identifier /
51
+ * unary / binary / logical / conditional / member access), 'array', 'object',
52
+ * 'arrow-function', 'function-expression'. Defaults to `['arrow-function']`.
53
+ */
54
+ /** All initializer categories the `types` option can select. */
55
+ export declare const ALL_INIT_TYPES: string[];
56
+ export declare const DEFAULT_INIT_TYPES: string[];
57
+ /**
58
+ * Which `types` category a (already known-pure) initializer belongs to, after
59
+ * unwrapping the same `as` / `!` / `satisfies` / parens wrappers the purity
60
+ * check sees through. `null` for a node that isn't a recognized initializer
61
+ * shape at all.
62
+ */
63
+ export declare const classifyInit: (node: any) => any;
64
+ /** Build the set of enabled initializer categories from the rule options. */
65
+ export declare const resolveInitTypes: (options: any) => Set<any>;
66
+ /** A value that evaluates the same way, with no side effects, wherever it runs. */
67
+ export declare const isPureExpression: (node: any) => any;
68
+ /** Does `node` contain a `this` / `super` that would resolve outside of it (through arrow boundaries only)? */
69
+ export declare const containsBlockingThis: (node: any) => any;
70
+ declare const _default: {
71
+ meta: {
72
+ type: string;
73
+ docs: {
74
+ description: string;
75
+ recommended: boolean;
76
+ };
77
+ schema: {
78
+ type: string;
79
+ properties: {
80
+ types: {
81
+ type: string;
82
+ items: {
83
+ enum: string[];
84
+ };
85
+ uniqueItems: boolean;
86
+ default: string[];
87
+ };
88
+ };
89
+ additionalProperties: boolean;
90
+ }[];
91
+ messages: {
92
+ hoistable: string;
93
+ };
94
+ };
95
+ create(context: any): {
96
+ VariableDeclarator(node: any): void;
97
+ };
98
+ };
99
+ export default _default;
package/decl/plugin.d.ts CHANGED
@@ -243,5 +243,34 @@ declare const _default: {
243
243
  JSXElement: (node: any) => void;
244
244
  };
245
245
  };
246
+ 'consistent-const-scoping': {
247
+ meta: {
248
+ type: string;
249
+ docs: {
250
+ description: string;
251
+ recommended: boolean;
252
+ };
253
+ schema: {
254
+ type: string;
255
+ properties: {
256
+ types: {
257
+ type: string;
258
+ items: {
259
+ enum: string[];
260
+ };
261
+ uniqueItems: boolean;
262
+ default: string[];
263
+ };
264
+ };
265
+ additionalProperties: boolean;
266
+ }[];
267
+ messages: {
268
+ hoistable: string;
269
+ };
270
+ };
271
+ create(context: any): {
272
+ VariableDeclarator(node: any): void;
273
+ };
274
+ };
246
275
  };
247
276
  export default _default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tcy/eslint-rules",
3
- "version": "1.9.2",
3
+ "version": "1.10.0-beta.2",
4
4
  "description": "```typescript import { plugin as customRules } from 'tcy@eslint-rules/src/index.mjs';",
5
5
  "homepage": "https://github.com/tcastelly/eslint-rules#readme",
6
6
  "bugs": {
@@ -47,12 +47,12 @@
47
47
  "test": "jest"
48
48
  },
49
49
  "devDependencies": {
50
- "@babel/core": "^8.0.5",
51
- "@babel/preset-env": "^8.0.5",
50
+ "@babel/core": "^8.0.6",
51
+ "@babel/preset-env": "^8.0.6",
52
52
  "@types/jest": "^30.0.0",
53
- "@types/node": "^26.5.0",
54
- "babel-jest": "^30.5.1",
55
- "jest": "^30.5.1",
53
+ "@types/node": "^26.6.2",
54
+ "babel-jest": "^30.5.2",
55
+ "jest": "^30.5.2",
56
56
  "rimraf": "^6.1.3",
57
57
  "typescript": "^7.0.2"
58
58
  }
package/src/back/back.js CHANGED
@@ -11,5 +11,6 @@ export default {
11
11
  'tcy/export-specifiers-per-line': 'error',
12
12
  'tcy/array-elements-per-line': 'error',
13
13
  'tcy/route-dto-required': 'error',
14
+ 'tcy/consistent-const-scoping': 'error',
14
15
  }
15
16
  }
@@ -20,5 +20,6 @@ export default {
20
20
  'tcy/vuejs-define-workspace': 'error',
21
21
  'tcy/require-fragment-key': 'error',
22
22
  'tcy/no-static-key-in-map': 'error',
23
+ 'tcy/consistent-const-scoping': 'error',
23
24
  }
24
25
  }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * @fileoverview consistent-const-scoping
3
+ *
4
+ * Reports a `const` declared inside a function when its initializer does not
5
+ * depend on anything from that function (or any function nesting it) — no
6
+ * parameter, no local variable, no `this` / `super` / `arguments`:
7
+ *
8
+ * function makeGreeter() {
9
+ * const hello = () => console.log('hello'); // ✗ recreated every call
10
+ * return { hello };
11
+ * }
12
+ *
13
+ * // ✓
14
+ * const hello = () => console.log('hello');
15
+ * function makeGreeter() {
16
+ * return { hello };
17
+ * }
18
+ *
19
+ * A value with no runtime input to the function is identical on every call,
20
+ * so declaring it inside the function just rebuilds the same thing each
21
+ * time for no benefit and buries a module-level concern inside call-time
22
+ * code.
23
+ *
24
+ * Only a *pure* initializer is flagged — a literal, a template literal /
25
+ * array / object built from pure values, or a function / arrow expression.
26
+ * A `CallExpression`, `NewExpression`, `await`, `yield`, tagged template, or
27
+ * any other expression that can run a side effect or produce a different
28
+ * result depending on *when* it runs is deliberately left alone: unlike a
29
+ * function definition (which does not execute until called), moving one of
30
+ * those changes it from running once per call to running once at module
31
+ * load — that is a behavior change, not just a relocation, and this rule
32
+ * never suggests it.
33
+ *
34
+ * It stays silent when:
35
+ *
36
+ * - the `const` is already at module scope — nothing to hoist past
37
+ * - the id is a destructuring pattern (`const { a } = …`) — out of scope
38
+ * for this rule
39
+ * - the initializer reads a parameter, an outer local, `this`, `super`,
40
+ * or `arguments` — moving it would change what it reads
41
+ * - the initializer is not provably side-effect-free (see above)
42
+ *
43
+ * Which *shape* of initializer gets flagged is configurable via the `types`
44
+ * option, so different parts of a codebase can opt into different strictness
45
+ * levels (e.g. only arrow functions in most folders, arrow functions +
46
+ * primitives in a folder that wants to be stricter):
47
+ *
48
+ * 'consistent-const-scoping': ['error', { types: ['arrow-function', 'primitive'] }]
49
+ *
50
+ * Recognized values: 'primitive', 'template-literal', 'expression' (identifier /
51
+ * unary / binary / logical / conditional / member access), 'array', 'object',
52
+ * 'arrow-function', 'function-expression'. Defaults to `['arrow-function']`.
53
+ */
54
+
55
+ const LITERAL_TYPES = new Set([
56
+ 'Literal', // espree: string / number / boolean / null / regex
57
+ 'StringLiteral', // @babel/parser
58
+ 'NumericLiteral',
59
+ 'BooleanLiteral',
60
+ 'BigIntLiteral',
61
+ 'NullLiteral',
62
+ 'RegExpLiteral',
63
+ ]);
64
+
65
+ const UNWRAP_TYPES = new Set([
66
+ 'ParenthesizedExpression',
67
+ 'TSAsExpression',
68
+ 'TSNonNullExpression',
69
+ 'TSSatisfiesExpression',
70
+ ]);
71
+
72
+ const FUNCTION_TYPES = new Set(['FunctionExpression', 'ArrowFunctionExpression']);
73
+
74
+ /** All initializer categories the `types` option can select. */
75
+ export const ALL_INIT_TYPES = [
76
+ 'primitive',
77
+ 'template-literal',
78
+ 'expression',
79
+ 'array',
80
+ 'object',
81
+ 'arrow-function',
82
+ 'function-expression',
83
+ ];
84
+
85
+ export const DEFAULT_INIT_TYPES = ['arrow-function'];
86
+
87
+ const CATEGORY_BY_TYPE = {
88
+ ArrowFunctionExpression: 'arrow-function',
89
+ FunctionExpression: 'function-expression',
90
+ ArrayExpression: 'array',
91
+ ObjectExpression: 'object',
92
+ TemplateLiteral: 'template-literal',
93
+ };
94
+
95
+ const unwrap = (node) => (node && UNWRAP_TYPES.has(node.type) ? unwrap(node.expression) : node);
96
+
97
+ /**
98
+ * Which `types` category a (already known-pure) initializer belongs to, after
99
+ * unwrapping the same `as` / `!` / `satisfies` / parens wrappers the purity
100
+ * check sees through. `null` for a node that isn't a recognized initializer
101
+ * shape at all.
102
+ */
103
+ export const classifyInit = (node) => {
104
+ const inner = unwrap(node);
105
+ if (!inner) return null;
106
+ if (LITERAL_TYPES.has(inner.type)) return 'primitive';
107
+ if (CATEGORY_BY_TYPE[inner.type]) return CATEGORY_BY_TYPE[inner.type];
108
+ if (
109
+ inner.type === 'Identifier'
110
+ || inner.type === 'UnaryExpression'
111
+ || inner.type === 'BinaryExpression'
112
+ || inner.type === 'LogicalExpression'
113
+ || inner.type === 'ConditionalExpression'
114
+ || inner.type === 'MemberExpression'
115
+ || inner.type === 'OptionalMemberExpression'
116
+ ) return 'expression';
117
+ return null;
118
+ };
119
+
120
+ /** Build the set of enabled initializer categories from the rule options. */
121
+ export const resolveInitTypes = (options) => new Set((options && options.types) || DEFAULT_INIT_TYPES);
122
+
123
+ /** A value that evaluates the same way, with no side effects, wherever it runs. */
124
+ export const isPureExpression = (node) => {
125
+ if (!node) return false;
126
+ if (node.type === 'ThisExpression' || node.type === 'Super') return false;
127
+ if (LITERAL_TYPES.has(node.type)) return true;
128
+ if (UNWRAP_TYPES.has(node.type)) return isPureExpression(node.expression);
129
+ if (FUNCTION_TYPES.has(node.type)) return true;
130
+ if (node.type === 'Identifier') return true;
131
+ if (node.type === 'TemplateLiteral') return node.expressions.every(isPureExpression);
132
+
133
+ if (node.type === 'UnaryExpression') {
134
+ return node.operator !== 'delete' && isPureExpression(node.argument);
135
+ }
136
+ if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression') {
137
+ return isPureExpression(node.left) && isPureExpression(node.right);
138
+ }
139
+ if (node.type === 'ConditionalExpression') {
140
+ return isPureExpression(node.test)
141
+ && isPureExpression(node.consequent)
142
+ && isPureExpression(node.alternate);
143
+ }
144
+ if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
145
+ return isPureExpression(node.object) && (!node.computed || isPureExpression(node.property));
146
+ }
147
+ if (node.type === 'ArrayExpression') {
148
+ return node.elements.every((el) => {
149
+ if (el === null) return true;
150
+ if (el.type === 'SpreadElement') return isPureExpression(el.argument);
151
+ return isPureExpression(el);
152
+ });
153
+ }
154
+ if (node.type === 'ObjectExpression') {
155
+ return node.properties.every((prop) => {
156
+ if (prop.type === 'SpreadElement') return isPureExpression(prop.argument);
157
+ if (prop.computed && !isPureExpression(prop.key)) return false;
158
+ return isPureExpression(prop.value);
159
+ });
160
+ }
161
+
162
+ return false;
163
+ };
164
+
165
+ /** Types that bind their own `this` — a `this` / `super` past this point belongs to them, not the const's init. */
166
+ const THIS_BOUNDARY_TYPES = new Set([
167
+ 'FunctionDeclaration',
168
+ 'FunctionExpression',
169
+ 'ClassDeclaration',
170
+ 'ClassExpression',
171
+ ]);
172
+
173
+ /** Does `node` contain a `this` / `super` that would resolve outside of it (through arrow boundaries only)? */
174
+ export const containsBlockingThis = (node) => {
175
+ if (!node || typeof node.type !== 'string') return false;
176
+ if (node.type === 'ThisExpression' || node.type === 'Super') return true;
177
+ if (THIS_BOUNDARY_TYPES.has(node.type)) return false;
178
+
179
+ return Object.keys(node).some((key) => {
180
+ if (key === 'parent') return false;
181
+ const value = node[key];
182
+ if (Array.isArray(value)) {
183
+ return value.some((child) => child && typeof child.type === 'string' && containsBlockingThis(child));
184
+ }
185
+ return !!value && typeof value.type === 'string' && containsBlockingThis(value);
186
+ });
187
+ };
188
+
189
+ const describeFunction = (fnNode) => {
190
+ if (fnNode.id?.name) return fnNode.id.name;
191
+ const { parent } = fnNode;
192
+ if (parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier') return parent.id.name;
193
+ if (parent?.type === 'Property' && parent.key.type === 'Identifier') return parent.key.name;
194
+ return '(anonymous function)';
195
+ };
196
+
197
+ export default {
198
+ meta: {
199
+ type: 'suggestion',
200
+ docs: {
201
+ description:
202
+ 'Disallow a `const` inside a function when its (side-effect-free) value does not '
203
+ + 'depend on that function\'s parameters, locals, `this`, or `arguments` — declare it '
204
+ + 'outside so it is not rebuilt on every call.',
205
+ recommended: false,
206
+ },
207
+ schema: [
208
+ {
209
+ type: 'object',
210
+ properties: {
211
+ types: {
212
+ type: 'array',
213
+ items: { enum: ALL_INIT_TYPES },
214
+ uniqueItems: true,
215
+ default: DEFAULT_INIT_TYPES,
216
+ },
217
+ },
218
+ additionalProperties: false,
219
+ },
220
+ ],
221
+ messages: {
222
+ hoistable:
223
+ '`{{name}}` does not depend on anything from `{{fnName}}`\'s scope — declare it '
224
+ + 'outside the function so it is not rebuilt on every call.',
225
+ },
226
+ },
227
+
228
+ create(context) {
229
+ const { sourceCode } = context;
230
+ const enabledTypes = resolveInitTypes(context.options[0]);
231
+
232
+ /** Every scope from `node` up to (excluding) module/global scope, or `null` if none is a function. */
233
+ const blockingChain = (node) => {
234
+ const chain = [];
235
+ let scope = sourceCode.getScope(node);
236
+ let hasFunctionAncestor = false;
237
+
238
+ while (scope && scope.type !== 'global' && scope.type !== 'module') {
239
+ chain.push(scope);
240
+ if (scope.type === 'function') hasFunctionAncestor = true;
241
+ scope = scope.upper;
242
+ }
243
+
244
+ return hasFunctionAncestor ? chain : null;
245
+ };
246
+
247
+ const isReferencedIn = (chain, range) => chain.some((scope) => scope.variables.some(
248
+ (variable) => variable.references.some(
249
+ (ref) => ref.identifier.range[0] >= range[0] && ref.identifier.range[1] <= range[1],
250
+ ),
251
+ ));
252
+
253
+ const nearestFunctionScope = (chain) => chain.find((scope) => scope.type === 'function');
254
+
255
+ return {
256
+ VariableDeclarator(node) {
257
+ if (node.parent.type !== 'VariableDeclaration' || node.parent.kind !== 'const') return;
258
+ if (node.id.type !== 'Identifier' || !node.init) return;
259
+
260
+ const chain = blockingChain(node);
261
+ if (!chain) return; // already at module scope
262
+
263
+ if (!isPureExpression(node.init)) return;
264
+ if (containsBlockingThis(node.init)) return;
265
+ if (isReferencedIn(chain, node.init.range)) return;
266
+ if (!enabledTypes.has(classifyInit(node.init))) return;
267
+
268
+ const fnScope = nearestFunctionScope(chain);
269
+
270
+ context.report({
271
+ node,
272
+ messageId: 'hoistable',
273
+ data: {
274
+ name: node.id.name,
275
+ fnName: describeFunction(fnScope.block),
276
+ },
277
+ });
278
+ },
279
+ };
280
+ },
281
+ };
package/src/plugin.js CHANGED
@@ -12,6 +12,7 @@ import vuejsDefineWorkspace from './vuejs-define-workspace.js'
12
12
  import routeDtoRequired from './route-dto-required.js'
13
13
  import requireFragmentKey from './require-fragment-key.js'
14
14
  import noStaticKeyInMap from './no-static-key-in-map.js'
15
+ import consistentConstScoping from './consistent-const-scoping.js'
15
16
 
16
17
  export default {
17
18
  'import-specifiers-per-line': importSpecifiersPerLineRule,
@@ -28,4 +29,5 @@ export default {
28
29
  'route-dto-required': routeDtoRequired,
29
30
  'require-fragment-key': requireFragmentKey,
30
31
  'no-static-key-in-map': noStaticKeyInMap,
32
+ 'consistent-const-scoping': consistentConstScoping,
31
33
  }
@@ -0,0 +1,102 @@
1
+ import { parse } from '@babel/parser';
2
+ import {
3
+ classifyInit,
4
+ containsBlockingThis,
5
+ DEFAULT_INIT_TYPES,
6
+ isPureExpression,
7
+ resolveInitTypes,
8
+ } from '../src/consistent-const-scoping';
9
+
10
+ // ─── isPureExpression ───────────────────────────────────────────────────────
11
+
12
+ describe('GIVEN "consistent-const-scoping" / isPureExpression', () => {
13
+ const expr = (code) => parse(`(${code})`, { plugins: ['typescript'] }).program.body[0].expression;
14
+
15
+ it.each([
16
+ ['"hello"', true],
17
+ ['42', true],
18
+ ['/foo/g', true],
19
+ ['`hello`', true],
20
+ ['() => console.log("hi")', true],
21
+ ['function () { return 1; }', true],
22
+ ['{ a: 1, b: [1, 2, "x"] }', true],
23
+ ['[1, 2, 3]', true],
24
+ ['a.b.c', true],
25
+ ['1 + 2', true],
26
+ ['a ? 1 : 2', true],
27
+ ['console.log("hi")', false],
28
+ ['new Date()', false],
29
+ ['Math.random()', false],
30
+ ['`hello ${getName()}`', false],
31
+ ['this.value', false],
32
+ ['[foo()]', false],
33
+ ['{ a: foo() }', false],
34
+ ])('THEN %s → pure:%s', (code, pure) => {
35
+ expect(isPureExpression(expr(code))).toBe(pure);
36
+ });
37
+ });
38
+
39
+ // ─── containsBlockingThis ───────────────────────────────────────────────────
40
+
41
+ describe('GIVEN "consistent-const-scoping" / containsBlockingThis', () => {
42
+ const expr = (code) => parse(`(${code})`, { plugins: ['typescript'] }).program.body[0].expression;
43
+
44
+ it('THEN a bare `this` is blocking', () => {
45
+ expect(containsBlockingThis(expr('this.value'))).toBe(true);
46
+ });
47
+
48
+ it('THEN `this` inside an arrow (inherited) is blocking', () => {
49
+ expect(containsBlockingThis(expr('() => this.value'))).toBe(true);
50
+ });
51
+
52
+ it('THEN `this` inside a nested function (own binding) is NOT blocking', () => {
53
+ expect(containsBlockingThis(expr('function () { return this.value; }'))).toBe(false);
54
+ });
55
+
56
+ it('THEN no `this` at all is not blocking', () => {
57
+ expect(containsBlockingThis(expr('() => 42'))).toBe(false);
58
+ });
59
+ });
60
+
61
+ // ─── classifyInit ───────────────────────────────────────────────────────────
62
+
63
+ describe('GIVEN "consistent-const-scoping" / classifyInit', () => {
64
+ const expr = (code) => parse(`(${code})`, { plugins: ['typescript'] }).program.body[0].expression;
65
+
66
+ it.each([
67
+ ['"hello"', 'primitive'],
68
+ ['42', 'primitive'],
69
+ ['/foo/g', 'primitive'],
70
+ ['`hello`', 'template-literal'],
71
+ ['() => 1', 'arrow-function'],
72
+ ['function () { return 1; }', 'function-expression'],
73
+ ['[1, 2, 3]', 'array'],
74
+ ['{ a: 1 }', 'object'],
75
+ ['a', 'expression'],
76
+ ['a.b.c', 'expression'],
77
+ ['1 + 2', 'expression'],
78
+ ['a ? 1 : 2', 'expression'],
79
+ ])('THEN %s → %s', (code, category) => {
80
+ expect(classifyInit(expr(code))).toBe(category);
81
+ });
82
+
83
+ it('THEN it unwraps `as` / `!` / `satisfies` / parens before classifying', () => {
84
+ expect(classifyInit(expr('(() => 1) as unknown'))).toBe('arrow-function');
85
+ expect(classifyInit(expr('(1)!'))).toBe('primitive');
86
+ expect(classifyInit(expr('({ a: 1 } satisfies unknown)'))).toBe('object');
87
+ });
88
+ });
89
+
90
+ // ─── resolveInitTypes ───────────────────────────────────────────────────────
91
+
92
+ describe('GIVEN "consistent-const-scoping" / resolveInitTypes', () => {
93
+ it('THEN it defaults to arrow-function only', () => {
94
+ expect(resolveInitTypes()).toEqual(new Set(DEFAULT_INIT_TYPES));
95
+ expect(resolveInitTypes(undefined)).toEqual(new Set(['arrow-function']));
96
+ });
97
+
98
+ it('THEN an explicit "types" option overrides the default', () => {
99
+ expect(resolveInitTypes({ types: ['arrow-function', 'primitive'] }))
100
+ .toEqual(new Set(['arrow-function', 'primitive']));
101
+ });
102
+ });