refactor: enforce semantic values and numeric lint rules
This commit is contained in:
+1
-1
@@ -9,7 +9,7 @@
|
||||
| Создать/перенести module/component/slice; выбрать page/entity/feature/shared; cross-slice imports | [Architecture](conventions/frontend-architecture.md) |
|
||||
| Component/props, container/VM/view, form, local state/effect, loading/error/retry, Mantine/UI | [UI](conventions/frontend-ui.md) |
|
||||
| Только продуктовая строка или Zod message | [Строки](conventions/frontend-ui.md#строки-и-валидация) |
|
||||
| Только TS declaration/import/export | [Код](conventions/frontend-ui.md#код-и-components) |
|
||||
| TS declaration/import/export, domain literals, magic values | [Код](conventions/frontend-ui.md#код-и-components) + [Domain literals](conventions/frontend-ui.md#domain-literals-and-magic-values) |
|
||||
| query/mutation, shared/api, server state/cache, generated types, Bearer/refresh | [Data](conventions/frontend-data.md) |
|
||||
| Тесты или behavior с testing risk | [Testing](conventions/frontend-testing.md) |
|
||||
| Новый abstraction/dependency, refactor или неоднозначный scope | [Общий выбор реализации](../../docs/development/engineering-governance.md#выбор-реализации) |
|
||||
|
||||
@@ -91,6 +91,57 @@ CSF `*.stories.tsx` сохраняют default meta и прямые story export
|
||||
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
|
||||
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
|
||||
|
||||
## Domain literals and magic values
|
||||
|
||||
Finite business vocabulary must be modeled explicitly; incidental implementation
|
||||
literals stay inline. Это относится к error codes, statuses, operation/account/
|
||||
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
|
||||
|
||||
Перед новым определением найди existing owner/type/value. В branching и comparisons
|
||||
используй символическое значение владельца; не повторяй raw domain literals.
|
||||
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
|
||||
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
|
||||
без подходящего аналога используй `as const` с derived union:
|
||||
|
||||
```ts
|
||||
const BankErrorCode = {
|
||||
InvalidDate: "BANK_INVALID_DATE",
|
||||
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
|
||||
} as const;
|
||||
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||
|
||||
// Вместо code === "BANK_INVALID_DATE":
|
||||
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
|
||||
```
|
||||
|
||||
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
|
||||
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
|
||||
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
|
||||
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
|
||||
`percentage * 100` и очевидные локальные детали без semantic benefit.
|
||||
При неясном owner/смысле оставь значение и укажи ограничение в review.
|
||||
|
||||
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
|
||||
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
|
||||
custom lint/AST rules, generation/validation scripts или тесты существования
|
||||
констант. Semantic review проверяет ownership, единое написание и неизменность
|
||||
wire values; обычные behavior tests проверяют поведение.
|
||||
|
||||
Backend API vocabulary бери из generated OpenAPI types/client, runtime values —
|
||||
когда генератор их предоставляет. Не создавай ручную копию backend enum/object.
|
||||
Текущий `schema.d.ts` предоставляет только types: используй indexed-access type
|
||||
из `paths`; typed literals в запросах/сравнениях допустимы при отсутствии
|
||||
runtime values. `ProblemDetailsDto.code` сейчас `string`: не выдумывай закрытый
|
||||
frontend error enum. Развитие API source — отдельное contract-решение.
|
||||
Frontend `enum` по-прежнему запрещён локальным TS/style profile.
|
||||
|
||||
`noMagicNumbers` включён как error в Biome. Fixtures, tests и stories исключены
|
||||
из этого правила; остальные проверки для них сохраняются. Используй имена
|
||||
политик/единиц и existing values. Точечное подавление допустимо для очевидного
|
||||
incidental значения с объяснением, например перевода доли в проценты; не подавляй
|
||||
скрытые бизнес-лимиты. Semantic magic strings проверяются conventions/review: в
|
||||
установленном Biome нет такого встроенного правила, новый инструмент не добавляем.
|
||||
|
||||
## Строки и валидация
|
||||
|
||||
Продуктовый текст хранится в `src/shared/i18n/locales/ru.ts`, читается через
|
||||
|
||||
Reference in New Issue
Block a user