Files
jobtrackingapp/docs/i18n/00/integer-counts/probe.mjs
T

151 lines
8.5 KiB
JavaScript

// Research probe. Run from the audit checkout with frontend development dependencies available locally.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(path.resolve(process.argv[2] || 'job-tracker-ui', 'package.json'));
const ts = require('typescript');
const { chromium } = require('playwright');
const revision = '7a2b8a95c146d67bc4584740e4a72740cfc25cbf';
const auditSource = 'aaf66ca2';
const git = (...args) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
const eu = new Set('bg hr cs da nl en et fi fr de el hu ga it lv lt mt pl pt ro sk sl es sv'.split(' '));
const catalogPath = 'docs/i18n/00/LOCALE_CATALOG.json';
const catalogBlob = git('rev-parse', auditSource + ':' + catalogPath).trim();
const locales = JSON.parse(git('cat-file', 'blob', catalogBlob)).locales;
const tags = locales.map(entry => entry.tag);
assert.equal(new Set(tags).size, 60);
assert.ok(locales.every(entry => entry.status === 'planned' && Object.values(entry.surfaces).every(status => status === 'planned')));
assert.deepEqual(new Set(tags.map(tag => tag.split('-')[0]).filter(language => eu.has(language))), eu);
// The function is also evaluated verbatim inside isolated Chromium language contexts.
function cardinalSamples(tags) {
const values = [...Array(2002).keys(), 999999, 1000000, 1000001, 2000000, 1000000000];
return tags.map(tag => {
const accepted = Intl.PluralRules.supportedLocalesOf([tag], { localeMatcher: 'lookup' });
const rules = new Intl.PluralRules(tag, { localeMatcher: 'lookup', type: 'cardinal' });
const options = rules.resolvedOptions();
const witnesses = {};
const sequence = [];
let binaryCounterexample = null;
for (const value of values) {
const category = rules.select(value);
sequence.push(category);
witnesses[category] ??= value;
if (binaryCounterexample === null && category !== (value === 1 ? 'one' : 'other')) binaryCounterexample = { value, category };
}
const examples = Object.fromEntries([0, 1, 2, 3, 5, 6, 11, 21, 22, 101, 1000000].map(n => [n, rules.select(n)]));
return { tag, lookup: accepted, canonical: Intl.getCanonicalLocales(tag)[0], resolved: options.locale, reported: options.pluralCategories, witnesses, binaryCounterexample, examples, sequence: sequence.join(',') };
});
}
const host = cardinalSamples(tags);
const browser = await chromium.launch({ channel: 'chromium' });
const browserVersion = browser.version();
const browsers = {};
try {
for (const locale of ['en-GB', 'pl-PL']) {
const context = await browser.newContext({ locale });
const page = await context.newPage();
browsers[locale] = await page.evaluate(cardinalSamples, tags);
await context.close();
}
} finally {
await browser.close();
}
for (const [index, node] of host.entries()) {
for (const results of Object.values(browsers)) {
const browserRow = results[index];
assert.equal(browserRow.tag, node.tag);
assert.deepEqual(browserRow.lookup, node.lookup);
if (node.lookup.length) assert.equal(browserRow.sequence, node.sequence, node.tag);
}
}
const kvenEnglishHost = browsers['en-GB'].find(row => row.tag === 'fkv-NO');
const kvenPolishHost = browsers['pl-PL'].find(row => row.tag === 'fkv-NO');
assert.deepEqual(kvenEnglishHost.lookup, []);
assert.deepEqual(kvenPolishHost.lookup, []);
assert.notEqual(kvenEnglishHost.sequence, kvenPolishHost.sequence);
for (const row of [...host, ...Object.values(browsers).flat()]) {
row.sampleSha256 = createHash('sha256').update(row.sequence).digest('hex');
delete row.sequence;
}
const listing = git('ls-tree', '-r', revision, '--', 'job-tracker-ui/src').trimEnd().split('\n');
const files = listing.map(line => {
const [modeAndObject, filename] = line.split('\t');
return { filename, blob: modeAndObject.split(' ')[2] };
}).filter(file => /\.tsx?$/.test(file.filename) && !/(?:\.(?:test|spec)\.tsx?$|\/__tests__\/|\/setupTests\.ts$)/.test(file.filename));
const blobs = execFileSync('git', ['cat-file', '--batch'], { input: files.map(file => file.blob).join('\n') + '\n', maxBuffer: 32 * 1024 * 1024 });
let offset = 0;
for (const file of files) {
const end = blobs.indexOf(10, offset);
const [hash, type, length] = blobs.subarray(offset, end).toString('ascii').split(' ');
assert.equal(hash, file.blob);
assert.equal(type, 'blob');
file.source = ts.createSourceFile(file.filename, blobs.subarray(end + 1, end + 1 + Number(length)).toString('utf8'), ts.ScriptTarget.Latest, true);
assert.equal(file.source.parseDiagnostics.length, 0, file.filename);
offset = end + 2 + Number(length);
}
const catalogFile = files.find(file => file.filename.endsWith('/i18n/translations.ts'));
const variable = catalogFile.source.statements.filter(ts.isVariableStatement).flatMap(statement => statement.declarationList.declarations).find(decl => decl.name.getText() === 'translations');
const tuples = {};
const line = (file, node) => file.source.getLineAndCharacterOfPosition(node.getStart(file.source)).line + 1;
for (const language of variable.initializer.expression.properties) {
const labels = {};
for (const property of language.initializer.properties) {
assert.ok(ts.isPropertyAssignment(property) && ts.isStringLiteralLike(property.initializer));
labels[property.name.text] = { text: property.initializer.text, line: line(catalogFile, property) };
}
tuples[language.name.text] = labels;
}
const isCount = message => /\{count\}/.test(message);
const keys = Object.keys(tuples.en).filter(key => isCount(tuples.en[key].text) || isCount(tuples.nb[key].text));
const messages = Object.fromEntries(keys.map(key => [key, { en: tuples.en[key], nb: tuples.nb[key], references: [] }]));
for (const file of files) {
if (file === catalogFile) continue;
function visit(node) {
if (ts.isStringLiteralLike(node) && Object.hasOwn(messages, node.text)) {
let cursor = node;
while (cursor.parent && ts.isConditionalExpression(cursor.parent) && (cursor === cursor.parent.whenTrue || cursor === cursor.parent.whenFalse)) cursor = cursor.parent;
const parent = cursor.parent;
const call = ts.isCallExpression(parent) && parent.arguments[0] === cursor ? parent : null;
const descriptor = ts.isPropertyAssignment(parent) && parent.name.getText() === 'key' && ts.isObjectLiteralExpression(parent.parent) ? parent.parent : null;
const descriptorParams = descriptor?.properties.find(prop => prop.name?.getText() === 'params');
const params = call?.arguments[1] ?? descriptorParams?.initializer;
const count = params && ts.isObjectLiteralExpression(params) && params.properties.find(item => item.name?.getText() === 'count');
const conditional = ts.isConditionalExpression(cursor) ? cursor : call && ts.isConditionalExpression(call.parent) ? call.parent : null;
messages[node.text].references.push({
file: file.filename, blob: file.blob, line: line(file, node),
call: call?.expression.getText() ?? (descriptor ? 'deferred key descriptor' : null), count: count?.getText() ?? null,
selection: conditional?.condition.getText() ?? null,
});
}
ts.forEachChild(node, visit);
}
visit(file.source);
}
const write = (name, data) => {
const target = path.join(here, name);
if (process.argv.includes('--check')) assert.deepEqual(data, JSON.parse(readFileSync(target, 'utf8')), name);
else writeFileSync(target, JSON.stringify(data, null, 2) + '\n');
};
// Supported browser records matched the complete Node sequence above. Retain each
// binding, and retain the full observation wherever host fallback supplies the rules.
for (const results of Object.values(browsers)) {
for (const [index, row] of results.entries()) {
if (row.lookup.length) {
const { tag, lookup, resolved, sampleSha256 } = row;
results[index] = { tag, lookup, resolved, sampleSha256 };
}
}
}
write('count-callers.json', { revision, catalogBlob: catalogFile.blob, typescript: ts.version, sourceFiles: files.length, messages });
write('cardinals.json', { catalogBlob, euLanguages: [...eu], node: process.version, hostDefault: new Intl.PluralRules().resolvedOptions().locale, icu: process.versions.icu, cldr: process.versions.cldr, browser: browserVersion, host, browsers });
console.log('Candidate tags', tags.length, 'EU languages', eu.size, 'source files', files.length, 'count keys', keys.length);