diff --git a/locales/de/common.json b/locales/de/common.json index 6f9071839..c1fc81494 100644 --- a/locales/de/common.json +++ b/locales/de/common.json @@ -44,7 +44,6 @@ "maps.mapPool": "Arenen-Pool", "maps.tournamentMaplist": "Arenen-Liste für Turnier erstellen (maps.iplabs.ink)", "maps.validation.TOO_MUCH_STAGE_REPEAT": "Arena kann nicht mehr als {{maxStageRepeat}} Mal ausgewählt werden", - "maps.validation.VALID": "Arenen-Pool ok!", "results": "Ergebnisse", "forms.name": "Name", "forms.description": "Beschreibung", diff --git a/locales/en/common.json b/locales/en/common.json index 38e0ba2da..580510264 100644 --- a/locales/en/common.json +++ b/locales/en/common.json @@ -266,7 +266,6 @@ "maps.validation.STAGE_REPEAT_IN_SAME_MODE": "Can't pick the same map twice in the same mode", "maps.validation.TOO_MUCH_STAGE_REPEAT": "Can't pick stage more than {{maxStageRepeat}} times", "maps.validation.NOT_IN_POOL": "Can't pick stages outside of the map pool", - "maps.validation.VALID": "Map pool ok!", "results": "Results", "forms.name": "Name", "forms.description": "Description", diff --git a/locales/en/tournament.json b/locales/en/tournament.json index 4c097f7c2..04831f306 100644 --- a/locales/en/tournament.json +++ b/locales/en/tournament.json @@ -265,7 +265,6 @@ "progression.error.SAME_PLACEMENT_TO_MULTIPLE_BRACKETS": "Same placement leads to multiple brackets", "progression.error.GAP_IN_PLACEMENTS": "Gap in placements that advance", "progression.error.TOO_MANY_PLACEMENTS": "Too many placements (more than teams in groups)", - "progression.error.PLACEMENT_TOO_HIGH": "Placement is too high (max {{max}})", "progression.error.DUPLICATE_BRACKET_NAME": "Duplicate bracket name", "progression.error.NAME_MISSING": "Bracket name missing", "progression.error.NEGATIVE_PROGRESSION": "Teams knocked out early can only move on from an elimination bracket", diff --git a/locales/es-ES/common.json b/locales/es-ES/common.json index cf70daea3..7616748b9 100644 --- a/locales/es-ES/common.json +++ b/locales/es-ES/common.json @@ -224,7 +224,6 @@ "maps.validation.STAGE_REPEAT_IN_SAME_MODE": "No se puede elegir el mismo escenario dos veces en el mismo modo", "maps.validation.TOO_MUCH_STAGE_REPEAT": "No se puede elegir un escenario más de {{maxStageRepeat}} veces", "maps.validation.NOT_IN_POOL": "No se pueden elegir escenarios fuera del grupo de mapas", - "maps.validation.VALID": "¡Grupo de mapas correcto!", "results": "Resultados", "forms.name": "Nombre", "forms.description": "Descripción", diff --git a/locales/es-ES/tournament.json b/locales/es-ES/tournament.json index ded900f89..398238ed5 100644 --- a/locales/es-ES/tournament.json +++ b/locales/es-ES/tournament.json @@ -262,7 +262,6 @@ "progression.error.SAME_PLACEMENT_TO_MULTIPLE_BRACKETS": "La misma posición lleva a varios brackets", "progression.error.GAP_IN_PLACEMENTS": "Hay un hueco en las posiciones que avanzan", "progression.error.TOO_MANY_PLACEMENTS": "Demasiadas posiciones (más que equipos en los grupos)", - "progression.error.PLACEMENT_TOO_HIGH": "La posición es demasiado alta (máximo {{max}})", "progression.error.DUPLICATE_BRACKET_NAME": "Nombre de bracket duplicado", "progression.error.NAME_MISSING": "Falta el nombre del bracket", "progression.error.MIXED_POSITIVE_NEGATIVE_PLACEMENTS": "Una fuente no puede mezclar posiciones que avanzan con equipos eliminados", diff --git a/locales/es-US/common.json b/locales/es-US/common.json index e27621293..7aa5a6e46 100644 --- a/locales/es-US/common.json +++ b/locales/es-US/common.json @@ -33,7 +33,6 @@ "maps.mapPool": "Grupo de escenarios", "maps.tournamentMaplist": "Crear lista de escenarios para torneo (maps.iplabs.ink)", "maps.validation.NOT_IN_POOL": "No se pueden elegir escenarios fuera del grupo de escenarios", - "maps.validation.VALID": "¡Grupo de escenarios correcto!", "forms.errors.title": "Los siguientes errores deben corregirse", "tag.name.MONEY": "Premios en efectivo", "tag.name.LOW": "Límite de habilidad", diff --git a/locales/fr-EU/common.json b/locales/fr-EU/common.json index bd9aaba9a..5886e02b0 100644 --- a/locales/fr-EU/common.json +++ b/locales/fr-EU/common.json @@ -182,7 +182,6 @@ "maps.tournamentMaplist": "Créer une liste de stages de tournoi (maps.iplabs.ink)", "maps.validation.STAGE_REPEAT_IN_SAME_MODE": "Impossible de choisir le même stage deux fois dans le même mode", "maps.validation.TOO_MUCH_STAGE_REPEAT": "Impossible de choisir le même stage plus de {{maxStageRepeat}} fois", - "maps.validation.VALID": "Liste de stages valide !", "results": "Résultats", "forms.name": "Nom", "forms.description": "Description", diff --git a/locales/ja/common.json b/locales/ja/common.json index 8a13e4916..bfb5e86bc 100644 --- a/locales/ja/common.json +++ b/locales/ja/common.json @@ -153,7 +153,6 @@ "maps.tournamentMaplist": "大会ステージリストを作る (maps.iplabs.ink)", "maps.validation.STAGE_REPEAT_IN_SAME_MODE": "同じルールで1回以上同じマップを選択できません", "maps.validation.TOO_MUCH_STAGE_REPEAT": "同じステージを {{maxStageRepeat}} 回以上選択できません", - "maps.validation.VALID": "ステージリストに問題はありません!", "results": "結果", "forms.name": "名前", "forms.description": "説明", diff --git a/locales/zh/common.json b/locales/zh/common.json index cace7055e..0c18352c5 100644 --- a/locales/zh/common.json +++ b/locales/zh/common.json @@ -155,7 +155,6 @@ "maps.tournamentMaplist": "创建赛事场地列表 (maps.iplabs.ink)", "maps.validation.STAGE_REPEAT_IN_SAME_MODE": "无法在相同模式下选择重复的场地", "maps.validation.TOO_MUCH_STAGE_REPEAT": "每个场地只能选择 {{maxStageRepeat}} 次", - "maps.validation.VALID": "场地池已完成!", "results": "结果", "forms.name": "名称", "forms.description": "简介", diff --git a/locales/zh/tournament.json b/locales/zh/tournament.json index b2ea741e1..6ff432fce 100644 --- a/locales/zh/tournament.json +++ b/locales/zh/tournament.json @@ -156,7 +156,6 @@ "progression.error.SAME_PLACEMENT_TO_MULTIPLE_BRACKETS": "相同的名次导向了多个对战表", "progression.error.GAP_IN_PLACEMENTS": "晋级名次之间存在断层", "progression.error.TOO_MANY_PLACEMENTS": "名次数量过多(超过了小组中的队伍总数)", - "progression.error.PLACEMENT_TOO_HIGH": "名次过高(最大值为 {{max}})", "progression.error.DUPLICATE_BRACKET_NAME": "对战表名称重复", "progression.error.NAME_MISSING": "缺少对战表名称", "progression.error.SWISS_EARLY_ADVANCE_NO_DESTINATION": "包含提前晋级/淘汰的瑞士轮对战表必须导向另一个对战表", diff --git a/scripts/generate-translation-usage.ts b/scripts/generate-translation-usage.ts index c1213ce0f..be7e688b5 100644 --- a/scripts/generate-translation-usage.ts +++ b/scripts/generate-translation-usage.ts @@ -2,11 +2,14 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { API, type Type } from "typescript/unstable/sync"; import { parseSync } from "vite"; // Generates the index of where each translation key is used (source files and the routes rendering them) // shown on the /translate page. Literal keys are matched exactly, template literals (t(`sorts.${x}`)) by -// their static parts and the route of a file is found by following imports from each route module. +// their static parts plus, when the TypeScript type of an interpolated value is a union of literals +// (t(`sorts.${sort}`) with sort: "A" | "B"), exactly those values. The route of a file is found by +// following imports from each route module. // With --check-unused it instead fails if a key of the English translations is used nowhere. const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,7 +38,15 @@ type ParsedFile = { imports: string[]; namespaces: string[]; literals: string[]; - templates: string[][]; + templates: Template[]; +}; + +type Template = { + quasis: string[]; + /** Where the type of each interpolated value can be asked from the type checker, null if not */ + expressionPositions: Array; + /** Possible values of each interpolated value, null if any string is possible */ + expressionValues: Array; }; const startedAt = performance.now(); @@ -44,6 +55,9 @@ const englishKeys = loadEnglishKeys(); const knownIds = knownIdsOf(englishKeys); const files = listSourceFiles(APP); const parsed = new Map(files.map((file) => [file, parseFile(file)])); +const isCheckingUnused = process.argv.includes("--check-unused"); +// costs seconds of type checking, the usage index can live with a few extra files listed for a key +if (isCheckingUnused) resolveTemplateExpressionValues(); const routes = flattenRoutes( (await import(pathToFileURL(path.join(APP, "routes.ts")).href)) @@ -68,8 +82,8 @@ for (const [file, { namespaces, literals, templates }] of parsed) { for (const literal of literals) { for (const id of matchLiteral(literal, namespaces)) ids.add(id); } - for (const parts of templates) { - for (const id of matchTemplate(parts, namespaces)) ids.add(id); + for (const template of templates) { + for (const id of matchTemplate(template, namespaces)) ids.add(id); } if (ids.size === 0) continue; @@ -89,7 +103,7 @@ for (const entry of Object.values(usage)) { entry.r.sort((a, b) => a - b); } -if (process.argv.includes("--check-unused")) { +if (isCheckingUnused) { const unusedKeys = findUnusedKeys(); if (unusedKeys.length > 0) { console.error( @@ -177,14 +191,17 @@ function matchLiteral(literal: string, fileNamespaces: string[]): string[] { .map((namespace) => `${namespace}:${literal}`); } -function matchTemplate(parts: string[], fileNamespaces: string[]): string[] { - const separatorIdx = parts[0].indexOf(":"); - const explicitNamespace = parts[0].slice(0, separatorIdx); +function matchTemplate( + { quasis, expressionValues }: Template, + fileNamespaces: string[], +): string[] { + const separatorIdx = quasis[0].indexOf(":"); + const explicitNamespace = quasis[0].slice(0, separatorIdx); const hasExplicitNamespace = separatorIdx !== -1 && knownIds.has(explicitNamespace); const idParts = hasExplicitNamespace - ? [parts[0].slice(separatorIdx + 1), ...parts.slice(1)] - : parts; + ? [quasis[0].slice(separatorIdx + 1), ...quasis.slice(1)] + : quasis; const staticPart = idParts.join(""); let namespaces = fileNamespaces; @@ -201,7 +218,16 @@ function matchTemplate(parts: string[], fileNamespaces: string[]): string[] { } const pattern = new RegExp( - `^${idParts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".+")}$`, + `^${idParts + .map((part, i) => { + if (i === 0) return escapeRegExp(part); + const values = expressionValues[i - 1]; + const expression = values + ? `(?:${values.map(escapeRegExp).join("|")})` + : ".+"; + return `${expression}${escapeRegExp(part)}`; + }) + .join("")}$`, ); return namespaces.flatMap((namespace) => @@ -211,6 +237,68 @@ function matchTemplate(parts: string[], fileNamespaces: string[]): string[] { ); } +function escapeRegExp(text: string) { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Asks the type checker what each interpolated identifier or property (`${sort}`, `${build.mode}`) can be */ +function resolveTemplateExpressionValues() { + const api = new API({ cwd: ROOT }); + try { + const project = api + .updateSnapshot({ openProjects: [path.join(ROOT, "tsconfig.json")] }) + .getProjects()[0]; + + for (const [file, { namespaces, templates }] of parsed) { + // checking a file is the slow part, skip those whose templates can't be a key anyway + const keyTemplates = templates.filter( + (template) => matchTemplate(template, namespaces).length > 0, + ); + const positions = keyTemplates + .flatMap((template) => template.expressionPositions) + .filter((position) => position !== null); + if (positions.length === 0) continue; + + const types = project.checker.getTypeAtPosition( + path.join(APP, file), + positions, + ); + const valuesByPosition = new Map( + positions.map((position, i) => [position, literalValues(types[i])]), + ); + for (const template of keyTemplates) { + template.expressionValues = template.expressionPositions.map( + (position) => + position === null ? null : (valuesByPosition.get(position) ?? null), + ); + } + } + } finally { + api.close(); + } +} + +function literalValues(type: Type | undefined): string[] | null { + if (!type) return null; + + const members = type.isUnionType() ? (type.getTypes() ?? []) : [type]; + if (members.length === 0) return null; + + const values: string[] = []; + for (const member of members) { + if ( + !member.isStringLiteralType() && + !member.isNumberLiteralType() && + !member.isBooleanLiteralType() + ) { + return null; + } + values.push(String(member.value)); + } + + return values; +} + function listSourceFiles(dir: string): string[] { return fs .readdirSync(dir, { recursive: true, encoding: "utf8" }) @@ -291,9 +379,11 @@ function parseFile(file: string): ParsedFile { if (n.expressions.length === 0) { result.literals.push(n.quasis[0].value.cooked); } else { - result.templates.push( - n.quasis.map((quasi: any) => quasi.value.cooked), - ); + result.templates.push({ + quasis: n.quasis.map((quasi: any) => quasi.value.cooked), + expressionPositions: n.expressions.map(typeLookupPosition), + expressionValues: n.expressions.map(() => null), + }); } break; case "TSTypeAnnotation": @@ -316,6 +406,19 @@ function parseFile(file: string): ParsedFile { return result; } +function typeLookupPosition(expression: any): number | null { + if (expression.type === "Identifier") return expression.start; + if ( + expression.type === "MemberExpression" && + !expression.computed && + !expression.optional + ) { + return expression.property.start; + } + + return null; +} + function stringValues(node: any): string[] { if (!node) return []; if (node.type === "Literal" && typeof node.value === "string") { diff --git a/scripts/living-docs/package-scripts.ts b/scripts/living-docs/package-scripts.ts index aa82b75c5..d64c1d0c0 100644 --- a/scripts/living-docs/package-scripts.ts +++ b/scripts/living-docs/package-scripts.ts @@ -62,7 +62,7 @@ const DESCRIPTIONS: Record = { "check-translation-sync": "Fails when the translation jsons are out of sync with English", "check-unused-translations": - "Fails when an English translation key is used nowhere in app/, matched like the `i18n:usage` index", + "Fails when an English translation key is used nowhere in app/, matched like the `i18n:usage` index but with template literal keys narrowed by the TypeScript types of their interpolated values", checks: "Everything CI checks: lint, unit and browser tests, translations, type checks, knip and the docs build, the read-only ones in parallel. A task isn't done until it passes", "checks:scanner": "`checks` plus the scanner tests",