rob-revisited/ide/ui/js/i18n.test.mjs

114 lines
11 KiB
JavaScript

// Every IDE text that goes through t() / tr() (and the label tables of IDE Remote) must be translated in the 13 other languages.
// Run: docker run --rm -v $PWD:/w -w /w node:22-alpine node --test ide/ui/js/i18n.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const LANGS = ['fr', 'es', 'de', 'it', 'pt', 'nl', 'pl', 'ru', 'uk', 'tr', 'ja', 'zh', 'ko'];
// the same word in the language is fine
const SAME_OK = new Set(['Cookies', 'Snippets', 'Parameters', 'Variables: {names}', 'Request body', 'download', '{passed}/{total} tests', '{n} h', 'Section', 'Arguments', 'Options', 'argument', 'Argument', 'option', 'Option', 'Body', 'Context', 'Context (#[AsContext])', 'Note', 'Question', 'Style', 'Help', 'Tests', 'Output', 'Arguments…', 'Port', 'Servers', 'Remote', 'Terminal', 'Panel', 'Conflict', 'Claude', 'Update', 'Tutorial', 'Recent', 'Documentation', 'Debug', 'Debugger', 'Later', 'version {v}', 'Profiler', 'File', 'N frames', 'per frame', 'OK', 'Variables', 'Commit', 'Push', 'Notifications', 'Account', 'Preview', 'Watches', 'Exceptions', 'Commit (Ctrl+K)', 'Push (Ctrl+Shift+K)', 'Breakpoints ({n})', 'Test (Ctrl+Shift+F10)', 'Docker', 'Database', 'Docker Hub', 'Composer', 'Packagist', 'Artisan', 'Console', 'CPU', 'Logs', 'Tags', 'Image', 'Images', 'Version', 'Code', 'Scripts', 'Amstrad CPC', 'Sprites', 'Desktop', 'Offset', 'Stars', 'Pull', 'Description', 'Board', 'Checklist', 'Local', 'Notes', 'Pull request', 'Color', 'Issue', 'Description (Markdown)', 'Link', 'Extra', 'Host', 'Password', 'Routines', 'Tables', 'Unique', 'no', 'production', 'table', 'via SSH', '(optional)', 'Type', 'Structure', 'Error', '{count} images', 'base', 'Engine', 'Logs: {name}', 'optional', 'Name', 'local', 'Variable', 'Secret', 'Options', 'Driver', 'services {names} ({file})']);
// the Doctrine window (doctrine.js): the same word in several languages
for (const k of ['(in {file})', 'Namespace', 'PHP enum', 'Migrations', 'abstract', 'Relations', 'Diagram', 'Mapping', 'Joins', 'discriminator', 'Repository: {name}', '+ Join…', 'Classes', 'Types: {types}', 'PHP enum…', 'Property in {name}', 'Enum', 'Nullable', 'Layout', 'Repository', 'Relation…']) SAME_OK.add(k);
const EXTRA = ['Restart Now', 'Install', 'Later', 'This conversation is open in the Terminal (Remote Control): write there, or close that Terminal tab to use the panel again. Only one Claude works on a session.']; // + the server message shown through tr()
// (Restart Now / Install / Later are notification button labels, translated by notify())
const unescape = (s) => s.replace(/\\(['"\\])/g, '$1');
function keysOf(file) {
const src = readFileSync(join(here, file), 'utf8');
const keys = new Set();
for (const m of src.matchAll(/\b(?:t|tr)\(\s*'((?:[^'\\\n]|\\.)*)'/g)) keys.add(unescape(m[1]));
for (const m of src.matchAll(/\b(?:t|tr)\(\s*"((?:[^"\\\n]|\\.)*)"/g)) keys.add(unescape(m[1]));
return keys;
}
function tableKeys() {
const keys = new Set();
const share = readFileSync(join(here, 'remote-share.js'), 'utf8');
for (const name of ['SCOPE_OPTIONS', 'MODE_OPTIONS']) {
const block = share.match(new RegExp(`const ${name} = \\[([\\s\\S]*?)\\n\\];`))[1];
for (const m of block.matchAll(/\['[a-z]+', '((?:[^'\\]|\\.)*)'\]/g)) keys.add(unescape(m[1]));
}
const host = readFileSync(join(here, 'remote-host.js'), 'utf8');
const labels = host.match(/SCOPE_LABELS = \{([^}]*)\}/)[1];
for (const m of labels.matchAll(/: '((?:[^'\\]|\\.)*)'/g)) keys.add(unescape(m[1]));
return keys;
}
const files = ['app.js', 'symfony-forms.js', 'claude.js', 'remote-host.js', 'remote-share.js', 'welcome.js', 'ui.js', 'editor.js', 'plugins.js', 'debug.js', 'var-tree.js', 'hover-inspect.js', 'profiler.js', 'flame.js', 'zoom.js', 'board.js', 'ssh.js', 'docker.js', 'scripts.js', 'db.js', 'css-designer.js', 'dotenv.js', 'tests.js', 'gutter-run.js', 'command-wizard.js', 'docs-browser.js', 'http-client.js', 'openapi.js'];
files.push('tutorial/tour-ui.js', 'tutorial/tutorial.js'); // the interactive tutorial's panel and dialogs (the steps' own texts are English + French data)
files.push('doctrine.js', 'sql-builder.js', 'schema-check.js');
SAME_OK.add('Database OK'); // the Doctrine window, the Database window's visual SQL builder
// Debug / Run texts that reach t() through a table or a menu (menu(), action labels, the titles of index.html, dialog buttons), not a t('...') literal
const MENU_KEYS = ['Edit Condition…', 'Add Breakpoint', 'Remove Breakpoint', 'Copy as JSON', 'Copy as PHP code', 'Set Value…', 'Add to Watches', 'the program ended first', 'nothing after 3 minutes',
'Run Tests', 'Take a Screenshot', 'Run Tool Window', 'Run Configurations…', 'Run Anything… (bin/jumphp)', 'Debug with… (Xdebug / PHP Debugger)', 'Resume Program', 'Step Over', 'Step Into', 'Step Out',
'Toggle Line Breakpoint', 'Debug Tool Window', 'Run Tests on jumphp.net', 'Cancel', 'OK', 'Save', 'Watches', 'Variables', 'Call Stack', 'Evaluate', 'Edit', 'Resume', 'Debug with…', 'Copy', 'Hide', 'Nothing found', 'Increase Font Size', 'Decrease Font Size', 'Reset Font Size', 'Reset All Zoom', 'Zoom In the Whole IDE', 'Zoom Out the Whole IDE', 'Reset the Whole IDE Zoom',
...[...readFileSync(join(here, '..', 'index.html'), 'utf8').matchAll(/title="([^"]*)"/g)].map((m) => m[1].replace(/&/g, '&')).filter((k) => k !== 'Debug (Shift+F9): click for the debugger menu')];
// the Symfony Events / Messenger windows: their files, and the words that read the same in some languages
files.push('symfony-events.js', 'messenger.js');
// the Translations window
files.push('translations.js');
for (const k of ['source', 'Model', 'Term', 'Tip', 'service', 'resolver', 'upload', 'header', 'request', 'Collection {name}']) SAME_OK.add(k);
// the Validation and Security windows (Symfony's own words read the same in several languages)
files.push('symfony-validation.js', 'symfony-security.js', 'symfony-diff.js');
for (const k of ['Dates', 'Finance', 'Collections', 'Validation', 'getter', 'Route', 'Voter', 'Firewalls', 'Roles', 'Firewall: {name}', 'Constraint (NotBlank, Length, Email…)', 'Constraints', 'Hasher', 'Namespace', 'project', 'Constraint + validator', 'Providers', 'JWT API']) SAME_OK.add(k);
for (const k of ['Diff', 'Events', 'Listeners', 'type (int, string, App\\Entity\\Order…)', 'Transports', 'code {code}', 'auto', 'Message', 'Messages', 'Transport', 'Routing', 'Route', 'Handler', 'Start', 'Restart']) SAME_OK.add(k);
// the Bootstrap editor (bootstrap-editor.js, bootstrap-support.js): CSS words that read the same in every language
files.push('bootstrap-editor.js', 'bootstrap-support.js');
// the Security Audit window (security-audit.js): rule texts marked with tr()
files.push('security-audit.js');
// the API Platform window (api-platform.js): its field labels and section titles reach t() through tables, not t('...') literals
files.push('api-platform.js', 'api-install.js');
for (const k of ['Routes', 'Pagination', 'Formats', 'Filters', 'Resource', 'Resource…', 'Subresource', 'State provider', 'State processor', 'API Platform…', '{n} routes']) SAME_OK.add(k);
const API_KEYS = ['Short name', 'URI variables (links)', 'Normalization groups (read)', 'Denormalization groups (write)', 'Security (expression)', 'Security after denormalization', 'Security message', 'Items per page', 'The client can turn pagination on or off', 'The client can set the items per page', 'Most items per page', 'Default order', 'State provider', 'State processor', 'Input class (false: none)', 'Output class (false: none)', 'Serialization and validation', 'Formats and order', 'Resource…'];
for (const k of ['info', 'Total', 'AI', 'Date', 'Status', 'Injection', 'Vulnerable', 'Server-Side Request Forgery', 'AI: {verdict}']) SAME_OK.add(k);
for (const k of ['Float', 'Overflow', 'Grow', 'Gap', 'Flex', 'Direction', 'Position', 'Text', 'Utilities', 'Gutter', 'Padding', 'Transform', 'Grid', 'Display', 'Components', 'Size', 'Style', 'Offset', 'Order', 'Ask']) SAME_OK.add(k);
// the New… hub (new-hub.js): its groups and entries are table rows, not t('...') literals
const hubSrc = readFileSync(join(here, 'new-hub.js'), 'utf8');
const HUB_KEYS = [...hubSrc.matchAll(/, '([A-Z][A-Za-z ]+)', '([^']+)', '[a-z]+', /g)].flatMap((m) => [m[1], m[2]]).concat([...hubSrc.match(/GROUPS = \[([^\]]*)\]/)[1].matchAll(/'([^']+)'/g)].map((m) => m[1]), ['New…', 'What do you want to create?', 'Template name (home/index)']);
for (const k of ['Login (authenticator)…', 'Migration (diff)', 'State provider…', 'State processor…', 'Symfony', 'Doctrine', 'Security', 'Translations', 'Script…', 'Test…', 'Controller…', 'Command…', 'Entity…', 'User…', 'Voter…', 'Folder…', 'File…', 'Project']) SAME_OK.add(k);
files.push('new-hub.js');
// the controller panel (controller-panel.js): its kinds of parameters reach t() through a table
files.push('controller-panel.js');
const CP_KEYS = Object.values((await import('./controller-panel-model.js')).KIND_LABEL).concat(['not used by the action']);
let keys;
// version control (vcs-setup.js): the hosts' labels, the address hints of vcs-model.js and the menu / dialog labels are table rows, not t('...') literals
files.push('vcs-setup.js');
import { HOSTS } from './vcs-model.js';
const VCS_KEYS = [...HOSTS.map((h) => h.label), 'This is not a repository address.', 'not a Subversion URL (http://, https://, svn://, svn+ssh://, file://)',
'not a Git URL (https://…, ssh://…, git@host:owner/repo.git or a folder)', 'Do not put a password in the URL: add a token in the credentials of the IDE.',
'Remotes and hosting…', 'Version control…', 'Detach', 'Check out', 'Save', 'Remove', 'Close'];
for (const k of ['Local', 'GitHub', 'Bitbucket', 'Git', 'Subversion', 'SVN', 'Subversion (SVN)', 'Token', 'JumPHP forge (git.jumphp.net)']) SAME_OK.add(k);
keys = new Set([...CP_KEYS, ...HUB_KEYS, ...VCS_KEYS, ...EXTRA, ...MENU_KEYS, ...tableKeys(), ...API_KEYS]);
for (const f of files) for (const k of keysOf(f)) keys.add(k);
keys.delete('');
for (const k of [...keys]) if (!/[A-Za-z]/.test(k)) keys.delete(k);
for (const lang of LANGS) {
test(`i18n/${lang}.js translates every t() text`, async () => {
const dict = (await import(`./i18n/${lang}.js`)).default;
const bad = [];
for (const k of keys) {
const v = dict[k];
if (typeof v !== 'string' || v.trim() === '') bad.push(`missing: ${k}`);
else if (v === k && !SAME_OK.has(k) && !/^[^A-Za-z]*$/.test(k)) bad.push(`English copy: ${k}`);
else {
const vars = (s) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join();
if (vars(v) !== vars(k)) bad.push(`placeholders differ: ${k}`);
}
}
assert.deepEqual(bad, []);
});
}
test('no language file has a key that is not an English text of the code (typo guard)', async () => {
// keys of fr.js must exist in the code or the checked tables: a renamed English text leaves a dead entry
const fr = (await import('./i18n/fr.js')).default;
const all = new Set();
for (const f of readdirSync(here).filter((n) => n.endsWith('.js'))) for (const k of keysOf(f)) all.add(k);
const dead = Object.keys(fr).filter((k) => !all.has(k) && !keys.has(k));
// informational only: dead entries do no harm
if (dead.length) console.log(`# ${dead.length} entries of fr.js are not used by a literal t() call (dynamic keys are fine)`);
});