@kikiutils/eslint-config 11.5.0 → 12.0.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.
Files changed (112) hide show
  1. package/README.md +41 -23
  2. package/dist/_internals/configs/base-rules.d.ts.map +1 -1
  3. package/dist/_internals/configs/base-rules.js +38 -37
  4. package/dist/_internals/configs/base-rules.js.map +1 -1
  5. package/dist/_internals/configs/jsdoc.d.ts +0 -36
  6. package/dist/_internals/configs/jsdoc.d.ts.map +1 -1
  7. package/dist/_internals/configs/jsdoc.js +1 -42
  8. package/dist/_internals/configs/jsdoc.js.map +1 -1
  9. package/dist/_internals/configs/type-aware.d.ts.map +1 -1
  10. package/dist/_internals/configs/type-aware.js +26 -1
  11. package/dist/_internals/configs/type-aware.js.map +1 -1
  12. package/dist/_internals/configs/typescript.d.ts +42 -0
  13. package/dist/_internals/configs/typescript.d.ts.map +1 -0
  14. package/dist/_internals/configs/typescript.js +49 -0
  15. package/dist/_internals/configs/typescript.js.map +1 -0
  16. package/dist/_internals/eslint-plugin-promise.d.ts +7 -0
  17. package/dist/_internals/eslint-plugin-promise.d.ts.map +1 -0
  18. package/dist/_internals/rules/consistent-condition-layout.d.ts.map +1 -1
  19. package/dist/_internals/rules/consistent-condition-layout.js +15 -14
  20. package/dist/_internals/rules/consistent-condition-layout.js.map +1 -1
  21. package/dist/_internals/rules/consistent-parameter-layout.d.ts.map +1 -1
  22. package/dist/_internals/rules/consistent-parameter-layout.js +17 -11
  23. package/dist/_internals/rules/consistent-parameter-layout.js.map +1 -1
  24. package/dist/_internals/rules/index.d.ts +7 -1
  25. package/dist/_internals/rules/index.d.ts.map +1 -1
  26. package/dist/_internals/rules/index.js +11 -2
  27. package/dist/_internals/rules/index.js.map +1 -1
  28. package/dist/_internals/rules/no-composable-in-head-getter.d.ts.map +1 -1
  29. package/dist/_internals/rules/no-composable-in-head-getter.js +97 -19
  30. package/dist/_internals/rules/no-composable-in-head-getter.js.map +1 -1
  31. package/dist/_internals/rules/no-reactive-composable-return.d.ts +3 -0
  32. package/dist/_internals/rules/no-reactive-composable-return.d.ts.map +1 -0
  33. package/dist/_internals/rules/no-reactive-composable-return.js +43 -0
  34. package/dist/_internals/rules/no-reactive-composable-return.js.map +1 -0
  35. package/dist/_internals/rules/no-reactive-destructure.d.ts +3 -0
  36. package/dist/_internals/rules/no-reactive-destructure.d.ts.map +1 -0
  37. package/dist/_internals/rules/no-reactive-destructure.js +44 -0
  38. package/dist/_internals/rules/no-reactive-destructure.js.map +1 -0
  39. package/dist/_internals/rules/no-silent-catch.d.ts.map +1 -1
  40. package/dist/_internals/rules/no-silent-catch.js +3 -2
  41. package/dist/_internals/rules/no-silent-catch.js.map +1 -1
  42. package/dist/_internals/rules/no-thenable-zod-refinement.d.ts.map +1 -1
  43. package/dist/_internals/rules/no-thenable-zod-refinement.js +9 -3
  44. package/dist/_internals/rules/no-thenable-zod-refinement.js.map +1 -1
  45. package/dist/_internals/rules/prefer-enhanced-date.d.ts +3 -0
  46. package/dist/_internals/rules/prefer-enhanced-date.d.ts.map +1 -0
  47. package/dist/_internals/rules/prefer-enhanced-date.js +307 -0
  48. package/dist/_internals/rules/prefer-enhanced-date.js.map +1 -0
  49. package/dist/_internals/rules/promise-function-async.d.ts.map +1 -1
  50. package/dist/_internals/rules/promise-function-async.js.map +1 -1
  51. package/dist/_internals/rules/statement-padding.d.ts.map +1 -1
  52. package/dist/_internals/rules/statement-padding.js +19 -15
  53. package/dist/_internals/rules/statement-padding.js.map +1 -1
  54. package/dist/_internals/rules/utils.d.ts +23 -0
  55. package/dist/_internals/rules/utils.d.ts.map +1 -0
  56. package/dist/_internals/rules/utils.js +17 -0
  57. package/dist/_internals/rules/utils.js.map +1 -0
  58. package/dist/_internals/rules/vue-reactivity.d.ts +3 -0
  59. package/dist/_internals/rules/vue-reactivity.d.ts.map +1 -0
  60. package/dist/_internals/rules/vue-reactivity.js +30 -0
  61. package/dist/_internals/rules/vue-reactivity.js.map +1 -0
  62. package/dist/base.d.ts.map +1 -1
  63. package/dist/base.js +51 -29
  64. package/dist/base.js.map +1 -1
  65. package/dist/nuxt.d.ts +3 -1
  66. package/dist/nuxt.d.ts.map +1 -1
  67. package/dist/nuxt.js +53 -3
  68. package/dist/nuxt.js.map +1 -1
  69. package/dist/style.d.ts.map +1 -1
  70. package/dist/style.js +1 -0
  71. package/dist/style.js.map +1 -1
  72. package/dist/vue.d.ts +1 -1
  73. package/dist/vue.d.ts.map +1 -1
  74. package/dist/vue.js +17 -19
  75. package/dist/vue.js.map +1 -1
  76. package/package.json +6 -5
  77. package/src/_internals/configs/base-rules.ts +30 -44
  78. package/src/_internals/configs/jsdoc.ts +0 -51
  79. package/src/_internals/configs/type-aware.ts +29 -1
  80. package/src/_internals/configs/typescript.ts +62 -0
  81. package/src/_internals/eslint-plugin-promise.d.ts +6 -0
  82. package/src/_internals/rules/consistent-condition-layout.ts +20 -23
  83. package/src/_internals/rules/consistent-parameter-layout.ts +30 -34
  84. package/src/_internals/rules/index.ts +10 -1
  85. package/src/_internals/rules/no-composable-in-head-getter.ts +132 -26
  86. package/src/_internals/rules/no-reactive-composable-return.ts +55 -0
  87. package/src/_internals/rules/no-reactive-destructure.ts +64 -0
  88. package/src/_internals/rules/no-silent-catch.ts +4 -10
  89. package/src/_internals/rules/no-thenable-zod-refinement.ts +14 -9
  90. package/src/_internals/rules/prefer-enhanced-date.ts +448 -0
  91. package/src/_internals/rules/promise-function-async.ts +2 -6
  92. package/src/_internals/rules/statement-padding.ts +23 -24
  93. package/src/_internals/{utils.ts → rules/utils.ts} +31 -0
  94. package/src/_internals/rules/vue-reactivity.ts +42 -0
  95. package/src/base.ts +51 -47
  96. package/src/nuxt.ts +90 -5
  97. package/src/style.ts +1 -0
  98. package/src/vue.ts +24 -26
  99. package/dist/_internals/configs/restricted-syntax.d.ts +0 -5
  100. package/dist/_internals/configs/restricted-syntax.d.ts.map +0 -1
  101. package/dist/_internals/configs/restricted-syntax.js +0 -12
  102. package/dist/_internals/configs/restricted-syntax.js.map +0 -1
  103. package/dist/_internals/configs/typefest.d.ts +0 -3
  104. package/dist/_internals/configs/typefest.d.ts.map +0 -1
  105. package/dist/_internals/configs/typefest.js +0 -21
  106. package/dist/_internals/configs/typefest.js.map +0 -1
  107. package/dist/_internals/utils.d.ts +0 -4
  108. package/dist/_internals/utils.d.ts.map +0 -1
  109. package/dist/_internals/utils.js +0 -10
  110. package/dist/_internals/utils.js.map +0 -1
  111. package/src/_internals/configs/restricted-syntax.ts +0 -8
  112. package/src/_internals/configs/typefest.ts +0 -19
