357 lines
14 KiB
JavaScript
357 lines
14 KiB
JavaScript
/**
|
||
* ESLint конфигурация для frontend (TypeScript, React, Vite, ES Modules).
|
||
* strictTypeChecked + react + react-hooks + jsx-a11y + sonarjs + import-x.
|
||
*/
|
||
import js from '@eslint/js';
|
||
import comments from '@eslint-community/eslint-plugin-eslint-comments';
|
||
import importX from 'eslint-plugin-import-x';
|
||
import jsxA11y from 'eslint-plugin-jsx-a11y';
|
||
import react from 'eslint-plugin-react';
|
||
import reactHooks from 'eslint-plugin-react-hooks';
|
||
import sonarjs from 'eslint-plugin-sonarjs';
|
||
import globals from 'globals';
|
||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||
import tseslint from 'typescript-eslint';
|
||
|
||
const CONFIG_ROOT = import.meta.dirname;
|
||
|
||
const TEST_FILES = ['**/*.{test,spec}.{ts,tsx}'];
|
||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/vite.config.*'];
|
||
|
||
/* eslint-disable no-unused-vars -- eslint.config.js lintится самим собой */
|
||
|
||
/* Забираем правила из пресетов плагинов */
|
||
const reactRecommendedRules =
|
||
react.configs.flat?.recommended?.rules ??
|
||
react.configs.recommended?.rules ??
|
||
{};
|
||
|
||
const reactHooksRecommendedRules =
|
||
reactHooks.configs?.flat?.recommended?.rules ??
|
||
reactHooks.configs?.['flat/recommended']?.rules ??
|
||
reactHooks.configs?.['recommended-latest']?.rules ??
|
||
reactHooks.configs?.recommended?.rules ??
|
||
{};
|
||
|
||
const jsxA11yRecommendedRules =
|
||
jsxA11y.flatConfigs?.recommended?.rules ??
|
||
jsxA11y.configs?.recommended?.rules ??
|
||
{};
|
||
|
||
export default defineConfig(
|
||
/* ── Глобальные игноры ─────────────────────────────────────── */
|
||
globalIgnores([
|
||
'**/node_modules/**',
|
||
'**/dist/**',
|
||
'**/build/**',
|
||
'**/coverage/**',
|
||
'**/*.min.js',
|
||
]),
|
||
|
||
/* ── Политика линтера ─────────────────────────────────────── */
|
||
{
|
||
name: 'client/linter-policy',
|
||
linterOptions: {
|
||
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
|
||
// Единственный способ отключить правило — file-level override в этом конфиге.
|
||
noInlineConfig: true,
|
||
reportUnusedDisableDirectives: 'error',
|
||
reportUnusedInlineConfigs: 'error',
|
||
},
|
||
},
|
||
|
||
/* ── TypeScript — strict mode ──────────────────────────────── */
|
||
...tseslint.configs.strictTypeChecked,
|
||
|
||
/* ── Импорты (import-x) ────────────────────────────────────── */
|
||
importX.flatConfigs.recommended,
|
||
importX.flatConfigs.typescript,
|
||
|
||
/* ── SonarJS ───────────────────────────────────────────────── */
|
||
sonarjs.configs.recommended,
|
||
|
||
/* ── React (TSX) ───────────────────────────────────────────── */
|
||
{
|
||
name: 'client/react',
|
||
files: ['**/*.tsx'],
|
||
plugins: {
|
||
react,
|
||
'react-hooks': reactHooks,
|
||
'jsx-a11y': jsxA11y,
|
||
},
|
||
languageOptions: {
|
||
parserOptions: {
|
||
ecmaFeatures: { jsx: true },
|
||
},
|
||
},
|
||
settings: {
|
||
react: { version: 'detect' },
|
||
},
|
||
rules: {
|
||
...reactRecommendedRules,
|
||
...reactHooksRecommendedRules,
|
||
...jsxA11yRecommendedRules,
|
||
|
||
'react-hooks/exhaustive-deps': 'error',
|
||
'react-hooks/rules-of-hooks': 'error',
|
||
'react/jsx-no-leaked-render': 'error',
|
||
'react/no-array-index-key': 'error',
|
||
'react/no-danger': 'error',
|
||
'react/no-unstable-nested-components': ['error', { allowAsProps: false }],
|
||
/* В TS prop-types не нужны */
|
||
'react/prop-types': 'off',
|
||
/* React 18 с jsx: react-jsx не требует React в scope */
|
||
'react/react-in-jsx-scope': 'off',
|
||
},
|
||
},
|
||
|
||
/* ── Правила клиентского кода ──────────────────────────────── */
|
||
{
|
||
name: 'client/rules',
|
||
files: ['**/*.{ts,tsx}'],
|
||
languageOptions: {
|
||
ecmaVersion: 'latest',
|
||
sourceType: 'module',
|
||
globals: { ...globals.browser, ...globals.es2021 },
|
||
parserOptions: {
|
||
projectService: {
|
||
allowDefaultProject: ['*.config.ts'],
|
||
},
|
||
tsconfigRootDir: CONFIG_ROOT,
|
||
},
|
||
},
|
||
settings: {
|
||
'import-x/resolver': {
|
||
typescript: { alwaysTryTypes: true },
|
||
node: true,
|
||
},
|
||
},
|
||
plugins: {
|
||
'@eslint-community/eslint-comments': comments,
|
||
},
|
||
rules: {
|
||
...js.configs.recommended.rules,
|
||
|
||
/* Отключаем базовые правила, которые заменяет TS */
|
||
'no-redeclare': 'off',
|
||
'no-unused-vars': 'off',
|
||
'no-use-before-define': 'off',
|
||
'no-shadow': 'off',
|
||
'no-throw-literal': 'off',
|
||
'consistent-return': 'off',
|
||
'prefer-promise-reject-errors': 'off',
|
||
'require-await': 'off',
|
||
|
||
/* Корректность */
|
||
'array-callback-return': ['error', { allowImplicit: false, checkForEach: true }],
|
||
curly: ['error', 'all'],
|
||
eqeqeq: ['error', 'always', { null: 'ignore' }],
|
||
'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }],
|
||
'no-console': ['error', { allow: ['error', 'warn'] }],
|
||
'no-debugger': 'error',
|
||
'no-eval': 'error',
|
||
'no-alert': 'error',
|
||
'no-else-return': ['error', { allowElseIf: false }],
|
||
'no-extend-native': 'error',
|
||
'no-implicit-coercion': 'error',
|
||
'no-lone-blocks': 'error',
|
||
'no-nested-ternary': 'error',
|
||
'no-param-reassign': ['error', { props: true }],
|
||
'no-promise-executor-return': 'error',
|
||
'no-return-assign': ['error', 'always'],
|
||
'no-self-compare': 'error',
|
||
'no-sequences': 'error',
|
||
'no-unneeded-ternary': 'error',
|
||
'no-useless-concat': 'error',
|
||
'no-useless-return': 'error',
|
||
'object-shorthand': ['error', 'always'],
|
||
'prefer-const': 'error',
|
||
'prefer-object-spread': 'error',
|
||
'require-atomic-updates': 'error',
|
||
|
||
/* TS — типы */
|
||
'@typescript-eslint/ban-ts-comment': [
|
||
'error',
|
||
{
|
||
'ts-check': false,
|
||
'ts-expect-error': 'allow-with-description',
|
||
'ts-ignore': true,
|
||
'ts-nocheck': true,
|
||
minimumDescriptionLength: 20,
|
||
},
|
||
],
|
||
'@typescript-eslint/consistent-type-assertions': ['error', { assertionStyle: 'as' }],
|
||
'@typescript-eslint/no-explicit-any': 'error',
|
||
'@typescript-eslint/no-non-null-assertion': 'error',
|
||
'@typescript-eslint/no-unnecessary-type-assertion': ['error', { checkLiteralConstAssertions: true }],
|
||
'@typescript-eslint/no-unsafe-argument': 'error',
|
||
'@typescript-eslint/no-unsafe-assignment': 'error',
|
||
'@typescript-eslint/no-unsafe-call': 'error',
|
||
'@typescript-eslint/no-unsafe-member-access': 'error',
|
||
'@typescript-eslint/no-unsafe-return': 'error',
|
||
'@typescript-eslint/no-unsafe-type-assertion': 'error',
|
||
|
||
/* TS — контракты */
|
||
'@typescript-eslint/consistent-return': 'error',
|
||
'@typescript-eslint/consistent-type-exports': 'error',
|
||
'@typescript-eslint/consistent-type-imports': [
|
||
'error',
|
||
{ prefer: 'type-imports', fixStyle: 'separate-type-imports' },
|
||
],
|
||
'@typescript-eslint/no-deprecated': 'error',
|
||
'@typescript-eslint/no-misused-promises': [
|
||
'error',
|
||
{
|
||
checksConditionals: true,
|
||
checksSpreads: true,
|
||
checksVoidReturn: {
|
||
arguments: true,
|
||
properties: true,
|
||
returns: true,
|
||
variables: true,
|
||
},
|
||
},
|
||
],
|
||
'@typescript-eslint/no-unnecessary-condition': [
|
||
'error',
|
||
{ allowConstantLoopConditions: 'only-allowed-literals' },
|
||
],
|
||
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
|
||
'@typescript-eslint/only-throw-error': 'error',
|
||
'@typescript-eslint/prefer-nullish-coalescing': [
|
||
'error',
|
||
{
|
||
ignoreBooleanCoercion: false,
|
||
ignoreConditionalTests: false,
|
||
ignorePrimitives: { bigint: false, boolean: false, number: false, string: false },
|
||
ignoreTernaryTests: false,
|
||
},
|
||
],
|
||
'@typescript-eslint/prefer-optional-chain': [
|
||
'error',
|
||
{
|
||
allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: false,
|
||
checkAny: true,
|
||
checkBigInt: true,
|
||
checkBoolean: true,
|
||
checkNumber: true,
|
||
checkString: true,
|
||
requireNullish: true,
|
||
},
|
||
],
|
||
'@typescript-eslint/require-await': 'error',
|
||
'@typescript-eslint/return-await': ['error', 'error-handling-correctness-only'],
|
||
'@typescript-eslint/strict-boolean-expressions': 'error',
|
||
'@typescript-eslint/promise-function-async': 'error',
|
||
'@typescript-eslint/no-floating-promises': ['error', { ignoreIIFE: false, ignoreVoid: false }],
|
||
'@typescript-eslint/no-shadow': 'error',
|
||
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
|
||
|
||
/* Сложность */
|
||
complexity: ['error', 10],
|
||
'max-classes-per-file': ['error', 1],
|
||
'max-depth': ['error', 3],
|
||
'max-lines': ['error', { max: 400, skipBlankLines: true, skipComments: true }],
|
||
'max-lines-per-function': ['error', { IIFEs: true, max: 80, skipBlankLines: true, skipComments: true }],
|
||
'max-nested-callbacks': ['error', 3],
|
||
'max-params': ['error', 4],
|
||
'max-statements': ['error', 25],
|
||
'sonarjs/cognitive-complexity': ['error', 10],
|
||
'sonarjs/no-duplicate-string': 'error',
|
||
|
||
/* Импорты */
|
||
'import-x/first': 'error',
|
||
'import-x/newline-after-import': 'error',
|
||
'import-x/no-absolute-path': 'error',
|
||
'import-x/no-cycle': ['warn', { ignoreExternal: true, maxDepth: 5 }],
|
||
'import-x/no-duplicates': 'error',
|
||
'import-x/no-extraneous-dependencies': [
|
||
'error',
|
||
{ devDependencies: false, optionalDependencies: false, peerDependencies: false },
|
||
],
|
||
'import-x/no-named-as-default': 'error',
|
||
'import-x/no-named-as-default-member': 'error',
|
||
'import-x/no-self-import': 'error',
|
||
'import-x/no-useless-path-segments': 'error',
|
||
'import-x/order': ['error', {
|
||
alphabetize: { caseInsensitive: true, order: 'asc' },
|
||
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'type'],
|
||
'newlines-between': 'always',
|
||
}],
|
||
|
||
},
|
||
},
|
||
|
||
/* ── Конфигурационные файлы ────────────────────────────────── */
|
||
{
|
||
name: 'client/config-files',
|
||
files: CONFIG_AND_SCRIPT_FILES,
|
||
extends: [tseslint.configs.disableTypeChecked],
|
||
rules: {
|
||
'no-console': ['error', { allow: ['error', 'warn'] }],
|
||
'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }],
|
||
},
|
||
},
|
||
|
||
/* ── Тестовые файлы ────────────────────────────────────────── */
|
||
{
|
||
name: 'client/tests',
|
||
files: TEST_FILES,
|
||
rules: {
|
||
'max-lines': ['error', { max: 700, skipBlankLines: true, skipComments: true }],
|
||
'max-lines-per-function': 'off',
|
||
'max-statements': 'off',
|
||
'sonarjs/cognitive-complexity': 'off',
|
||
'sonarjs/no-duplicate-string': 'off',
|
||
'react/no-array-index-key': 'off',
|
||
'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }],
|
||
'@typescript-eslint/no-floating-promises': 'off',
|
||
'@typescript-eslint/require-await': 'off',
|
||
},
|
||
},
|
||
|
||
/* ── Файловые исключения (единственный способ отключить правило) ── */
|
||
{
|
||
name: 'client/api-client',
|
||
files: ['src/api/client.ts'],
|
||
rules: {
|
||
// fetch.json() возвращает any — assertion неизбежен
|
||
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||
},
|
||
},
|
||
{
|
||
name: 'client/news-editor',
|
||
files: ['src/hooks/useNewsEditor.ts'],
|
||
rules: {
|
||
// Хук-оркестратор: 4 action-обработчика + toolbar + upload
|
||
'max-lines-per-function': 'off',
|
||
// window.confirm для подтверждения удаления
|
||
'no-alert': 'off',
|
||
// e.target.value = '' — сброс file input (стандартный паттерн)
|
||
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
|
||
// async IIFE в useEffect для загрузки новости
|
||
'@typescript-eslint/no-floating-promises': 'off',
|
||
// newsId гарантированно string (проверено isNew)
|
||
'@typescript-eslint/restrict-template-expressions': 'off',
|
||
},
|
||
},
|
||
{
|
||
name: 'client/auth-context',
|
||
files: ['src/auth/AuthContext.tsx'],
|
||
rules: {
|
||
// onAuthExpired: navigate('/login') возвращает void,
|
||
// но линтер требует обработки (no-floating-promises)
|
||
'@typescript-eslint/no-floating-promises': 'off',
|
||
},
|
||
},
|
||
{
|
||
name: 'client/auth-pages',
|
||
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
|
||
rules: {
|
||
// .then/.catch/.finally цепочка в handleSubmit: rejection обработан,
|
||
// но no-floating-promises не распознаёт pattern (см. комментарий в файле)
|
||
'@typescript-eslint/no-floating-promises': 'off',
|
||
},
|
||
},
|
||
);
|