@hug/ngx-g11n
Version:
Angular helpers for internationalizing and localizing your application
105 lines ⢠4.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.execute = void 0;
const node_fs_1 = require("node:fs");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const ori_schema_1 = require("./ori-schema");
const execute = async (options, context) => {
try {
const projectName = context.target?.project;
if (!projectName) {
throw new Error('The builder requires a target.');
}
await runExtractI18nBuilder(context, projectName, options);
await runExtractedFileCleanUp(context, options);
return { success: true };
}
catch (error) {
context.logger.error(normalizeError(error));
return { success: false };
}
};
exports.execute = execute;
// --- HELPER(s) ---
const runExtractedFileCleanUp = async (context, options) => {
context.logger.info('\nš [2/2] Cleaning extracted translations...');
if (options.format !== ori_schema_1.Format.Json) {
context.logger.warn('ā (skipped) Not a JSON format.');
return;
}
if (options.ignoreKeyPatterns?.length === 0) {
context.logger.warn('ā (skipped) No ignoreKeyPatterns provided.');
return;
}
const outDir = (options.outputPath) ? (0, node_path_1.join)(context.workspaceRoot, options.outputPath) : context.workspaceRoot;
const outFile = (0, node_path_1.resolve)(outDir, options.outFile ?? 'messages.json');
if ((0, node_fs_1.existsSync)(outFile)) {
context.logger.info(`ā Reading file for cleanup: ${outFile}`);
const data = JSON.parse(await (0, promises_1.readFile)(outFile, 'utf-8'));
if (Object.hasOwn(data, 'translations')) {
const regexList = options.ignoreKeyPatterns?.map(pattern => new RegExp(`^${pattern}$`)) ?? [];
const { matched, remaining } = Object.entries(data.translations).reduce((acc, [key, value]) => {
const match = regexList.some(rx => rx.test(key));
(match ? acc.matched : acc.remaining)[key] = value;
return acc;
}, { matched: {}, remaining: {} });
if (Object.keys(matched).length) {
context.logger.info(`ā Saving cleaned data to: ${outFile}`);
await (0, promises_1.writeFile)(outFile, JSON.stringify({ ...data, translations: remaining }, null, 4), 'utf-8');
if (options.backupIgnoredTranslations) {
const now = new Date();
const timestamp = [
now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes(),
].map(n => String(n).padStart(2, '0')).join('');
const outBakFile = (0, node_path_1.resolve)(outDir, `${(0, node_path_1.parse)(outFile).name}_${timestamp}.bak.json`);
context.logger.info(`ā Saving matching keys to: ${outBakFile}`);
await (0, promises_1.writeFile)(outBakFile, JSON.stringify({ ...data, translations: matched }, null, 4), 'utf-8');
}
}
else {
context.logger.warn('ā (skipped) No matching keys to clean.');
}
}
else {
context.logger.warn('ā (skipped) No "translations" property found in file.');
return;
}
}
else {
context.logger.warn(`ā (skipped) Extracted file not found at ${outFile}`);
return;
}
context.logger.info('ā Cleanup Complete.');
};
const runExtractI18nBuilder = async (context, projectName, options) => {
context.logger.info(`š [1/2] Running Angular extract-i18n for project "${projectName}"...`);
// Normalize options to only keep keys that are really defined
const builderOptions = Object.fromEntries(['buildTarget', 'format', 'i18nDuplicateTranslation', 'outFile', 'outputPath', 'progress']
.filter((key) => key in options)
.map(key => [key, options[key]]));
const extraction = await context.scheduleBuilder(resolveExtractI18nBuilder(), builderOptions, { target: context.target });
const extractionResult = await extraction.result;
if (!extractionResult.success) {
throw new Error('Failed to execute extract-i18n.');
}
};
const resolveExtractI18nBuilder = () => {
try {
require.resolve('@angular/build/package.json');
return '@angular/build:extract-i18n';
}
catch {
return '@angular-devkit/build-angular:extract-i18n';
}
};
const normalizeError = (error) => {
if (error instanceof Error) {
return error.message;
}
else if (typeof error === 'string') {
return error;
}
return 'Unknown error occurred';
};
//# sourceMappingURL=builder.js.map