@@ -0,0 +1,448 @@
1
+ import type {
2
+ AST,
3
+ Rule,
4
+ Scope,
5
+ } from 'eslint';
6
+ import { objectEntries } from 'ts-extras';
7
+
8
+ import type { ParserServices } from './utils';
9
+
10
+ type CallNode = Extract<Rule.Node, { type: 'CallExpression' }>;
11
+ type ProvidedName = keyof typeof importSources;
12
+
13
+ // Replaces the start of a call up to `range[1]` with `text`; the rest of the call stays as written.
14
+ interface Edit {
15
+ provides?: ProvidedName;
16
+ range: AST.Range;
17
+ text: string;
18
+ }
19
+
20
+ interface Plan {
21
+ edit?: Edit;
22
+ replacement: string;
23
+ returnsDate: boolean;
24
+ }
25
+
26
+ const importSources = {
27
+ EnhancedDate: '@kikiutils/shared/classes/enhanced-date',
28
+ formatDate: '@kikiutils/shared/datetime',
29
+ } as const;
30
+
31
+ // EnhancedDate mirrors these date-fns functions with the date as `this` and the remaining arguments, options included.
32
+ const instanceMethods = new Set([
33
+ ...[
34
+ 'Days',
35
+ 'Hours',
36
+ 'Milliseconds',
37
+ 'Minutes',
38
+ 'Months',
39
+ 'Seconds',
40
+ 'Weeks',
41
+ 'Years',
42
+ ].flatMap((unit) => [
43
+ `add${unit}`,
44
+ `sub${unit}`,
45
+ ]),
46
+ ...[
47
+ 'Day',
48
+ 'Minute',
49
+ 'Month',
50
+ 'Week',
51
+ ].flatMap((unit) => [
52
+ `endOf${unit}`,
53
+ `startOf${unit}`,
54
+ ]),
55
+ 'differenceInCalendarDays',
56
+ 'differenceInCalendarWeeks',
57
+ 'differenceInMinutes',
58
+ 'differenceInSeconds',
59
+ 'format',
60
+ 'formatDistanceToNow',
61
+ 'getUnixTime',
62
+ 'isAfter',
63
+ 'isBefore',
64
+ 'isEqual',
65
+ 'isFuture',
66
+ 'isSameDay',
67
+ 'isSameMinute',
68
+ 'isToday',
69
+ 'isTomorrow',
70
+ 'isValid',
71
+ ]);
72
+
73
+ const staticMethods = new Map<string, string>(objectEntries({
74
+ endOfToday: 'endOfToday',
75
+ endOfTomorrow: 'endOfTomorrow',
76
+ endOfYesterday: 'endOfYesterday',
77
+ fromUnixTime: 'fromUnixSeconds',
78
+ max: 'max',
79
+ min: 'min',
80
+ parse: 'fromFormat',
81
+ parseISO: 'fromISO',
82
+ startOfToday: 'startOfToday',
83
+ startOfTomorrow: 'startOfTomorrow',
84
+ startOfYesterday: 'startOfYesterday',
85
+ }));
86
+
87
+ // Receivers that need no parentheses before a member access.
88
+ const memberSafeTypes = new Set([
89
+ 'CallExpression',
90
+ 'Identifier',
91
+ 'MemberExpression',
92
+ 'NewExpression',
93
+ 'ThisExpression',
94
+ ]);
95
+
96
+ function findVariable(scope: Scope.Scope, name: string): Scope.Variable | undefined {
97
+ for (let current: null | Scope.Scope = scope; current; current = current.upper) {
98
+ const variable = current.set.get(name);
99
+ if (variable) return variable;
100
+ }
101
+ }
102
+
103
+ // `date-fns/fp` is curried and `date-fns/locale` has no date functions; `formatDate` is date-fns' alias of `format`.
104
+ function getDateFnsName(source: string, importedName: string): string | undefined {
105
+ let name = importedName;
106
+ if (source !== 'date-fns') {
107
+ if (!source.startsWith('date-fns/') || /^date-fns\/(?:fp|locale)(?:\/|$)/.test(source)) return;
108
+ if (importedName === 'default') name = source.slice('date-fns/'.length);
109
+ }
110
+
111
+ return name === 'formatDate' ? 'format' : name;
112
+ }
113
+
114
+ function isTypeImport(node: unknown): boolean {
115
+ return (node as { importKind?: string }).importKind === 'type';
116
+ }
117
+
118
+ export const preferEnhancedDate: Rule.RuleModule = {
119
+ create(context) {
120
+ const { sourceCode } = context;
121
+ const services = sourceCode.parserServices as Partial<ParserServices> | undefined;
122
+ // Type information only finds receivers that already are EnhancedDate; files without it are still fixed.
123
+ const checker = services?.program?.getTypeChecker();
124
+ const nodeMap = services?.esTreeNodeToTSNodeMap;
125
+ // Calls are collected first so a call can chain onto the rewrite of a date-fns call in its arguments.
126
+ const dateFnsCalls = new Map<CallNode, string>();
127
+ const plans = new Map<CallNode, Plan | undefined>();
128
+ const chainedCalls = new Set<CallNode>();
129
+
130
+ function isEnhancedDate(node: Rule.Node): boolean {
131
+ if (!checker || !nodeMap) return false;
132
+ return checker.getTypeAtLocation(nodeMap.get(node)).getSymbol()?.getName() === 'EnhancedDate';
133
+ }
134
+
135
+ function isNativeDate(node: Rule.Node): boolean {
136
+ if (node.type !== 'Identifier' || node.name !== 'Date') return false;
137
+ // Value references skip type-only declarations; anything else declared as `Date` is not the global.
138
+ const definitions = findVariable(sourceCode.getScope(node), 'Date')?.defs ?? [];
139
+ return definitions.every((definition) => definition.type === 'ImportBinding' && isTypeImport(definition.parent));
140
+ }
141
+
142
+ // Nuxt auto-imports and globals the parser does not know show up as unresolved references.
143
+ function isUnresolved(name: string): boolean {
144
+ return sourceCode.scopeManager.globalScope!.through.some((reference) => reference.identifier.name === name);
145
+ }
146
+
147
+ // Returns undefined when the name cannot be provided, such as a type-only binding or a CommonJS file.
148
+ function provide(node: Rule.Node, fixer: Rule.RuleFixer, name: ProvidedName): Rule.Fix[] | undefined {
149
+ const variable = findVariable(sourceCode.getScope(node), name);
150
+ if (variable) {
151
+ // Configured globals have no definitions.
152
+ const isValue = variable.defs.every((definition) => definition.type !== 'ImportBinding' || (!isTypeImport(definition.node) && !isTypeImport(definition.parent)));
153
+ return isValue ? [] : undefined;
154
+ }
155
+
156
+ if (isUnresolved(name)) return [];
157
+ const { body, sourceType } = sourceCode.ast;
158
+ // Configs often parse CommonJS files as modules, so the extension decides as well.
159
+ if (sourceType !== 'module' || /\.c[jt]s$/.test(context.filename)) return;
160
+ const importText = `import { ${name} } from '${importSources[name]}';`;
161
+ const lastImport = body.findLast((statement) => statement.type === 'ImportDeclaration');
162
+ if (lastImport) {
163
+ // A trailing comment, such as `// eslint-disable-line`, stays on the import it belongs to.
164
+ const after = sourceCode.getTokenAfter(lastImport, { includeComments: true });
165
+ const isTrailingComment = (after?.type === 'Block' || after?.type === 'Line') && after.loc!.start.line === lastImport.loc!.end.line;
166
+ const end = isTrailingComment ? after.range![1] : lastImport.range![1];
167
+ return [
168
+ fixer.insertTextAfterRange(
169
+ [
170
+ end,
171
+ end,
172
+ ],
173
+ `\n${importText}`,
174
+ ),
175
+ ];
176
+ }
177
+
178
+ const lastDirective = body.findLast((statement) => 'directive' in statement && !!statement.directive);
179
+ if (lastDirective) return [fixer.insertTextAfter(lastDirective, `\n\n${importText}`)];
180
+ // Comments directly above the first statement, such as JSDoc or `eslint-disable-next-line`, stay attached to it.
181
+ const [first] = body;
182
+ let start = first!.range![0];
183
+ let line = first!.loc!.start.line;
184
+ for (const comment of sourceCode.getCommentsBefore(first!).toReversed()) {
185
+ if ((comment.type as string) === 'Shebang' || comment.loc!.end.line + 1 < line) break;
186
+ start = comment.range![0];
187
+ line = comment.loc!.start.line;
188
+ }
189
+
190
+ return [
191
+ fixer.insertTextBeforeRange(
192
+ [
193
+ start,
194
+ start,
195
+ ],
196
+ `${importText}\n\n`,
197
+ ),
198
+ ];
199
+ }
200
+
201
+ // Another local, date-fns, global or auto-imported `formatDate` may take other arguments, so those files keep the wrapper.
202
+ function isSharedFormatDateAvailable(node: Rule.Node): boolean {
203
+ const definitions = findVariable(sourceCode.getScope(node), 'formatDate')?.defs;
204
+ if (!definitions) return !isUnresolved('formatDate');
205
+ return definitions.length > 0 && definitions.every((definition) => definition.type === 'ImportBinding'
206
+ && (definition.parent as unknown as { source: { value: unknown } }).source.value === importSources.formatDate);
207
+ }
208
+
209
+ function withProvided(node: Rule.Node, fixer: Rule.RuleFixer, name: ProvidedName, fix: Rule.Fix): null | Rule.Fix[] {
210
+ const provided = provide(node, fixer, name);
211
+ return provided
212
+ ? [
213
+ fix,
214
+ ...provided,
215
+ ]
216
+ : null;
217
+ }
218
+
219
+ // Includes the parentheses written around an argument, which belong to its text.
220
+ function getArgumentTokens(node: Rule.Node, openParen: AST.Token): [AST.Token, AST.Token] {
221
+ let first = sourceCode.getFirstToken(node)!;
222
+ let last = sourceCode.getLastToken(node)!;
223
+ for (;;) {
224
+ const before = sourceCode.getTokenBefore(first)!;
225
+ const after = sourceCode.getTokenAfter(last)!;
226
+ if (before === openParen || before.value !== '(' || after.value !== ')') break;
227
+ first = before;
228
+ last = after;
229
+ }
230
+
231
+ return [
232
+ first,
233
+ last,
234
+ ];
235
+ }
236
+
237
+ function getPlan(node: CallNode): Plan | undefined {
238
+ if (plans.has(node)) return plans.get(node);
239
+ const plan = createPlan(node, dateFnsCalls.get(node)!);
240
+ plans.set(node, plan);
241
+ return plan;
242
+ }
243
+
244
+ function getRewrittenText(node: Rule.Node, edit: Edit): string {
245
+ return edit.text + sourceCode.text.slice(edit.range[1], node.range![1]);
246
+ }
247
+
248
+ function createPlan(node: CallNode, name: string): Plan | undefined {
249
+ if (node.optional || node.arguments.some((argument) => argument.type === 'SpreadElement')) return;
250
+ const openParen = sourceCode.getTokenAfter(node.callee, (token) => token.value === '(')!;
251
+ const staticMethod = staticMethods.get(name);
252
+ if (staticMethod) {
253
+ // `fromUnixSeconds()` takes no options; `fromUnixTime()` options only pick the returned Date class.
254
+ if (name === 'fromUnixTime' && node.arguments.length > 1) return;
255
+ return {
256
+ edit: {
257
+ provides: 'EnhancedDate',
258
+ range: [
259
+ node.range![0],
260
+ openParen.range[0],
261
+ ],
262
+ text: `EnhancedDate.${staticMethod}`,
263
+ },
264
+ replacement: `EnhancedDate.${staticMethod}()`,
265
+ returnsDate: true,
266
+ };
267
+ }
268
+
269
+ const [target, ...rest] = node.arguments as Rule.Node[];
270
+ if (!target || !instanceMethods.has(name)) return;
271
+ // A date-fns call that is rewritten too returns a new EnhancedDate, so the method chains onto its rewrite.
272
+ const inner = target.type === 'CallExpression' && dateFnsCalls.has(target) ? getPlan(target) : undefined;
273
+ const innerEdit = inner?.returnsDate ? inner.edit : undefined;
274
+ const isNewDate = target.type === 'NewExpression'
275
+ && target.callee.type === 'Identifier'
276
+ && (target.callee.name === 'EnhancedDate' || isNativeDate(target.callee as Rule.Node));
277
+
278
+ const isFresh = !!innerEdit || isNewDate;
279
+ const isExisting = !isFresh && isEnhancedDate(target);
280
+ const isWrapped = !isFresh && !isExisting;
281
+ // date-fns `isValid()` is false for anything but a Date or number, which a wrapper would parse instead.
282
+ if (name === 'isValid' && isWrapped) return;
283
+ const [firstToken, lastToken] = getArgumentTokens(target, openParen);
284
+ const targetText = sourceCode.text.slice(firstToken.range[0], lastToken.range[1]);
285
+ const closeParen = sourceCode.getLastToken(node)!;
286
+ const separator = rest.length ? sourceCode.getTokenAfter(lastToken)! : closeParen;
287
+ const hasLostComments = sourceCode.commentsExistBetween(openParen, firstToken) || sourceCode.commentsExistBetween(lastToken, separator);
288
+ // A wrapper copies the date before an awaited argument settles, while date-fns reads it afterwards.
289
+ const awaitsLater = isWrapped && rest.some((argument) => sourceCode.getTokens(argument).some((token) => token.value === 'await' || token.value === 'yield'));
290
+ // Shared's `formatDate` takes the same arguments and reads better than a wrapper.
291
+ if (name === 'format' && isWrapped && isSharedFormatDateAvailable(node)) {
292
+ return {
293
+ edit: {
294
+ provides: 'formatDate',
295
+ range: [
296
+ node.range![0],
297
+ openParen.range[0],
298
+ ],
299
+ text: 'formatDate',
300
+ },
301
+ replacement: 'formatDate()',
302
+ returnsDate: false,
303
+ };
304
+ }
305
+
306
+ let receiver = `new EnhancedDate(${targetText})`;
307
+ if (innerEdit) {
308
+ const [start, end] = target.range!;
309
+ receiver = sourceCode.text.slice(firstToken.range[0], start) + getRewrittenText(target, innerEdit) + sourceCode.text.slice(end, lastToken.range[1]);
310
+ } else if (isNewDate) {
311
+ const callee = target.callee as Rule.Node;
312
+ receiver = `new EnhancedDate${sourceCode.text.slice(callee.range![1], target.range![1]) || '()'}`;
313
+ } else if (isExisting) {
314
+ const isParenthesized = firstToken !== sourceCode.getFirstToken(target);
315
+ receiver = memberSafeTypes.has(target.type) || isParenthesized ? targetText : `(${targetText})`;
316
+ }
317
+
318
+ const replacement = `${isWrapped ? 'new EnhancedDate(date)' : 'date'}.${name}()`;
319
+ const returnsDate = /^(?:add|endOf|startOf|sub)[A-Z]/.test(name);
320
+ if (hasLostComments || awaitsLater) {
321
+ return {
322
+ replacement,
323
+ returnsDate,
324
+ };
325
+ }
326
+
327
+ // The inner rewrite is part of this edit; its own edit would overlap, and when it shares the import insertion it could win.
328
+ if (innerEdit) chainedCalls.add(target as CallNode);
329
+ return {
330
+ edit: {
331
+ provides: innerEdit ? innerEdit.provides : isExisting ? undefined : 'EnhancedDate',
332
+ range: [
333
+ node.range![0],
334
+ rest.length ? sourceCode.getTokenAfter(separator, { includeComments: true })!.range![0] : closeParen.range[1],
335
+ ],
336
+ text: `${receiver}.${name}${rest.length ? '(' : '()'}`,
337
+ },
338
+ replacement,
339
+ returnsDate,
340
+ };
341
+ }
342
+
343
+ function reportDateFnsCall(node: CallNode, name: string): void {
344
+ const plan = getPlan(node);
345
+ if (!plan) return;
346
+ const edit = chainedCalls.has(node) ? undefined : plan.edit;
347
+ context.report({
348
+ data: {
349
+ name,
350
+ replacement: plan.replacement,
351
+ },
352
+ fix: edit
353
+ ? (fixer) => {
354
+ const fix = fixer.replaceTextRange(edit.range, edit.text);
355
+ return edit.provides ? withProvided(node, fixer, edit.provides, fix) : [fix];
356
+ }
357
+ : null,
358
+ messageId: 'dateFns',
359
+ node,
360
+ });
361
+ }
362
+
363
+ function checkNativeDateReference(identifier: Rule.Node): void {
364
+ const parent = identifier.parent!;
365
+ const isCallee = (parent.type === 'CallExpression' || parent.type === 'NewExpression') && parent.callee === identifier;
366
+ if (isCallee && parent.type === 'CallExpression') {
367
+ context.report({
368
+ messageId: 'dateCall',
369
+ node: parent,
370
+ });
371
+
372
+ return;
373
+ }
374
+
375
+ // `Date.now()` and other statics return numbers; `EnhancedDate` inherits them and would only add an import.
376
+ if (!isCallee) return;
377
+ context.report({
378
+ fix: (fixer) => withProvided(parent, fixer, 'EnhancedDate', fixer.replaceText(identifier, 'EnhancedDate')),
379
+ messageId: 'date',
380
+ node: parent,
381
+ });
382
+ }
383
+
384
+ function checkNamespaceReference(identifier: Rule.Node): void {
385
+ const parent = identifier.parent!;
386
+ if (
387
+ parent.type !== 'MemberExpression'
388
+ || parent.object !== identifier
389
+ || parent.computed
390
+ || parent.optional
391
+ || parent.property.type !== 'Identifier'
392
+ ) return;
393
+
394
+ const call = parent.parent;
395
+ if (call.type === 'CallExpression' && call.callee === parent) dateFnsCalls.set(call, getDateFnsName('date-fns', parent.property.name)!);
396
+ }
397
+
398
+ return {
399
+ 'ImportDeclaration': (node) => {
400
+ const source = node.source.value;
401
+ if (isTypeImport(node) || typeof source !== 'string') return;
402
+ for (const specifier of node.specifiers) {
403
+ if (isTypeImport(specifier)) continue;
404
+ let name: string | undefined;
405
+ if (specifier.type !== 'ImportNamespaceSpecifier') {
406
+ const { imported } = specifier as { imported?: { name?: string; value?: unknown } };
407
+ name = getDateFnsName(source, imported ? imported.name ?? String(imported.value) : 'default');
408
+ if (!name) continue;
409
+ } else if (source !== 'date-fns') continue;
410
+
411
+ for (const { references } of sourceCode.getDeclaredVariables(specifier)) {
412
+ for (const reference of references) {
413
+ const identifier = reference.identifier as Rule.Node;
414
+ const parent = identifier.parent!;
415
+ if (!name) checkNamespaceReference(identifier);
416
+ else if (parent.type === 'CallExpression' && parent.callee === identifier) dateFnsCalls.set(parent, name);
417
+ }
418
+ }
419
+ }
420
+ },
421
+ 'Program:exit': () => {
422
+ // Every plan exists before reporting, so calls chained into an outer rewrite are known.
423
+ for (const node of dateFnsCalls.keys()) getPlan(node);
424
+ for (const [node, name] of dateFnsCalls) reportDateFnsCall(node, name);
425
+ const { globalScope } = sourceCode.scopeManager;
426
+ const references = globalScope!.set.get('Date')?.references
427
+ ?? globalScope!.through.filter((reference) => reference.identifier.name === 'Date');
428
+
429
+ for (const reference of references) {
430
+ // typescript-eslint also resolves `: Date` annotations here; only value references create dates.
431
+ if ((reference as { isValueReference?: boolean }).isValueReference === false) continue;
432
+ checkNativeDateReference(reference.identifier as Rule.Node);
433
+ }
434
+ },
435
+ };
436
+ },
437
+ meta: {
438
+ docs: { description: 'Prefer `EnhancedDate` from `@kikiutils/shared` over native `Date` creation and the date-fns functions it wraps.' },
439
+ fixable: 'code',
440
+ messages: {
441
+ date: 'Use `EnhancedDate` instead of `Date`: it is a drop-in subclass with chainable date-fns methods. Disable this line only where a plain `Date` is required.',
442
+ dateCall: '`Date()` returns a string; use `new EnhancedDate().toString()` instead.',
443
+ dateFns: 'Use `{{ replacement }}` instead of date-fns `{{ name }}()` to keep date handling on `EnhancedDate`.',
444
+ },
445
+ schema: [],
446
+ type: 'suggestion',
447
+ },
448
+ };
@@ -1,16 +1,12 @@
1
1
  import tseslint from '@typescript-eslint/eslint-plugin';
