289 lines
14 KiB
TypeScript
289 lines
14 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.
|
||
//
|
||
// 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.
|
||
// 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. Core prompts for agents and CLI output are not screens. */
|
||
export const GLOSSARY_ROOTS = ["apps/web/app", "apps/web/components", "apps/bot/src"];
|
||
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;
|
||
|
||
/** Texts of a .ts/.tsx source that reach the screen: JSX text, user-facing attributes, Cyrillic strings. */
|
||
export function sourceTexts(fileName: string, source: string): TextPiece[] {
|
||
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 visit = (node: ts.Node) => {
|
||
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) return;
|
||
if (ts.isJsxText(node)) 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)) add(node, node.text);
|
||
}
|
||
ts.forEachChild(node, visit);
|
||
};
|
||
visit(sf);
|
||
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): Violation[] {
|
||
if (IGNORE_FILE.test(source)) return [];
|
||
const lines = source.split("\n");
|
||
const pieces = file.endsWith(".json") ? jsonTexts(source) : sourceTexts(file, source);
|
||
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): 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 — only the screens; translation files — wherever they appear.
|
||
const files = new Set([...under(roots).filter(isSource), ...under(TRANSLATION_ROOTS).filter(isTranslation)]);
|
||
return [...files].sort().flatMap((file) => checkText(file, readFileSync(join(root, file), "utf8"), matcher));
|
||
}
|
||
|
||
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);
|
||
if (opts.update) {
|
||
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 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: <почему>`.");
|
||
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") }));
|
||
}
|