343 lines
18 KiB
TypeScript
343 lines
18 KiB
TypeScript
// PEP-124: the glossary check. Reads the «Нельзя» column of docs/glossary.md, collects the texts
|
||
// a person sees on the screens (JSX text, user-facing attributes, Cyrillic string literals,
|
||
// translation files) and fails when a forbidden word shows up — with the file, the line, the word
|
||
// and what to write instead.
|
||
//
|
||
// PEP-129: messages built outside the screens (Telegram notifications, chat events, the digest —
|
||
// packages/core, packages/runner, packages/mcp) are checked too. Those files also hold prompts for
|
||
// agents and output for developers, so only the texts marked as «for a person» count there:
|
||
// m("…") / tr("…") / t("…") / t.n(…) — the translation-dictionary mark (PEP-98)
|
||
// // glossary-user: <why> — this line and the next one (a text that skips the dictionary)
|
||
// // glossary-user-file: <why> — the whole file is read like a screen
|
||
//
|
||
// pnpm lint check (exit 1 on a new forbidden word)
|
||
// pnpm lint --update rewrite the list of old debts
|
||
//
|
||
// Old debts live in docs/glossary-baseline.json (file → word → count): the check fails only when
|
||
// a file has more occurrences of a word than recorded there, so the list can only shrink.
|
||
// PEP-137: the list holds screens only — files of packages/core, packages/runner and packages/mcp
|
||
// are never recorded there, a forbidden word in a message fails the check at once.
|
||
// A text that is shown in «Инженер» mode only is marked in the source:
|
||
// // glossary-ignore: <why> — this line and the next one
|
||
// // glossary-ignore-file: <why> — the whole file
|
||
// The same mark fits a word used in its everyday meaning («команда агентов» is not a terminal command).
|
||
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||
import { join, relative, resolve, sep } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import ts from "typescript";
|
||
|
||
export type GlossaryRule = { concept: string; write: string; forbidden: string[]; allowed: string[] };
|
||
export type Violation = { file: string; line: number; word: string; found: string; write: string; text: string };
|
||
export type Baseline = Record<string, Record<string, number>>;
|
||
|
||
/** Where the texts of the product live: every Cyrillic string there is a text on a screen. */
|
||
export const GLOSSARY_ROOTS = ["apps/web/app", "apps/web/components", "apps/bot/src"];
|
||
/** Where messages are built next to prompts for agents and developer output: only marked texts count. */
|
||
export const MESSAGE_ROOTS = ["packages/core/src", "packages/runner/src", "packages/mcp/src"];
|
||
/** How a source file is read: `screen` — every text; `messages` — only texts marked as «for a person». */
|
||
export type TextMode = "screen" | "messages";
|
||
export const TRANSLATION_ROOTS = ["apps", "packages"];
|
||
export const GLOSSARY_FILE = "docs/glossary.md";
|
||
export const BASELINE_FILE = "docs/glossary-baseline.json";
|
||
|
||
const cells = (line: string) =>
|
||
line
|
||
.trim()
|
||
.replace(/^\||\|$/g, "")
|
||
.split("|")
|
||
.map((c) => c.trim());
|
||
const terms = (cell: string) =>
|
||
cell
|
||
.split(",")
|
||
.map((t) => t.trim())
|
||
.filter((t) => t && !/^[—–-]+$/.test(t));
|
||
|
||
/** Rows of the table «Понятие | Пишем | Нельзя | Пояснение». */
|
||
export function parseGlossary(markdown: string): GlossaryRule[] {
|
||
const rules: GlossaryRule[] = [];
|
||
let cols: { concept: number; write: number; forbidden: number } | null = null;
|
||
for (const line of markdown.split("\n")) {
|
||
if (!line.trim().startsWith("|")) {
|
||
cols = null;
|
||
continue;
|
||
}
|
||
const row = cells(line);
|
||
if (!cols) {
|
||
const forbidden = row.indexOf("Нельзя");
|
||
if (forbidden >= 0) cols = { concept: Math.max(row.indexOf("Понятие"), 0), write: row.indexOf("Пишем"), forbidden };
|
||
continue;
|
||
}
|
||
if (row.every((c) => /^:?-+:?$/.test(c))) continue;
|
||
const write = cols.write >= 0 ? (row[cols.write] ?? "") : "";
|
||
rules.push({ concept: row[cols.concept] ?? "", write, forbidden: terms(row[cols.forbidden] ?? ""), allowed: terms(write) });
|
||
}
|
||
if (!rules.some((r) => r.forbidden.length)) throw new Error("В словаре нет таблицы с колонкой «Нельзя»");
|
||
return rules;
|
||
}
|
||
|
||
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
const CONSONANT = /[бвгджзклмнпрстфхцчшщ]$/i;
|
||
|
||
/** Russian case forms of a noun, by its ending: «раннер» → раннера, раннеров…; «ветка» → ветки, веток. */
|
||
export function wordForms(word: string): string[] {
|
||
const w = word;
|
||
const cyr = /[а-яё]$/i.test(w) && w.length >= 3;
|
||
if (!cyr || /(ть|ться)$/i.test(w)) return [w];
|
||
const with_ = (stem: string, ends: string[]) => [...new Set([w, ...ends.map((e) => stem + e)])];
|
||
const hard = ["", "а", "у", "ом", "ем", "е", "ы", "и", "ов", "ей", "ам", "ами", "ах"];
|
||
if (/ия$/i.test(w)) return with_(w.slice(0, -1), ["я", "и", "ю", "ей", "й", "е", "ем", "ям", "ями", "ях"]);
|
||
if (/[аеиоу]й$/i.test(w)) return with_(w.slice(0, -1), ["й", "я", "ю", "ё", "е", "ем", "и", "ев", "ям", "ями", "ях"]);
|
||
if (/ь$/i.test(w)) return with_(w.slice(0, -1), ["ь", "и", "я", "ю", "ью", "ем", "ей", "ям", "ями", "ях"]);
|
||
if (/а$/i.test(w)) {
|
||
const stem = w.slice(0, -1);
|
||
const forms = with_(stem, ["а", "ы", "и", "е", "у", "ой", "ою", "", "ам", "ами", "ах"]);
|
||
// «ветка» → «веток», «выкатка» → «выкаток».
|
||
if (/[бвгджзлмнпрстфхцчшщ]к$/i.test(stem)) forms.push(`${stem.slice(0, -1)}ок`, `${stem.slice(0, -1)}ек`);
|
||
return forms;
|
||
}
|
||
// A plural in the glossary («токены», «инциденты»): the singular is forbidden as well.
|
||
if (w.length >= 5 && (/[бвгджзклмнпрстфхцчшщ]ы$/i.test(w) || /[гкхжчшщ]и$/i.test(w))) return with_(w.slice(0, -1), hard);
|
||
if (CONSONANT.test(w)) return with_(w, hard);
|
||
return [w];
|
||
}
|
||
|
||
const EDGE_BEFORE = "(?<![\\p{L}\\p{N}_])";
|
||
const EDGE_AFTER = "(?![\\p{L}\\p{N}_])";
|
||
|
||
/** A term of the glossary as a regular expression: whole words, any case (acronyms — exact case). */
|
||
export function termRegExp(term: string): RegExp {
|
||
if (!/[\p{L}\p{N}]/u.test(term)) return new RegExp(esc(term), "gu");
|
||
let body: string;
|
||
if (/\s/.test(term)) {
|
||
body = term.split(/\s+/).map(esc).join("\\s+");
|
||
} else {
|
||
// «API-ключ», «превью-стенд»: the last part declines.
|
||
const cut = term.lastIndexOf("-") + 1;
|
||
body = `${esc(term.slice(0, cut))}(?:${wordForms(term.slice(cut)).map(esc).join("|")})`;
|
||
}
|
||
const flags = /^[A-Z]{2,}$/.test(term) ? "gu" : "giu";
|
||
return new RegExp(`${/^[\p{L}\p{N}_]/u.test(term) ? EDGE_BEFORE : ""}${body}${/[\p{L}\p{N}_]$/u.test(term) ? EDGE_AFTER : ""}`, flags);
|
||
}
|
||
|
||
export type Matcher = { find(text: string): { word: string; found: string; index: number; write: string }[] };
|
||
|
||
export function glossaryMatcher(rules: GlossaryRule[]): Matcher {
|
||
const forbidden = rules.flatMap((r) => r.forbidden.map((word) => ({ word, write: r.write, re: termRegExp(word) })));
|
||
// «Peppa FACTORY» is what we write although «Peppa» alone is forbidden: such phrases are
|
||
// blanked out before the search.
|
||
const allowed = rules
|
||
.flatMap((r) => r.allowed)
|
||
.filter((phrase) => forbidden.some((f) => new RegExp(f.re.source, f.re.flags).test(phrase)))
|
||
.map(termRegExp);
|
||
return {
|
||
find(text) {
|
||
let clean = text;
|
||
for (const re of allowed) clean = clean.replace(re, (m) => " ".repeat(m.length));
|
||
const hits: { word: string; found: string; index: number; write: string }[] = [];
|
||
for (const f of forbidden) {
|
||
for (const m of clean.matchAll(f.re)) hits.push({ word: f.word, found: m[0], index: m.index, write: f.write });
|
||
}
|
||
// «pull request» also contains nothing shorter, but «merge request» ⊃ … — keep the longest hit per place.
|
||
hits.sort((a, b) => a.index - b.index || b.found.length - a.found.length);
|
||
const out: typeof hits = [];
|
||
let end = -1;
|
||
for (const h of hits) {
|
||
if (h.index < end) continue;
|
||
out.push(h);
|
||
end = h.index + h.found.length;
|
||
}
|
||
return out;
|
||
},
|
||
};
|
||
}
|
||
|
||
export type TextPiece = { line: number; text: string };
|
||
|
||
const VISIBLE_ATTRS = new Set(["title", "placeholder", "alt", "aria-label", "label", "description", "hint"]);
|
||
const CYRILLIC = /[а-яё]/i;
|
||
|
||
// The calls that mark a text for the translation dictionary (scripts/i18n-check.ts knows the same names).
|
||
const USER_TEXT_CALL = /^(t|m|tr|tn)$|\.(t|m|n)$/;
|
||
const calleeName = (e: ts.Expression): string => (ts.isIdentifier(e) ? e.text : ts.isPropertyAccessExpression(e) ? `${calleeName(e.expression)}.${e.name.text}` : "");
|
||
const USER_FILE = /glossary-user-file/;
|
||
const USER_LINE = /glossary-user(?!-file)/;
|
||
|
||
/**
|
||
* Texts of a .ts/.tsx source that reach a person. `screen`: JSX text, user-facing attributes, Cyrillic
|
||
* strings. `messages`: the same, but only inside `m()`/`tr()`/`t()`/`t.n()` calls (every string in the
|
||
* arguments, values of placeholders included) and on lines marked `glossary-user`.
|
||
*/
|
||
export function sourceTexts(fileName: string, source: string, mode: TextMode = "screen"): TextPiece[] {
|
||
const all = mode === "screen" || USER_FILE.test(source);
|
||
const lines = all ? [] : source.split("\n");
|
||
const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
||
const out: TextPiece[] = [];
|
||
// JSX text keeps its leading line breaks, so its lines are counted from the raw start.
|
||
const add = (node: ts.Node, text: string) => {
|
||
const start = ts.isJsxText(node) ? node.pos : node.getStart(sf);
|
||
if (text.trim()) out.push({ line: sf.getLineAndCharacterOfPosition(start).line + 1, text });
|
||
};
|
||
const userLine = (node: ts.Node) => {
|
||
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line;
|
||
return USER_LINE.test(lines[line] ?? "") || USER_LINE.test(lines[line - 1] ?? "");
|
||
};
|
||
const visit = (node: ts.Node, marked: boolean) => {
|
||
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) return;
|
||
if (!marked && ts.isCallExpression(node) && USER_TEXT_CALL.test(calleeName(node.expression))) {
|
||
visit(node.expression, false);
|
||
for (const arg of node.arguments) visit(arg, true);
|
||
return;
|
||
}
|
||
if (ts.isJsxText(node)) {
|
||
if (marked) add(node, node.text);
|
||
} else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) {
|
||
const attr = ts.isJsxAttribute(node.parent) && VISIBLE_ATTRS.has(node.parent.name.getText(sf));
|
||
if ((attr || CYRILLIC.test(node.text)) && (marked || userLine(node))) add(node, node.text);
|
||
}
|
||
ts.forEachChild(node, (child) => visit(child, marked));
|
||
};
|
||
visit(sf, all);
|
||
return out;
|
||
}
|
||
|
||
/** Every string of a translation file (messages/ru.json and the like). */
|
||
export function jsonTexts(source: string): TextPiece[] {
|
||
const out: TextPiece[] = [];
|
||
const lines = source.split("\n");
|
||
const walk = (v: unknown) => {
|
||
if (typeof v === "string") {
|
||
const needle = JSON.stringify(v).slice(1, -1);
|
||
const at = lines.findIndex((l) => l.includes(needle));
|
||
out.push({ line: at < 0 ? 1 : at + 1, text: v });
|
||
} else if (v && typeof v === "object") Object.values(v).forEach(walk);
|
||
};
|
||
walk(JSON.parse(source));
|
||
return out;
|
||
}
|
||
|
||
const IGNORE_FILE = /glossary-ignore-file/;
|
||
const IGNORE_LINE = /glossary-ignore(?!-file)/;
|
||
|
||
/** Forbidden words in one file. `file` is the path shown in the report. */
|
||
export function checkText(file: string, source: string, matcher: Matcher, mode: TextMode = "screen"): Violation[] {
|
||
if (IGNORE_FILE.test(source)) return [];
|
||
const lines = source.split("\n");
|
||
const pieces = file.endsWith(".json") ? jsonTexts(source) : sourceTexts(file, source, mode);
|
||
const out: Violation[] = [];
|
||
for (const piece of pieces) {
|
||
for (const hit of matcher.find(piece.text)) {
|
||
const line = piece.line + piece.text.slice(0, hit.index).split("\n").length - 1;
|
||
if (IGNORE_LINE.test(lines[line - 1] ?? "") || IGNORE_LINE.test(lines[line - 2] ?? "")) continue;
|
||
out.push({ file, line, word: hit.word, found: hit.found, write: hit.write, text: (lines[line - 1] ?? "").trim().slice(0, 160) });
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const isTranslation = (path: string) => /(^|\/)(messages|locales|i18n|translations)\/.*\.json$/.test(path);
|
||
const isSource = (path: string) => /\.tsx?$/.test(path) && !/\.(test|d)\.ts$/.test(path);
|
||
|
||
function walk(dir: string, out: string[]) {
|
||
for (const name of readdirSync(dir).sort()) {
|
||
if (name === "node_modules" || name.startsWith(".")) continue;
|
||
const path = join(dir, name);
|
||
if (statSync(path).isDirectory()) walk(path, out);
|
||
else out.push(path);
|
||
}
|
||
}
|
||
|
||
/** All forbidden words under the roots of a checkout. */
|
||
export function scanGlossary(root: string, roots = GLOSSARY_ROOTS, glossaryFile = GLOSSARY_FILE, messageRoots = MESSAGE_ROOTS): Violation[] {
|
||
const matcher = glossaryMatcher(parseGlossary(readFileSync(join(root, glossaryFile), "utf8")));
|
||
const rel = (path: string) => relative(root, path).split(sep).join("/");
|
||
const under = (dirs: string[]) => {
|
||
const files: string[] = [];
|
||
for (const d of dirs) if (existsSync(join(root, d))) walk(join(root, d), files);
|
||
return files.map(rel);
|
||
};
|
||
// Sources — the screens and the marked texts of the messages; translation files — wherever they appear.
|
||
const screens = new Set([...under(roots).filter(isSource), ...under(TRANSLATION_ROOTS).filter(isTranslation)]);
|
||
const messages = under(messageRoots).filter((f) => isSource(f) && !screens.has(f));
|
||
return [...screens, ...messages]
|
||
.sort()
|
||
.flatMap((file) => checkText(file, readFileSync(join(root, file), "utf8"), matcher, screens.has(file) ? "screen" : "messages"));
|
||
}
|
||
|
||
export function countViolations(violations: Violation[]): Baseline {
|
||
const counts: Baseline = {};
|
||
for (const v of violations) {
|
||
const file = (counts[v.file] ??= {});
|
||
file[v.word] = (file[v.word] ?? 0) + 1;
|
||
}
|
||
return counts;
|
||
}
|
||
|
||
/** Violations above the recorded old debts: every occurrence of a word in a file that has more of it than before. */
|
||
export function newViolations(violations: Violation[], baseline: Baseline): Violation[] {
|
||
const counts = countViolations(violations);
|
||
return violations.filter((v) => (counts[v.file]?.[v.word] ?? 0) > (baseline[v.file]?.[v.word] ?? 0));
|
||
}
|
||
|
||
/** One file per line, sorted: parallel changes rarely touch the same line. */
|
||
export function formatBaseline(baseline: Baseline): string {
|
||
const files = Object.keys(baseline).sort();
|
||
const rows = files.map((f) => {
|
||
const words = Object.keys(baseline[f]!).sort();
|
||
return ` ${JSON.stringify(f)}: {${words.map((w) => `${JSON.stringify(w)}: ${baseline[f]![w]}`).join(", ")}}`;
|
||
});
|
||
return `{\n${rows.join(",\n")}\n}\n`;
|
||
}
|
||
|
||
export function formatViolation(v: Violation, baseline: Baseline = {}): string {
|
||
const old = baseline[v.file]?.[v.word] ?? 0;
|
||
const debt = old ? ` (в файле было ${old} — стало больше)` : "";
|
||
const write = v.write ? ` Пишем: ${v.write}.` : "";
|
||
return `${v.file}:${v.line}: слово «${v.found}» нельзя показывать пользователю (словарь: «${v.word}»)${debt}.${write}\n ${v.text}`;
|
||
}
|
||
|
||
export function runGlossaryCheck(root: string, opts: { update?: boolean; log?: (line: string) => void } = {}): number {
|
||
const log = opts.log ?? console.log;
|
||
const baselinePath = join(root, BASELINE_FILE);
|
||
const all = scanGlossary(root);
|
||
// PEP-137: messages have no list of old debts — a forbidden word there always fails, and
|
||
// `--update` does not record it.
|
||
const inMessages = (file: string) => MESSAGE_ROOTS.some((dir) => file.startsWith(`${dir}/`));
|
||
const noDebt = all.filter((v) => inMessages(v.file));
|
||
const failMessages = (recorded: string[]) => {
|
||
for (const v of noDebt) log(formatViolation(v));
|
||
for (const file of recorded) log(`${BASELINE_FILE}: файл ${file} в списке старых долгов — для сообщений долгов нет, уберите запись.`);
|
||
log("");
|
||
log(`glossary: FAIL — запрещённых слов: ${noDebt.length}. Для сообщений (${MESSAGE_ROOTS.join(", ")}) старые долги не записываются.`);
|
||
log("Замените слово словом из колонки «Пишем» или, если текст читает только инженер, пометьте строку `glossary-ignore: <почему>`.");
|
||
return 1;
|
||
};
|
||
if (opts.update) {
|
||
if (noDebt.length) return failMessages([]);
|
||
writeFileSync(baselinePath, formatBaseline(countViolations(all)));
|
||
log(`glossary: список старых долгов обновлён — ${all.length} в ${new Set(all.map((v) => v.file)).size} файлах (${BASELINE_FILE})`);
|
||
return 0;
|
||
}
|
||
const baseline: Baseline = existsSync(baselinePath) ? JSON.parse(readFileSync(baselinePath, "utf8")) : {};
|
||
const recorded = Object.keys(baseline).filter(inMessages);
|
||
if (noDebt.length || recorded.length) return failMessages(recorded);
|
||
const fresh = newViolations(all, baseline);
|
||
if (fresh.length) {
|
||
for (const v of fresh) log(formatViolation(v, baseline));
|
||
log("");
|
||
log(`glossary: FAIL — запрещённых слов: ${fresh.length}. Замените их словами из колонки «Пишем» ${GLOSSARY_FILE}.`);
|
||
log("Текст виден только в режиме «Инженер» или слово стоит в другом значении — пометьте строку комментарием `glossary-ignore: <почему>`.");
|
||
log("Подсказки агентам в packages/* не проверяются: в `m()` оборачивается только текст для человека.");
|
||
return 1;
|
||
}
|
||
const counts = countViolations(all);
|
||
const paid = Object.entries(baseline).flatMap(([f, words]) => Object.entries(words).filter(([w, n]) => (counts[f]?.[w] ?? 0) < n));
|
||
log(`glossary: ok — новых запрещённых слов нет (старых долгов: ${all.length})`);
|
||
if (paid.length) log(`glossary: долгов стало меньше — зафиксируйте: pnpm lint --update`);
|
||
return 0;
|
||
}
|
||
|
||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||
const root = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
process.exit(runGlossaryCheck(root, { update: process.argv.includes("--update") }));
|
||
}
|