2
2
  import type { Rule } from 'eslint';
3
3
  import type {
4
- Node,
5
4
  SignatureDeclaration,
6
5
  Type,
7
6
  TypeChecker,
8
7
  } from 'typescript';
9
8
 
10
- interface ParserServices {
11
- esTreeNodeToTSNodeMap: { get: (node: unknown) => Node };
12
- program: { getTypeChecker: () => TypeChecker };
13
- }
9
+ import type { ParserServices } from './utils';
14
10
 
15
11
  const upstream = tseslint.rules['promise-function-async'] as unknown as Rule.RuleModule;
16
12
  const promiseMembers = new Set([
@@ -50,7 +46,7 @@ export const promiseFunctionAsync: Rule.RuleModule = {
50
46
  };
51
47
 
52
48
  // The upstream rule validates that type information is available.
53
- return upstream.create(Object.create(context, { report: { value: report } }));
49
+ return upstream.create(Object.create(context, { report: { value: report } }) as Rule.RuleContext);
54
50
  },
55
51
  meta: upstream.meta,
56
52
  };
@@ -2,6 +2,27 @@ import type { Rule } from 'eslint';
2
2
 
3
3
  type StatementNode = Extract<Rule.Node, { type: 'Program' }>['body'][number];
4
4
 
5
+ const blockTypes = new Set([
6
+ 'BlockStatement',
7
+ 'ClassDeclaration',
8
+ 'ForInStatement',
9
+ 'ForOfStatement',
10
+ 'ForStatement',
11
+ 'FunctionDeclaration',
12
+ 'IfStatement',
13
+ 'LabeledStatement',
14
+ 'SwitchStatement',
15
+ 'TryStatement',
16
+ 'WhileStatement',
17
+ 'WithStatement',
18
+ ]);
19
+
20
+ function isImportOrReexport(node: StatementNode): boolean {
21
+ return node.type === 'ImportDeclaration'
22
+ || node.type === 'ExportAllDeclaration'
23
+ || (node.type === 'ExportNamedDeclaration' && !!node.source);
24
+ }
25
+
5
26
  export const statementPadding: Rule.RuleModule = {
6
27
  create(context) {
7
28
  const { sourceCode } = context;
@@ -10,16 +31,7 @@ export const statementPadding: Rule.RuleModule = {
10
31
  for (let index = 1; index < statements.length; index++) {
11
32
  const previous = statements[index - 1]!;
12
33
  const next = statements[index]!;
13
- if (
14
- [
15
- previous,
16
- next,
17
- ].some((node) =>
18
- node.type === 'ImportDeclaration'
19
- || node.type === 'ExportAllDeclaration'
20
- || (node.type === 'ExportNamedDeclaration' && node.source))
21
- ) continue;
22
-
34
+ if (isImportOrReexport(previous) || isImportOrReexport(next)) continue;
23
35
  const previousFirstToken = sourceCode.getFirstToken(previous)!;
24
36
  const lastToken = sourceCode.getLastToken(previous)!;
25
37
  const firstToken = sourceCode.getFirstToken(next)!;
@@ -29,20 +41,7 @@ export const statementPadding: Rule.RuleModule = {
29
41
  ? previous.declaration
30
42
  : previous;
31
43
 
32
- const hasBlockClosing = lastToken.value === '}' && blockNode && [
33
- 'BlockStatement',
34
- 'ClassDeclaration',
35
- 'ForInStatement',
36
- 'ForOfStatement',
37
- 'ForStatement',
38
- 'FunctionDeclaration',
39
- 'IfStatement',
40
- 'LabeledStatement',
41
- 'SwitchStatement',
42
- 'TryStatement',
43
- 'WhileStatement',
44
- 'WithStatement',
45
- ].includes(blockNode.type);
44
+ const hasBlockClosing = lastToken.value === '}' && blockNode && blockTypes.has(blockNode.type);
46
45
 
47
46
  if (!isMultiline && !hasBlockClosing) continue;
48
47
  let previousEnd = lastToken.range[1];
@@ -2,12 +2,26 @@ import type {
2
2
  Rule,
3
3
  SourceCode,
4
4
  } from 'eslint';
5
+ import type {
6
+ Node,
7
+ TypeChecker,
8
+ } from 'typescript';
9
+
10
+ type Callee = Extract<Rule.Node, { type: 'CallExpression' }>['callee'];
11
+ type MemberNode = Extract<Callee, { type: 'MemberExpression' }>;
5
12
 
6
13
  export type TokenStore = Pick<
7
14
  SourceCode,
8
15
  'commentsExistBetween' | 'getLastToken' | 'getTokenAfter' | 'getTokenBefore' | 'getTokensBetween'
9
16
  >;
10
17
 
18
+ export interface ParserServices {
19
+ esTreeNodeToTSNodeMap: { get: (node: unknown) => Node };
20
+ program: { getTypeChecker: () => TypeChecker };
21
+ }
22
+
23
+ export const composablePattern = /^use[A-Z]/;
24
+
11
25
  interface TemplateParserServices {
12
26
  defineTemplateBodyVisitor?: (
13
27
  templateVisitor: Rule.RuleListener,
@@ -30,3 +44,20 @@ export function defineScriptAndTemplateVisitors(
30
44
  scriptVisitor,
31
45
  );
32
46
  }
47
+
48
+ export function insertNewlines(offsets: readonly number[]): Rule.ReportFixer {
49
+ return (fixer) => offsets.map((offset) => fixer.insertTextBeforeRange(
50
+ [
51
+ offset,
52
+ offset,
53
+ ],
54
+ '\n',
55
+ ));
56
+ }
57
+
58
+ export function isMemberNamed(node: Callee, name: string): node is MemberNode {
59
+ return node.type === 'MemberExpression'
60
+ && !node.computed
61
+ && node.property.type === 'Identifier'
62
+ && node.property.name === name;
63
+ }
@@ -0,0 +1,42 @@
1
+ import ts from 'typescript';
2
+ import type {
3
+ Symbol as TsSymbol,
4
+ Type,
5
+ TypeChecker,
6
+ } from 'typescript';
7
+
8
+ // `Reactive` (reactive), `ShallowReactive` (shallowReactive), `DeepReadonly` (readonly) and `ShallowUnwrapRef` (proxyRefs).
9
+ // `UnwrapRefSimple` is the mapped type behind `Reactive` and also what a ref's `.value` unwraps to.
10
+ const reactiveProxyAliases = new Set([
11
+ 'DeepReadonly',
12
+ 'Reactive',
13
+ 'ShallowReactive',
14
+ 'ShallowUnwrapRef',
15
+ 'UnwrapRefSimple',
16
+ ]);
17
+
18
+ // A plain-object result is not an alias reference but the alias's own mapped type (e.g. `{ a: number }` from
19
+ // `reactive({ a: 1 })`), so the alias only survives as the declaration enclosing that mapped type.
20
+ function getOriginAlias(checker: TypeChecker, type: Type): TsSymbol | undefined {
21
+ if (type.aliasSymbol) return type.aliasSymbol;
22
+ const declaration = type.getSymbol()?.declarations?.[0];
23
+ if (!declaration || !ts.isMappedTypeNode(declaration)) return;
24
+ let node = declaration.parent;
25
+ while (!ts.isTypeAliasDeclaration(node)) {
26
+ if (!node.parent) return;
27
+ node = node.parent;
28
+ }
29
+
30
+ return checker.getSymbolAtLocation(node.name);
31
+ }
32
+
33
+ // The qualified name is `"<module path>".Name`: a quoted package path for installs or a bare module name for ambient declarations.
34
+ export function isReactiveProxy(checker: TypeChecker, type: Type): boolean {
35
+ if (type.isUnion()) return type.types.some((part) => isReactiveProxy(checker, part));
36
+ const alias = getOriginAlias(checker, type);
37
+ if (!alias) return false;
38
+ const match = /^"(.+)"\.(\w+)$/.exec(checker.getFullyQualifiedName(alias));
39
+ return !!match
40
+ && reactiveProxyAliases.has(match[2]!)
41
+ && (match[1] === '@vue/reactivity' || match[1]!.includes('/@vue/reactivity/'));
42
+ }