UNPKG

@scoutello/i18n-magic

Version:

Intelligent CLI toolkit that automates internationalization workflows with AI-powered translations for JavaScript/TypeScript projects

78 lines 3.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.syncLocales = void 0; const utils_1 = require("../lib/utils"); const syncLocales = async (config) => { const { loadPath, savePath, defaultLocale, namespaces, locales, context, openai, } = config; try { for (const namespace of namespaces) { let defaultLocaleKeys; try { defaultLocaleKeys = await (0, utils_1.loadLocalesFile)(loadPath, defaultLocale, namespace); } catch (error) { throw new utils_1.TranslationError(`Failed to load default locale file for namespace "${namespace}"`, defaultLocale, namespace, error instanceof Error ? error : undefined); } for (const locale of locales) { if (locale === defaultLocale) continue; let localeKeys; try { localeKeys = await (0, utils_1.loadLocalesFile)(loadPath, locale, namespace); } catch (error) { console.warn(`Warning: Could not load locale file for ${locale} (namespace: ${namespace}). Creating new file.`); localeKeys = {}; } const missingKeys = {}; // Check which keys from default locale are missing in current locale for (const [key, value] of Object.entries(defaultLocaleKeys)) { if (!localeKeys[key]) { missingKeys[key] = value; } } // If there are missing keys, translate them if (Object.keys(missingKeys).length > 0) { console.log(`Found ${Object.keys(missingKeys).length} missing keys in ${locale} (namespace: ${namespace})`); let translatedValues; try { translatedValues = await (0, utils_1.translateKey)({ inputLanguage: defaultLocale, outputLanguage: locale, context, object: missingKeys, openai, model: config.model, }); } catch (error) { throw new utils_1.TranslationError(`Failed to translate keys for locale "${locale}" (namespace: ${namespace})`, locale, namespace, error instanceof Error ? error : undefined); } // Merge translated values with existing ones const updatedLocaleKeys = { ...localeKeys, ...translatedValues, }; try { await (0, utils_1.writeLocalesFile)(savePath, locale, namespace, updatedLocaleKeys); } catch (error) { throw new utils_1.TranslationError(`Failed to save translations for locale "${locale}" (namespace: ${namespace})`, locale, namespace, error instanceof Error ? error : undefined); } console.log(`Successfully translated and saved ${Object.keys(missingKeys).length} keys for ${locale} (namespace: ${namespace})`); } else { console.log(`No missing keys found for ${locale} (namespace: ${namespace})`); } } } } catch (error) { if (error instanceof utils_1.TranslationError) { throw error; } throw new utils_1.TranslationError("An unexpected error occurred during translation", undefined, undefined, error instanceof Error ? error : undefined); } }; exports.syncLocales = syncLocales; //# sourceMappingURL=sync-locales.js.map