48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
import { readFileSync, writeFileSync } from 'fs';
|
|
|
|
import readStrings from '../src/util/data/readStrings';
|
|
|
|
const TOP_COMMENT = '// This file is generated by dev/generateLangTypes.ts. Do not edit it manually.\n';
|
|
const LANG_KEY_TYPE = 'export type LangKey = keyof LangPair;';
|
|
|
|
const data = readFileSync('./src/assets/localization/fallback.strings', 'utf8');
|
|
|
|
const parsed = readStrings(data);
|
|
const keysWithVars = Object.entries(parsed).reduce((acc, [keyWithSuffix, value]) => {
|
|
const key = keyWithSuffix.split('_')[0];
|
|
const variables = extractVariables(value);
|
|
|
|
const previousVariables = acc[key] || [];
|
|
if (!previousVariables.length) {
|
|
acc[key] = variables;
|
|
} else {
|
|
acc[key] = Array.from(new Set([...previousVariables, ...variables]));
|
|
}
|
|
return acc;
|
|
}, {} as Record<string, string[]>);
|
|
|
|
let entries = '';
|
|
|
|
Object.entries(keysWithVars).forEach(([key, variables]) => {
|
|
const varString = variables.length
|
|
? `{\n ${variables.map((v) => `${wrapInQuotes(v)}: string | number;`).join('\n ')}\n };\n`
|
|
: 'undefined;\n';
|
|
entries += ` ${wrapInQuotes(key)}: ${varString}`;
|
|
});
|
|
|
|
const langPair = `export interface LangPair {\n${entries}\n}\n`;
|
|
const text = `${TOP_COMMENT}\n${langPair}\n${LANG_KEY_TYPE}\n`;
|
|
writeFileSync('./src/types/language.d.ts', text, 'utf8');
|
|
// eslint-disable-next-line no-console
|
|
console.log(`Language types generated: ${Object.keys(keysWithVars).length} keys`);
|
|
|
|
function extractVariables(value: string) {
|
|
const matches = value.match(/(?<!\\){[^{}]+}/g);
|
|
if (!matches) return [];
|
|
return matches.map((match) => match.slice(1, -1));
|
|
}
|
|
|
|
function wrapInQuotes(value: string) {
|
|
return `'${value}'`;
|
|
}
|