feat: remove v1 routes and libs

This commit is contained in:
2026-09-25 16:39:58 +05:00
parent 473b62ef53
commit 16d4288912
91 changed files with 181 additions and 11960 deletions
+12 -47
View File
@@ -8,12 +8,11 @@
- `web/eslint-plugins/` — локальные ESLint-плагины.
- `design-tokens/` — правила для `<style>`-блоков svelte-компонентов.
- `isolation/` — правило изоляции old/new UI.
- `conventions/` — конвенции кода (интерфейс пропсов, запрет union-алиасов).
- `i18n/` — кросс-языковой линтер словарей (`dict-consistency`).
- `__tests__/` — юнит-тесты (Vitest + `RuleTester`/`Linter`).
- `__fixtures__/` — фикстуры для тестов: миниатюрный `src/app.css` (словарь
токенов), файлы для изоляционных тестов и мини-словари `lib/i18n/`.
токенов) и мини-словари `lib/i18n/`.
- `web/scripts/`:
- `lint-all.mjs` — оркестратор `lint:all`.
- `check-tokens.mjs` + `token-audit/` — токен-аудит по `app.css`.
@@ -28,16 +27,9 @@
`@typescript-eslint/consistent-type-imports` (запрет инлайн-тип-импортов,
`prefer: 'type-imports'`).
- Полные `recommended`-наборы (`eslint` + `typescript-eslint` +
`eslint-plugin-svelte`) навешаны **только на новый код**
(`src/lib/components/**`, `src/routes/**`), чтобы старый код не засыпался
предсуществующими ошибками. Старый код (C17) — `src/lib/v1/**`,
`src/routes/v1/**`. Когда старый дизайн удалён (C19), scoped-блок убирается и
`recommended` включается на весь код.
- **Scoped-пути двигаются вместе с папками** (см. `plan-redesign.md` §10): не
оставлять устаревшие пути в `eslint.config.js` (C17 уже двигал
`routes/preview/**` → `routes/**` и `components/kit/**` → `components/**`; на
C19 при наведении порядка в `components/` paths останутся `components/**` +
`routes/**`).
`eslint-plugin-svelte`) навешаны на UI-код (`src/lib/components/**`,
`src/routes/**`). Scoped-пути двигаются вместе с папками: не оставлять
устаревшие пути в `eslint.config.js`.
- Для `*.svelte` выключен `prefer-const` (пропсы в Svelte 5 пишутся через
`let`).
- `allowDefaultProject` перечисляет test-файлы и фикстуры точечно (glob'ы с `**`
@@ -45,7 +37,6 @@
`__fixtures__/` дописать их туда же.
- design-tokens правила применяются к тем же scoped-путям
(`src/lib/components/**`, `src/routes/**`).
- isolation-правило включено на весь `**/*.{ts,svelte}`.
## Правила плагина design-tokens
@@ -66,10 +57,11 @@
## Правило плагина i18n (`i18n/dict-consistency`)
Кросс-языковой линтер словарей `lib/i18n/` (план: `docs/plan-preview-i18n.md`
§Фаза 8). Сравнивает каждый словарь со **всеми** остальными локалями (не только
с BASE). Список локалей берётся из `LOCALES` в `lib/i18n/dict.ts` — новый
словарь подхватывается без правки правила.
Кросс-языковой линтер словарей `lib/i18n/` (историческая модель и завершённые
фазы: `docs/archive/plan-preview-i18n.md`). Сравнивает каждый словарь со
**всеми** остальными локалями (не только с BASE). Список локалей берётся из
`LOCALES` в `lib/i18n/dict.ts` — новый словарь подхватывается без правки
правила.
- **warn-only, никогда `error`** — пропущенный перевод не валит сборку.
- Диагностика живёт там, где фикс: каждый файл репортит **только свои**
@@ -92,9 +84,9 @@
отсутствовать только в базовой локали; в текущей конфигурации это registry
metadata `tools.*.title` и `tools.*.description`. Пустые значения и
placeholders для присутствующих ключей всё равно проверяются.
- `ignoreMissingPatterns: string[]` — паттерны legacy-ключей, которые временно
не проверяются на missing; в текущей конфигурации это старый `tools.*.params`,
не используемый новым UI. Эта опция не отключает empty/placeholder checks.
- `ignoreMissingPatterns: string[]` — паттерны ключей, которые временно не
проверяются на missing; в текущей конфигурации это неиспользуемые
`tools.*.params`. Эта опция не отключает empty/placeholder checks.
- Тесты: `__tests__/dict-consistency.test.ts`, фикстуры-словари в
`__fixtures__/src/lib/i18n/` (`en`, `ru`, `de` — консистентные, zero-warn) — в
тестах подаются модифицированные варианты `en.ts`/`ru.ts` против эталонных на
@@ -150,9 +142,6 @@ hct-авторство.
`no-token-definition-in-svelte`) через `RuleTester` со строковыми кейсами;
`no-undefined-in-svelte` — через `Linter` API, т.к. читает словарь токенов из
`__fixtures__/src/app.css` (не из реального `src/app.css`).
- `__tests__/no-mixed-imports.test.ts` — isolation-правило через `Linter` API с
`cwd` на `__fixtures__`: правило резолвит импорты по реальным файлам, поэтому
цели импортов обязаны существовать на диске.
- Хелпер `__tests__/helpers.ts` собирает `Linter` с `cwd = __fixtures__` —
`process.cwd()` не трогается, реальные `src/` не читаются.
@@ -161,27 +150,3 @@ hct-авторство.
Фикстуры живут в `__fixtures__/` и сами прогоняются линтом (`eslint .`), поэтому
добавление/правка стабов — тоже работа с валидным кодом.
## Isolation-правило (`isolation/no-mixed-imports`)
**Полная взаимная изоляция** старого (v1) и нового (корень) UI. В отличие от
`no-restricted-imports`, правило **резолвит** каждый импорт (и `$lib/...`, и
относительные `./`/`../`) до реального файла и классифицирует стороны по
фактическому пути, поэтому относительным импортом правило не обойти.
- Старое: `routes/v1/**`, `lib/v1/**`.
- Новое: `routes/**` без `v1/**`; корневой `lib` целиком (`lib/**`) без
`lib/v1/**` и без общих пакетов.
- Общее (разрешено обоим) — только служебные пакеты: `core/`, `theme`. v1 не
высовывается: из `lib/v1/**` наружу разрешены импорты лишь в общие пакеты и в
собственный форк i18n (`lib/v1/i18n/**`).
- Плагин **конфигурируем** (опции `old`/`new` + `root`/`alias` в
`eslint.config.js`): перенос старых файлов в папки `old/` — это правка
glob-паттернов в настройке, а не код правила.
- Изоляция уже достигнута: старый `lib/v1/registry.ts`/`registry-helpers.ts` не
тянут `registry-schema` (пилоты add-border/add-stroke работают через
`params`), `registry.ts` не импортирует `ToolSchema`; новый `list-tools`
использует `$lib/tool-icons.ts`, а не старые `lib/v1/tools/tool-icons.ts`.
Линтер только показывает ошибки, старый код (непрефиксованные токены, hex в
`app_v1.css`) — известный техдолг, его НЕ чинить и не игнорировать правилами.
@@ -1 +0,0 @@
// Fixture stub for lint-rule tests: content is ignored, must exist for import resolution.
@@ -1,2 +0,0 @@
// Fixture stub for lint-rule tests: content is ignored (the test supplies the
// source code), this file only has to EXIST for import resolution.
@@ -1 +0,0 @@
<!-- Fixture stub for lint-rule tests: content is ignored, must exist for import resolution. -->
+4 -5
View File
@@ -3,11 +3,10 @@
// Two strategies, picked per rule in the test files:
// - RuleTester (eslint) — pure string cases, no filesystem. Best fit for the
// design-tokens rules that only inspect the postcss AST of Svelte `<style>`.
// - Linter API + fixtures — needed when a rule reads real files. The isolation
// rule resolves imports via fs (targets must exist on disk) and
// no-undefined-in-svelte reads <cwd>/src/app.css for the token dictionary.
// `verifyInFixtures` runs a rule with cwd fixed to `__fixtures__/`, so both
// work without touching process.cwd() or the real src/ tree.
// - Linter API + fixtures — needed when a rule reads real files, such as
// no-undefined-in-svelte, which reads <cwd>/src/app.css for the token
// dictionary. `verifyInFixtures` runs a rule with cwd fixed to
// `__fixtures__/`, without touching process.cwd() or the real src/ tree.
import { Linter } from "eslint";
import type { Rule } from "eslint";
import path from "node:path";
@@ -1,133 +0,0 @@
// Tests for the isolation rule (web/eslint-plugins/isolation/no-mixed-imports.js).
//
// The rule RESOLVES import specifiers to real files (via $lib alias and
// relative ../ paths), so every import target must exist on disk. It therefore
// runs through the Linter API with cwd pinned to the committed fixture tree
// (__fixtures__/src) — see __tests__/helpers.ts.
//
// Side map (mirrors the defaults in no-mixed-imports.js):
// old -> routes/v1/**, lib/v1/**
// new -> routes/** (minus v1), lib/** (minus lib/v1/** and shared)
// shared-> everything else: core/, theme
import { describe, expect, it } from "vitest";
import noMixedImports from "../isolation/no-mixed-imports.js";
import { asRuleModule, verifyInFixtures, type FlatConfig } from "./helpers.js";
const isolationConfig: FlatConfig = [
{
files: ["**/*.{ts,svelte}"],
plugins: {
isolation: {
rules: { "no-mixed-imports": asRuleModule(noMixedImports) },
},
},
rules: { "isolation/no-mixed-imports": "error" },
},
];
const messagesFor = (relFile: string, code: string) =>
verifyInFixtures(isolationConfig, code, relFile);
/** Assert a single "noMixed" violation with the given sides. */
function expectViolation(
relFile: string,
code: string,
side: string,
target: string,
) {
const messages = messagesFor(relFile, code);
expect(messages).toHaveLength(1);
expect(messages[0].messageId).toBe("noMixed");
// ESLint interpolates `data` into the message text (no `data` field on the
// returned message), so assert on the rendered message instead.
expect(messages[0].message).toContain(`"${side}" file imports "${target}"`);
}
/** Assert the import is allowed (no violations). */
function expectClean(relFile: string, code: string) {
expect(messagesFor(relFile, code)).toEqual([]);
}
describe("isolation/no-mixed-imports", () => {
it("flags an old file importing a new component", () => {
expectViolation(
"lib/v1/old.ts",
'import { c } from "../components/CheckerCanvas.svelte";',
"old",
"new",
);
});
it("flags a new route importing an old module through the $lib alias", () => {
expectViolation(
"routes/+page.svelte",
'import { o } from "$lib/v1/old";',
"new",
"old",
);
});
it("flags a new component importing old code via a relative path", () => {
expectViolation(
"lib/components/CheckerCanvas.svelte",
'import { o } from "../v1/old.ts";',
"new",
"old",
);
});
it("allows old -> shared (core via relative path)", () => {
expectClean("lib/v1/old.ts", 'import { e } from "../core/errors";');
});
it("flags old -> root i18n ($lib/i18n is the new branch now)", () => {
expectViolation(
"routes/v1/+layout.svelte",
'import { t } from "$lib/i18n/t";',
"old",
"new",
);
});
it("allows old -> own i18n copy and theme via $lib", () => {
expectClean(
"routes/v1/+layout.svelte",
'import { t } from "$lib/v1/i18n/t";',
);
expectClean(
"routes/v1/+layout.svelte",
'import { g } from "$lib/theme.svelte";',
);
});
it("allows new -> new (root i18n and components)", () => {
expectClean("routes/+page.svelte", 'import { t } from "$lib/i18n/t";');
expectClean(
"routes/+page.svelte",
'import { b } from "$lib/components/ui/Button.svelte";',
);
});
it("flags new i18n importing old and leaves core shared", () => {
expectViolation(
"lib/i18n/t.ts",
'import { o } from "$lib/v1/old";',
"new",
"old",
);
expectClean(
"lib/core/errors.ts",
'import { c } from "$lib/components/CheckerCanvas.svelte";',
);
});
it("keeps the old i18n copy on the old side", () => {
expectClean("lib/v1/i18n/t.ts", 'import { o } from "$lib/v1/old";');
expectViolation(
"lib/v1/i18n/t.ts",
'import { c } from "$lib/components/CheckerCanvas.svelte";',
"old",
"new",
);
});
});
-33
View File
@@ -1,33 +0,0 @@
/**
* Local ESLint plugin "isolation".
*
* Guarantees full isolation between the old (v1, archived) UI branch and the
* new one. Unlike no-restricted-imports (which matches the literal import
* specifier string only), these rules RESOLVE the specifier to a real file
* (supporting both `$lib/...` aliases and relative `./`/`../` paths) and then
* classify both sides by their actual location on disk.
*
* Why this is needed:
* - old code imports new things via RELATIVE paths (e.g. `../registry-schema`),
* which `$lib/...` glob patterns cannot catch;
* - the same target can be written many ways (`$lib/x`, `../x`, `../../x`),
* so enumerating literal strings is fragile.
*
* Configuration (per rule options):
* - `root`: path from the lint cwd to the source root (default "src");
* - `alias`: mapping from import aliases to dirs relative to root
* (default { "$lib": "lib" });
* - `old`, `new`: glob patterns (gitignore-style, `!` = negation) for the two
* branches. Files matched by neither are "shared" and unrestricted.
*/
import noMixedImports from "./no-mixed-imports.js";
export default {
meta: {
name: "isolation",
version: "1.0.0",
},
rules: {
"no-mixed-imports": noMixedImports,
},
};
@@ -1,196 +0,0 @@
/**
* Isolation rule: forbid mixing the "old" (v1) and the "new" branches.
*
* The rule RESOLVES every import specifier to a real file (handles both the
* `$lib/...` alias and relative `./` / `../` paths), classifies the source
* file and each import target by their actual location, and reports whenever an
* "old" file imports a "new" one or vice versa. Files that match neither side
* are "shared" (core/, theme, assets, tests, ...) and can import freely.
*
* Options (object, all optional):
* - root: path from lint cwd to the source dir (default "src");
* - alias: { $lib: "lib" } — alias -> dir relative to root;
* - old, new: gitignore-style glob lists for the two branches. Both default
* to the current layout so that moving a module between branches is a
* one-line config change (e.g. everything old will live under `old/`).
*/
import fs from "node:fs";
import path from "node:path";
// NEW declared as an allowlist: `lib/**` descends into v1/ and the shared
// packages (core/, theme), so negations carve them back out; `routes/**`
// needs `!routes/v1/**` for the old branch. Last-match-wins
// (see matchesGlobList).
const DEFAULT_OLD = ["routes/v1/**", "lib/v1/**"];
const DEFAULT_NEW = [
"routes/**",
"!routes/v1/**",
"lib/**",
"!lib/v1/**",
"!lib/core/**",
"!lib/theme.svelte.ts",
];
/** Escape everything except glob metacharacters, then handle **, *, ?. */
function globToRegExp(glob) {
let out = "^";
for (let i = 0; i < glob.length; i++) {
const ch = glob[i];
if (ch === "*" && glob[i + 1] === "*") {
out += ".*";
i++;
} else if (ch === "*") {
out += "[^/]*";
} else if (ch === "?") {
out += "[^/]";
} else if ("\\^$.|?*+()[]{}".includes(ch)) {
out += `\\${ch}`;
} else {
out += ch;
}
}
return new RegExp(out + "$");
}
/** gitignore-style: last-match-wins, `!` negates earlier positives. */
function matchesGlobList(patterns, rel) {
let included = false;
for (const raw of patterns) {
const negated = raw.startsWith("!");
const pattern = negated ? raw.slice(1) : raw;
if (globToRegExp(pattern).test(rel)) {
if (negated) return false;
included = true;
}
}
return included;
}
/** First existing candidate when resolving a bare path (no extension known). */
function firstExisting(base) {
const candidates = [
base,
`${base}.ts`,
`${base}.svelte`,
`${base}.svelte.ts`,
`${base}/index.ts`,
`${base}/index.svelte`,
];
for (const c of candidates) {
try {
if (fs.statSync(c).isFile()) return c;
} catch {
// keep trying
}
}
return null;
}
function toPortable(p) {
return p.replace(/\\/g, "/");
}
export default {
meta: {
type: "problem",
docs: {
description:
"Forbid imports between the old (v1) UI branch and the new branch.",
category: "Best Practices",
},
schema: [
{
type: "object",
properties: {
root: { type: "string" },
alias: { type: "object", additionalProperties: { type: "string" } },
old: { type: "array", items: { type: "string" } },
new: { type: "array", items: { type: "string" } },
},
additionalProperties: false,
},
],
messages: {
noMixed:
'Isolation violation: "{{side}}" file imports "{{target}}" ({{targetRel}}).',
},
},
create(context) {
const options = context.options[0] || {};
const cwd = context.cwd;
const srcRoot = path.resolve(cwd, options.root || "src");
const alias = options.alias || { $lib: "lib" };
const oldPatterns = options.old || DEFAULT_OLD;
const newPatterns = options.new || DEFAULT_NEW;
/** Classify a path (already absolute or portable rel to srcRoot). */
function classify(absOrRel, relativeToRoot) {
const rel = relativeToRoot
? absOrRel
: toPortable(path.relative(srcRoot, absOrRel));
// new wins over old if a path is matched by both (e.g. components/kit
// is != lib/components/** via negation, but keep precedence safe).
if (matchesGlobList(newPatterns, rel)) return "new";
if (matchesGlobList(oldPatterns, rel)) return "old";
return "shared";
}
/** Resolve a specifier to a portable rel path from srcRoot, or null. */
function resolveToRel(spec, currentDir) {
if (spec.startsWith("$")) {
const dot = spec.indexOf("/");
const mapKey = spec.slice(0, dot === -1 ? spec.length : dot);
const dir = alias[mapKey];
if (!dir) return null;
const rest = dot === -1 ? "" : spec.slice(dot + 1);
const base = path.resolve(srcRoot, dir, rest);
const found = firstExisting(base);
if (!found) return null;
return toPortable(path.relative(srcRoot, found));
}
if (spec.startsWith("./") || spec.startsWith("../")) {
const base = path.resolve(currentDir, spec);
const found = firstExisting(base);
if (!found) return null;
const rel = path.relative(srcRoot, found);
if (rel.startsWith("..")) return null; // outside srcRoot
return toPortable(rel);
}
return null; // package import (svelte, vitest, @lucide, ...)
}
const filename = context.filename || context.physicalFilename;
const currentAbs = path.resolve(filename);
const currentRel = toPortable(path.relative(srcRoot, currentAbs));
const currentSide = classify(currentRel, true);
const currentDir = path.dirname(currentAbs);
if (currentSide === "shared") return {};
function checkSource(node) {
const spec = node.source?.value;
if (typeof spec !== "string") return;
const targetRel = resolveToRel(spec, currentDir);
if (!targetRel) return;
const targetSide = classify(targetRel, true);
if (
(currentSide === "old" && targetSide === "new") ||
(currentSide === "new" && targetSide === "old")
) {
context.report({
node,
messageId: "noMixed",
data: { side: currentSide, target: targetSide, targetRel },
});
}
}
return {
ImportDeclaration: checkSource,
ImportExpression: checkSource,
ExportNamedDeclaration: checkSource,
ExportAllDeclaration: checkSource,
};
},
};