161 lines
10 KiB
JavaScript
161 lines
10 KiB
JavaScript
// Research evidence checks only; no runtime locale or release authority.
|
|
const assert = require('node:assert/strict');
|
|
const { createHash } = require('node:crypto');
|
|
const { execFileSync } = require('node:child_process');
|
|
const { readFileSync } = require('node:fs');
|
|
const path = require('node:path');
|
|
const { createRequire } = require('node:module');
|
|
const requireUi = createRequire(path.resolve(__dirname, '../../..', 'job-tracker-ui/package.json'));
|
|
const Ajv = requireUi('ajv');
|
|
const ts = requireUi('typescript');
|
|
const root = path.resolve(__dirname, '../../..');
|
|
const sha = value => createHash('sha256').update(value).digest('hex');
|
|
const load = name => JSON.parse(readFileSync(path.join(__dirname, name), 'utf8'));
|
|
const git = (...args) => execFileSync('git', args, { cwd: root, maxBuffer: 32 * 1024 * 1024 });
|
|
const cache = new Map();
|
|
function source(commit, file) {
|
|
assert.match(commit, /^[0-9a-f]{40}$/);
|
|
assert.match(file, /^(job-tracker-ui\/src\/|JobTrackerApi\/|tools\/summarizer\/)/);
|
|
assert(!file.split('/').includes('..'));
|
|
const key = `${commit}:${file}`;
|
|
if (!cache.has(key)) cache.set(key, git('show', key));
|
|
return cache.get(key);
|
|
}
|
|
const sorted = values => [...values].sort();
|
|
function unique(values, label) { assert.equal(new Set(values).size, values.length, `${label}: duplicate`); }
|
|
|
|
// Frozen candidate envelope from LOCALE_CATALOG.json, not a public support list.
|
|
const candidates = 'en en-GB nb-NO nn-NO sv-SE da-DK fi-FI is-IS bg-BG hr-HR cs-CZ nl-NL et-EE fr-FR de-DE el-GR hu-HU ga-IE it-IT lv-LV lt-LT mt-MT pl-PL pt-PT ro-RO sk-SK sl-SI es-ES uk-UA sq-AL sr-Latn-RS sr-Cyrl-RS bs-BA cnr-ME mk-MK tr-TR lb-LU cy-GB rm-CH fo-FO be-BY ka-GE hy-AM az-Latn-AZ ru-RU fr-CH de-CH it-CH nl-BE fr-BE de-BE en-IE ca-ES eu-ES gl-ES gd-GB se-NO smj-NO sma-NO fkv-NO'.split(' ');
|
|
// EU official language baseline already recorded in EUROPE_COUNTRY_LANGUAGE_MATRIX.md.
|
|
const eu24 = '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(' ');
|
|
function validateCatalogue(catalogue = load('LOCALE_CATALOG.json')) {
|
|
const validate = new Ajv({ allErrors: true }).compile(load('LOCALE_SCHEMA.json'));
|
|
assert(validate(catalogue), JSON.stringify(validate.errors));
|
|
const tags = catalogue.locales.map(locale => locale.tag);
|
|
unique(tags, 'locale tags');
|
|
assert.deepEqual(sorted(tags), sorted(candidates), 'candidate envelope changed');
|
|
const languages = new Set(tags.map(tag => new Intl.Locale(tag).language));
|
|
assert.deepEqual(eu24.filter(language => !languages.has(language)), [], 'missing EU language groups');
|
|
// Preserve raw cnr-ME identity; Intl canonicalisation is observation, never an alias decision.
|
|
return { candidates: tags.length, euLanguageGroups: eu24.length,
|
|
canonicalisationDifferences: tags.flatMap(tag => {
|
|
const canonical = Intl.getCanonicalLocales(tag)[0];
|
|
return canonical === tag ? [] : [{ tag, canonical }];
|
|
}), surfaceStatuses: 'planned', publicationAuthority: 'none' };
|
|
}
|
|
|
|
function parse(file, text) { return ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); }
|
|
function nodes(tree, predicate) {
|
|
const found = [];
|
|
function visit(node) { if (predicate(node)) found.push(node); ts.forEachChild(node, visit); }
|
|
visit(tree);
|
|
return found;
|
|
}
|
|
const lineAt = (tree, node) => tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1;
|
|
function validateFrontend(inventory = load('MESSAGE_INVENTORY.json')) {
|
|
const file = 'job-tracker-ui/src/i18n/translations.ts';
|
|
const bytes = source(inventory.baseline, file);
|
|
const tree = parse(file, bytes.toString('utf8'));
|
|
assert.equal(ts.version, inventory.typescriptVersion, 'parser version changed; requalify extraction');
|
|
const declarations = nodes(tree, node => ts.isVariableDeclaration(node) && node.name.getText(tree) === 'translations');
|
|
assert.equal(declarations.length, 1);
|
|
let object = declarations[0].initializer;
|
|
while (ts.isAsExpression(object) || ts.isSatisfiesExpression(object)) object = object.expression;
|
|
const en = object.properties.find(property => property.name.getText(tree) === 'en').initializer;
|
|
const extracted = en.properties.map(property => {
|
|
assert(ts.isPropertyAssignment(property) && ts.isStringLiteral(property.initializer));
|
|
return { id: property.name.text, english: property.initializer.text, line: lineAt(tree, property) };
|
|
});
|
|
unique(extracted.map(message => message.id), 'English source keys');
|
|
unique(inventory.messages.map(message => message.id), 'inventory keys');
|
|
assert.deepEqual(inventory.messages.map(({ id, english, line }) => ({ id, english, line })), extracted);
|
|
const actualCalls = new Map(extracted.map(message => [message.id, []]));
|
|
const files = git('ls-tree', '-r', '--name-only', inventory.baseline, '--', 'job-tracker-ui/src').toString('utf8')
|
|
.trim().split('\n').filter(name => /\.tsx?$/.test(name) && !/\.(test|d)\./.test(name));
|
|
assert.equal(files.length, inventory.scannedFrontendFiles);
|
|
let dynamic = 0;
|
|
for (const name of files) {
|
|
const ast = parse(name, source(inventory.baseline, name).toString('utf8'));
|
|
for (const call of nodes(ast, node => ts.isCallExpression(node) && /(^|\.)t$/.test(node.expression.getText(ast)))) {
|
|
const argument = call.arguments[0];
|
|
if (!argument || !ts.isStringLiteral(argument)) { dynamic++; continue; }
|
|
if (actualCalls.has(argument.text)) actualCalls.get(argument.text).push({ file: name, line: lineAt(ast, call), expression: call.getText(ast) });
|
|
}
|
|
}
|
|
assert.equal(dynamic, inventory.dynamicOrUnknownCalls);
|
|
for (const message of inventory.messages) {
|
|
assert.equal(message.source, file);
|
|
// Original frontend inventory hashed the Windows CRLF checkout; backend batches hash raw Git blobs.
|
|
assert.equal(message.sourceSha256, sha(bytes.toString('utf8').replace(/\r?\n/g, '\r\n')));
|
|
const placeholders = [...new Set([...message.english.matchAll(/\{(\w+)\}/g)].map(match => match[1]))];
|
|
assert.deepEqual(message.placeholders, placeholders, `${message.id}: placeholders`);
|
|
const normaliseCalls = calls => calls.map(call => ({ ...call, expression: call.expression.replace(/\r\n/g, '\n') }));
|
|
assert.deepEqual(normaliseCalls(message.callers), normaliseCalls(actualCalls.get(message.id)), `${message.id}: callers`);
|
|
}
|
|
return { baseline: inventory.baseline, messages: extracted.length, scannedFiles: files.length,
|
|
staticCallSites: inventory.messages.reduce((sum, message) => sum + message.callers.length, 0),
|
|
dynamicOrUnknownCalls: dynamic, withoutStaticCaller: inventory.messages.filter(message => !message.callers.length).length };
|
|
}
|
|
|
|
function validateCensus(census) {
|
|
assert.equal(census.status, 'partial-research-only');
|
|
unique(census.sourceBindings.map(binding => binding.path), 'source bindings');
|
|
const bindings = new Map(census.sourceBindings.map(binding => [binding.path, binding]));
|
|
let checks = 0;
|
|
for (const binding of census.sourceBindings) {
|
|
const bytes = source(census.sourceCommit, binding.path);
|
|
assert.equal(sha(bytes), binding.sha256, binding.path);
|
|
assert.equal(bytes.toString('utf8').replace(/\r?\n$/, '').split(/\r?\n/).length, binding.lineCount, binding.path);
|
|
checks++;
|
|
}
|
|
function checkLine(record) {
|
|
assert.equal(record.sourceSha256, bindings.get(record.source)?.sha256);
|
|
const lines = source(census.sourceCommit, record.source).toString('utf8').split(/\r?\n/);
|
|
assert(Number.isInteger(record.line) && record.line > 0 && record.line <= lines.length);
|
|
const expression = lines[record.line - 1].trim();
|
|
assert.equal(expression, record.sourceExpression, `${record.source}:${record.line}`);
|
|
assert.equal(sha(lines[record.line - 1]), record.sourceLineSha256);
|
|
checks++;
|
|
}
|
|
unique(census.records.map(record => record.id), 'record IDs');
|
|
unique(census.records.map(record => `${record.source}:${record.line}`), 'record loci');
|
|
const segmentKeys = ['sourceLiteralSegments', 'translationCandidateSegments', 'nonTranslatableSegments', 'unresolvedSegments'];
|
|
const segments = Object.fromEntries(segmentKeys.map(key => [key, 0]));
|
|
const categories = {};
|
|
for (const record of census.records) {
|
|
checkLine(record);
|
|
assert.equal(record.translator, null);
|
|
assert.equal(record.nativeReview, 'not-run');
|
|
assert.equal(record.runtimeReview, 'not-run');
|
|
for (const key of segmentKeys) segments[key] += record[key].length;
|
|
assert.deepEqual(sorted(record.sourceLiteralSegments), sorted([
|
|
...record.translationCandidateSegments, ...record.nonTranslatableSegments, ...record.unresolvedSegments
|
|
]), `${record.id}: segment partition`);
|
|
categories[record.category] = (categories[record.category] || 0) + 1;
|
|
}
|
|
assert.equal(census.counts.records, census.records.length);
|
|
assert.equal(census.counts.sources, census.sourceBindings.length);
|
|
assert.deepEqual(census.counts.byCategory, categories);
|
|
assert.deepEqual(Object.fromEntries(segmentKeys.map(key => [key, census.segmentAccounting[key]])), segments);
|
|
const traces = census.traces || [];
|
|
unique(traces.map(trace => trace.id), 'trace IDs');
|
|
for (const trace of traces) for (const record of trace.evidence) checkLine(record);
|
|
for (const record of census.records) for (const id of record.traceIds || []) assert(traces.some(trace => trace.id === id));
|
|
if (census.counts.traceEdges !== undefined) assert.equal(census.counts.traceEdges, traces.length);
|
|
return { sourceCommit: census.sourceCommit, records: census.records.length, traces: traces.length,
|
|
fileRecordTraceBindings: checks, segmentPartitions: census.records.length, segments };
|
|
}
|
|
|
|
function validateResearch() {
|
|
return { status: 'research-integrity-only', node: process.version, icu: process.versions.icu,
|
|
typescript: ts.version, ajv: requireUi('ajv/package.json').version,
|
|
inputSha256: Object.fromEntries(['LOCALE_CATALOG.json', 'LOCALE_SCHEMA.json', 'MESSAGE_INVENTORY.json',
|
|
'BACKEND_MESSAGE_CENSUS_B01.json', 'BACKEND_MESSAGE_CENSUS_B02.json', 'validate-research.cjs']
|
|
.map(name => [name, sha(readFileSync(path.join(__dirname, name)))])),
|
|
catalogue: validateCatalogue(), frontend: validateFrontend(),
|
|
backend: ['B01', 'B02'].map(batch => ({ batch, ...validateCensus(load(`BACKEND_MESSAGE_CENSUS_${batch}.json`)) })),
|
|
acceptance: 'NOT GRANTED', runtimeNativeProductTests: 'NOT RUN' };
|
|
}
|
|
module.exports = { load, validateCatalogue, validateFrontend, validateCensus, validateResearch };
|
|
if (require.main === module) console.log(JSON.stringify(validateResearch(), null, 2));
|