@publishpress/potomatic 0.0.0-stage → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +127 -0
- package/LICENSE.md +20 -0
- package/README.md +470 -2
- package/config/openai-pricing.json +112 -0
- package/config/po-header.json +10 -0
- package/config/prompt.md +23 -0
- package/package.json +84 -5
- package/potomatic +103 -0
- package/src/config/index.js +497 -0
- package/src/logging/index.js +362 -0
- package/src/orchestrator/index.js +1031 -0
- package/src/processors/batchProcessor.js +171 -0
- package/src/processors/languageProcessor.js +1464 -0
- package/src/providers/ProviderFactory.js +124 -0
- package/src/providers/base/Provider.js +198 -0
- package/src/providers/openai/OpenAIProvider.js +805 -0
- package/src/providers/openai/modelCapabilities.js +256 -0
- package/src/reporters/ConsoleReporter.js +256 -0
- package/src/reporters/JsonReporter.js +254 -0
- package/src/reporters/ReporterFactory.js +218 -0
- package/src/reporters/base/BaseReporter.js +124 -0
- package/src/utils/colorUtils.js +93 -0
- package/src/utils/costCalculations.js +245 -0
- package/src/utils/costTracker.js +277 -0
- package/src/utils/dictionaryUtils.js +211 -0
- package/src/utils/languageMapping.js +1113 -0
- package/src/utils/pluralization.js +39 -0
- package/src/utils/poFileUtils.js +599 -0
- package/src/utils/promptLoader.js +115 -0
- package/src/utils/reportingUtils.js +417 -0
- package/src/utils/validationStats.js +110 -0
- package/src/utils/xmlTranslation.js +532 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import { Command, Option } from 'commander';
|
|
2
|
+
import chalk from 'chalk';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { readFileSync } from 'fs';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { DEFAULT_MODEL, REASONING_EFFORTS } from '../providers/openai/modelCapabilities.js';
|
|
7
|
+
import { dirname, join } from 'path';
|
|
8
|
+
import { normalizeLanguageInput } from '../utils/languageMapping.js';
|
|
9
|
+
|
|
10
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
11
|
+
const __dirname = dirname(__filename);
|
|
12
|
+
const packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf8'));
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Banner, yo!
|
|
16
|
+
*
|
|
17
|
+
* @since 1.0.0
|
|
18
|
+
*/
|
|
19
|
+
const BANNER = `
|
|
20
|
+
|
|
21
|
+
___ ___ ___ ___ ___ ___ ___ ___
|
|
22
|
+
/\\ \\ /\\ \\ /\\ \\ /\\ \\ /\\__\\ /\\ \\ /\\ \\ ___ /\\ \\
|
|
23
|
+
/::\\ \\ /::\\ \\ \\:\\ \\ /::\\ \\ /::| | /::\\ \\ \\:\\ \\ /\\ \\ /::\\ \\
|
|
24
|
+
/:/\\:\\ \\ /:/\\:\\ \\ \\:\\ \\ /:/\\:\\ \\ /:|:| | /:/\\:\\ \\ \\:\\ \\ \\:\\ \\ /:/\\:\\ \\
|
|
25
|
+
/::\\~\\:\\ \\ /:/ \\:\\ \\ /::\\ \\ /:/ \\:\\ \\ /:/|:|__|__ /::\\~\\:\\ \\ /::\\ \\ /::\\__\\ /:/ \\:\\ \\
|
|
26
|
+
/:/\\:\\ \\:\\__\\/:/__/ \\:\\__\\ /:/\\:\\__\\/:/__/ \\:\\__\\/:/ |::::\\__\\/:/\\:\\ \\:\\__\\ /:/\\:\\__\\ __/:/\\/__//:/__/ \\:\\__\\
|
|
27
|
+
\\/__\\:\\/:/ /\\:\\ \\ /:/ //:/ \\/__/\\:\\ \\ /:/ /\\/__/~~/:/ /\\/__\\:\\/:/ //:/ \\/__//\\/:/ / \\:\\ \\ \\/__/
|
|
28
|
+
\\::/ / \\:\\ /:/ //:/ / \\:\\ /:/ / /:/ / \\::/ //:/ / \\::/__/ \\:\\ \\
|
|
29
|
+
\\/__/ \\:\\/:/ / \\/__/ \\:\\/:/ / /:/ / /:/ / \\/__/ \\:\\__\\ \\:\\ \\
|
|
30
|
+
\\::/ / \\::/ / /:/ / /:/ / \\/__/ \\:\\__\\
|
|
31
|
+
\\/__/ \\/__/ \\/__/ \\/__/ \\/__/
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Displays the banner with version information.
|
|
36
|
+
*
|
|
37
|
+
* @since 1.0.0
|
|
38
|
+
*
|
|
39
|
+
* @return {void}
|
|
40
|
+
*/
|
|
41
|
+
export function displayBanner() {
|
|
42
|
+
console.log(chalk.cyan(BANNER));
|
|
43
|
+
console.log(chalk.gray(`Potomatic - AI-powered translation utility for .pot files ${packageJson.version ? `| v${packageJson.version}` : ''}\n`));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Schema for environment variable validation and parsing.
|
|
48
|
+
*/
|
|
49
|
+
const envSchema = z.object({
|
|
50
|
+
// Provider settings.
|
|
51
|
+
PROVIDER: z.string().default('openai'),
|
|
52
|
+
|
|
53
|
+
// API keys - 5-tier resolution: Potomatic-specific > standard provider > generic > fallback.
|
|
54
|
+
POTOMATIC_API_KEY: z.string().optional(),
|
|
55
|
+
POTOMATIC_OPENAI_API_KEY: z.string().optional(),
|
|
56
|
+
POTOMATIC_GEMINI_API_KEY: z.string().optional(),
|
|
57
|
+
OPENAI_API_KEY: z.string().optional(),
|
|
58
|
+
GEMINI_API_KEY: z.string().optional(),
|
|
59
|
+
API_KEY: z.string().optional(),
|
|
60
|
+
|
|
61
|
+
// Model settings.
|
|
62
|
+
MODEL: z.string().default(DEFAULT_MODEL),
|
|
63
|
+
ALLOW_UNKNOWN_MODEL: booleanStringSchema(false),
|
|
64
|
+
|
|
65
|
+
// Performance settings.
|
|
66
|
+
BATCH_SIZE: z.coerce.number().int().min(1).max(100).default(20),
|
|
67
|
+
CONCURRENT_JOBS: z.coerce.number().int().min(1).max(10).default(2),
|
|
68
|
+
TEMPERATURE: z.coerce.number().min(0).max(2).default(0.7),
|
|
69
|
+
REASONING_EFFORT: z.preprocess((value) => (value === '' || value === undefined ? undefined : value), z.enum(REASONING_EFFORTS).optional()),
|
|
70
|
+
TIMEOUT: z.coerce.number().int().min(10).max(300).default(60),
|
|
71
|
+
MAX_TOKENS: z.coerce.number().int().min(1).max(32768).optional(),
|
|
72
|
+
|
|
73
|
+
// Retry settings.
|
|
74
|
+
MAX_RETRIES: z.coerce.number().int().min(0).max(10).default(3),
|
|
75
|
+
RETRY_DELAY: z.coerce.number().int().min(500).max(30000).default(2000),
|
|
76
|
+
ABORT_ON_FAILURE: booleanStringSchema(false),
|
|
77
|
+
SKIP_LANGUAGE_ON_FAILURE: booleanStringSchema(false),
|
|
78
|
+
|
|
79
|
+
// Testing settings.
|
|
80
|
+
TEST_RETRY_FAILURE_RATE: z.coerce.number().min(0).max(1).optional(),
|
|
81
|
+
TEST_ALLOW_COMPLETE_FAILURE: booleanStringSchema(false),
|
|
82
|
+
|
|
83
|
+
// Limits.
|
|
84
|
+
MAX_COST: z.coerce.number().min(0.001).optional(),
|
|
85
|
+
MAX_STRINGS_PER_JOB: z.coerce.number().int().min(1).optional(),
|
|
86
|
+
MAX_TOTAL_STRINGS: z.coerce.number().int().min(1).optional(),
|
|
87
|
+
|
|
88
|
+
// Paths and files.
|
|
89
|
+
OUTPUT_DIR: z.string().default('.'),
|
|
90
|
+
PO_FILE_PREFIX: z.string().optional(),
|
|
91
|
+
INPUT_PO_PATH: z.string().optional(),
|
|
92
|
+
|
|
93
|
+
// Dictionary settings.
|
|
94
|
+
DICTIONARY_PATH: z.string().default('./config/dictionaries'),
|
|
95
|
+
USE_DICTIONARY: booleanStringSchema(false),
|
|
96
|
+
|
|
97
|
+
// Configuration file paths.
|
|
98
|
+
PROMPT_FILE_PATH: z.string().optional(),
|
|
99
|
+
PO_HEADER_TEMPLATE_PATH: z.string().optional(),
|
|
100
|
+
|
|
101
|
+
// Optional target languages and pot file (can set defaults.).
|
|
102
|
+
TARGET_LANGUAGES: z.string().optional(),
|
|
103
|
+
POT_FILE_PATH: z.string().optional(),
|
|
104
|
+
SOURCE_LANGUAGE: z.string().default('en'),
|
|
105
|
+
|
|
106
|
+
// Locale format for file naming.
|
|
107
|
+
LOCALE_FORMAT: z.enum(['wp_locale', 'iso_639_1', 'iso_639_2', 'target_lang']).default('target_lang'),
|
|
108
|
+
|
|
109
|
+
// Output format options.
|
|
110
|
+
OUTPUT_FORMAT: z.enum(['console', 'json']).default('console'),
|
|
111
|
+
OUTPUT_FILE: z.string().optional(),
|
|
112
|
+
|
|
113
|
+
// Debug and behavior.
|
|
114
|
+
VERBOSE_LEVEL: z.coerce.number().int().min(0).max(3).default(1),
|
|
115
|
+
SAVE_DEBUG_INFO: booleanStringSchema(false),
|
|
116
|
+
DRY_RUN: booleanStringSchema(false),
|
|
117
|
+
FORCE_TRANSLATE: booleanStringSchema(false),
|
|
118
|
+
RICH_PROGRESS: booleanStringSchema(false),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Parses and validates environment variables.
|
|
123
|
+
*
|
|
124
|
+
* @since 1.0.0
|
|
125
|
+
*
|
|
126
|
+
* @return {Object} Validated environment configuration.
|
|
127
|
+
*/
|
|
128
|
+
function parseEnvironmentConfig() {
|
|
129
|
+
try {
|
|
130
|
+
return envSchema.parse(process.env);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
console.error('❌ Environment configuration error:');
|
|
133
|
+
|
|
134
|
+
if (error instanceof z.ZodError) {
|
|
135
|
+
error.errors.forEach((err) => {
|
|
136
|
+
console.error(` - ${err.path.join('.')}: ${err.message}`);
|
|
137
|
+
});
|
|
138
|
+
} else {
|
|
139
|
+
console.error(` - ${error.message}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
process.exit(1);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Creates a Zod schema for parsing boolean values from strings (env vars and CLI args).
|
|
148
|
+
* Handles common string representations: "true", "false", "1", "0".
|
|
149
|
+
*
|
|
150
|
+
* @since 1.1.0
|
|
151
|
+
*
|
|
152
|
+
* @param {boolean} defaultValue - Default value if not provided or empty.
|
|
153
|
+
*
|
|
154
|
+
* @return {z.ZodEffects} Zod schema that parses boolean strings.
|
|
155
|
+
*/
|
|
156
|
+
function booleanStringSchema(defaultValue = false) {
|
|
157
|
+
return z
|
|
158
|
+
.string()
|
|
159
|
+
.transform((s) => s.trim().toLowerCase())
|
|
160
|
+
.pipe(z.enum(['true', 'false', '1', '0', '']))
|
|
161
|
+
.default(defaultValue ? 'true' : 'false')
|
|
162
|
+
.transform((val) => val === 'true' || val === '1');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Auto-detects provider from environment variable keys.
|
|
167
|
+
* Checks for POTOMATIC_<PROVIDER>_API_KEY and <PROVIDER>_API_KEY patterns.
|
|
168
|
+
*
|
|
169
|
+
* @since 1.1.0
|
|
170
|
+
*
|
|
171
|
+
* @return {string|null} Detected provider name (lowercase) or null if none detected.
|
|
172
|
+
*/
|
|
173
|
+
function detectProviderFromEnv() {
|
|
174
|
+
const knownProviders = ['gemini', 'anthropic', 'cohere', 'openai'];
|
|
175
|
+
|
|
176
|
+
// Check POTOMATIC_<PROVIDER>_API_KEY first (higher priority).
|
|
177
|
+
for (const provider of knownProviders) {
|
|
178
|
+
const providerUpper = provider.toUpperCase();
|
|
179
|
+
|
|
180
|
+
if (process.env[`POTOMATIC_${providerUpper}_API_KEY`]) {
|
|
181
|
+
return provider;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Check <PROVIDER>_API_KEY (standard keys).
|
|
186
|
+
for (const provider of knownProviders) {
|
|
187
|
+
const providerUpper = provider.toUpperCase();
|
|
188
|
+
|
|
189
|
+
if (process.env[`${providerUpper}_API_KEY`]) {
|
|
190
|
+
return provider;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Parse environment configuration once at module load.
|
|
198
|
+
const ENV_CONFIG = parseEnvironmentConfig();
|
|
199
|
+
|
|
200
|
+
// Auto-detect provider from environment keys if not explicitly set.
|
|
201
|
+
const DETECTED_PROVIDER = detectProviderFromEnv();
|
|
202
|
+
const RESOLVED_PROVIDER = ENV_CONFIG.PROVIDER || DETECTED_PROVIDER || 'openai';
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Default configuration constants.
|
|
206
|
+
*
|
|
207
|
+
* @since 1.0.0
|
|
208
|
+
*/
|
|
209
|
+
export const DEFAULTS = {
|
|
210
|
+
PROVIDER: RESOLVED_PROVIDER,
|
|
211
|
+
BATCH_SIZE: ENV_CONFIG.BATCH_SIZE,
|
|
212
|
+
MODEL: ENV_CONFIG.MODEL,
|
|
213
|
+
ALLOW_UNKNOWN_MODEL: ENV_CONFIG.ALLOW_UNKNOWN_MODEL,
|
|
214
|
+
VERBOSE_LEVEL: ENV_CONFIG.VERBOSE_LEVEL,
|
|
215
|
+
PO_FILE_PREFIX: ENV_CONFIG.PO_FILE_PREFIX,
|
|
216
|
+
INPUT_PO_PATH: ENV_CONFIG.INPUT_PO_PATH,
|
|
217
|
+
CONCURRENT_JOBS: ENV_CONFIG.CONCURRENT_JOBS,
|
|
218
|
+
MAX_RETRIES: ENV_CONFIG.MAX_RETRIES,
|
|
219
|
+
RETRY_DELAY: ENV_CONFIG.RETRY_DELAY,
|
|
220
|
+
ABORT_ON_FAILURE: ENV_CONFIG.ABORT_ON_FAILURE,
|
|
221
|
+
SKIP_LANGUAGE_ON_FAILURE: ENV_CONFIG.SKIP_LANGUAGE_ON_FAILURE,
|
|
222
|
+
TEMPERATURE: ENV_CONFIG.TEMPERATURE,
|
|
223
|
+
REASONING_EFFORT: ENV_CONFIG.REASONING_EFFORT,
|
|
224
|
+
TIMEOUT: ENV_CONFIG.TIMEOUT,
|
|
225
|
+
MAX_TOKENS: ENV_CONFIG.MAX_TOKENS,
|
|
226
|
+
MAX_COST: ENV_CONFIG.MAX_COST,
|
|
227
|
+
MAX_STRINGS_PER_JOB: ENV_CONFIG.MAX_STRINGS_PER_JOB,
|
|
228
|
+
MAX_TOTAL_STRINGS: ENV_CONFIG.MAX_TOTAL_STRINGS,
|
|
229
|
+
OUTPUT_DIR: ENV_CONFIG.OUTPUT_DIR,
|
|
230
|
+
SAVE_DEBUG_INFO: ENV_CONFIG.SAVE_DEBUG_INFO,
|
|
231
|
+
DRY_RUN: ENV_CONFIG.DRY_RUN,
|
|
232
|
+
FORCE_TRANSLATE: ENV_CONFIG.FORCE_TRANSLATE,
|
|
233
|
+
RICH_PROGRESS: ENV_CONFIG.RICH_PROGRESS,
|
|
234
|
+
TARGET_LANGUAGES: ENV_CONFIG.TARGET_LANGUAGES,
|
|
235
|
+
POT_FILE_PATH: ENV_CONFIG.POT_FILE_PATH,
|
|
236
|
+
TEST_RETRY_FAILURE_RATE: ENV_CONFIG.TEST_RETRY_FAILURE_RATE,
|
|
237
|
+
TEST_ALLOW_COMPLETE_FAILURE: ENV_CONFIG.TEST_ALLOW_COMPLETE_FAILURE,
|
|
238
|
+
SOURCE_LANGUAGE: ENV_CONFIG.SOURCE_LANGUAGE,
|
|
239
|
+
OUTPUT_FORMAT: ENV_CONFIG.OUTPUT_FORMAT,
|
|
240
|
+
OUTPUT_FILE: ENV_CONFIG.OUTPUT_FILE,
|
|
241
|
+
LOCALE_FORMAT: ENV_CONFIG.LOCALE_FORMAT,
|
|
242
|
+
DICTIONARY_PATH: ENV_CONFIG.DICTIONARY_PATH,
|
|
243
|
+
USE_DICTIONARY: ENV_CONFIG.USE_DICTIONARY,
|
|
244
|
+
PROMPT_FILE_PATH: ENV_CONFIG.PROMPT_FILE_PATH,
|
|
245
|
+
PO_HEADER_TEMPLATE_PATH: ENV_CONFIG.PO_HEADER_TEMPLATE_PATH,
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Parses command line arguments and sets up the CLI interface.
|
|
250
|
+
* Creates a Commander.js program with all available options and validates input.
|
|
251
|
+
* Environment variables provide defaults for all options.
|
|
252
|
+
*
|
|
253
|
+
* @since 1.0.0
|
|
254
|
+
*
|
|
255
|
+
* @return {Object} Parsed command line options object.
|
|
256
|
+
*/
|
|
257
|
+
export function parseCliArguments() {
|
|
258
|
+
const program = new Command();
|
|
259
|
+
|
|
260
|
+
program
|
|
261
|
+
.version(packageJson.version)
|
|
262
|
+
// === Required Options (can be set via env vars) ===
|
|
263
|
+
.option(
|
|
264
|
+
'-l, --target-languages <languages>',
|
|
265
|
+
'Target locale codes, comma-separated (e.g., fr_FR, es_ES, de_DE)',
|
|
266
|
+
(value, previous) => {
|
|
267
|
+
const langs = value
|
|
268
|
+
|
|
269
|
+
.split(',')
|
|
270
|
+
.map((lang) => lang.trim())
|
|
271
|
+
.filter((lang) => lang.length > 0);
|
|
272
|
+
|
|
273
|
+
const isFirstCliArgument = Array.isArray(previous) && previous.length > 0 && DEFAULTS.TARGET_LANGUAGES && previous.join(',') === DEFAULTS.TARGET_LANGUAGES;
|
|
274
|
+
|
|
275
|
+
return isFirstCliArgument ? langs : previous.concat(langs);
|
|
276
|
+
},
|
|
277
|
+
DEFAULTS.TARGET_LANGUAGES ? DEFAULTS.TARGET_LANGUAGES.split(',').map((lang) => lang.trim()) : []
|
|
278
|
+
)
|
|
279
|
+
.option('-p, --pot-file-path <path>', 'Path to the input `.pot` file containing source strings', DEFAULTS.POT_FILE_PATH)
|
|
280
|
+
.option('-s, --source-language <lang>', 'Source language code (default: "en")', DEFAULTS.SOURCE_LANGUAGE)
|
|
281
|
+
|
|
282
|
+
// === Output Options ===
|
|
283
|
+
.option('-o, --output-dir <path>', 'Directory to save generated `.po` files for each language', DEFAULTS.OUTPUT_DIR)
|
|
284
|
+
.option('--output-format <format>', 'Output format: `console` or `json` (default: console)', DEFAULTS.OUTPUT_FORMAT)
|
|
285
|
+
.option('--output-file <path>', 'Path to save JSON output (use stdout if not provided)', DEFAULTS.OUTPUT_FILE)
|
|
286
|
+
.option('--po-file-prefix <prefix>', 'Prefix for each output `.po` file (e.g., "app-" → "app-fr_FR.po")', DEFAULTS.PO_FILE_PREFIX)
|
|
287
|
+
.option('--locale-format <format>', 'Format to use for locale codes in file names: `wp_locale` (ru_RU), `iso_639_1` (ru), `iso_639_2` (rus), or `target_lang` (default)', DEFAULTS.LOCALE_FORMAT)
|
|
288
|
+
|
|
289
|
+
// === Translation Options ===
|
|
290
|
+
.addOption(new Option('--provider <provider>', 'AI provider.').default(DEFAULTS.PROVIDER).hideHelp())
|
|
291
|
+
.option('-k, --api-key <key>', 'OpenAI API key (overrides POTOMATIC_OPENAI_API_KEY, OPENAI_API_KEY and POTOMATIC_API_KEY env vars)')
|
|
292
|
+
.option('-m, --model <model>', 'AI model name (e.g., "gpt-5.4-mini")', DEFAULTS.MODEL)
|
|
293
|
+
.option('--allow-unknown-model', 'Accept a model that is not in the pricing catalogue, costed at the fallback rate', DEFAULTS.ALLOW_UNKNOWN_MODEL)
|
|
294
|
+
.option('--temperature <number>', 'Creativity level (0.0-2.0); lower = more deterministic, higher = more creative', (val) => Math.max(0, Math.min(2, parseFloat(val))), DEFAULTS.TEMPERATURE)
|
|
295
|
+
.option(
|
|
296
|
+
'--reasoning-effort <level>',
|
|
297
|
+
`Reasoning effort (${REASONING_EFFORTS.join(', ')}). Omit to keep the model default. none sends temperature and skips reasoning headroom.`,
|
|
298
|
+
(val) => {
|
|
299
|
+
if (!REASONING_EFFORTS.includes(val)) {
|
|
300
|
+
throw new Error(`Reasoning effort must be one of: ${REASONING_EFFORTS.join(', ')}`);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
return val;
|
|
304
|
+
},
|
|
305
|
+
DEFAULTS.REASONING_EFFORT
|
|
306
|
+
)
|
|
307
|
+
.option('-F, --force-translate', 'Re-translate all strings, ignoring any existing translations', DEFAULTS.FORCE_TRANSLATE)
|
|
308
|
+
.option('--input-po-path <path>', 'Path to an existing `.po` file to use as a base for merging', DEFAULTS.INPUT_PO_PATH)
|
|
309
|
+
|
|
310
|
+
// === Dictionary Options ===
|
|
311
|
+
.option('--dictionary-path <path>', 'Directory containing translation dictionaries (default: ./config/dictionaries)', DEFAULTS.DICTIONARY_PATH)
|
|
312
|
+
.option('--use-dictionary', 'Use user dictionary for consistent term translation', DEFAULTS.USE_DICTIONARY)
|
|
313
|
+
|
|
314
|
+
// === Configuration File Paths ===
|
|
315
|
+
.option('--prompt-file-path <path>', 'Path to the prompt.md file containing translation instructions (default: ./config/prompt.md)', DEFAULTS.PROMPT_FILE_PATH)
|
|
316
|
+
.option('--extra-prompt-path <path>', 'Path to an additional prompt file appended to the default prompt (e.g., domain-specific terminology)')
|
|
317
|
+
.option('--po-header-template-path <path>', 'Path to the po-header.json file containing custom PO file headers (default: ./config/po-header.json)', DEFAULTS.PO_HEADER_TEMPLATE_PATH)
|
|
318
|
+
|
|
319
|
+
// === Performance Options ===
|
|
320
|
+
.option('-b, --batch-size <number>', 'Number of strings per translation batch (1-100). Larger batches reduce cost but increase risk of API failures.', (val) => Math.max(1, Math.min(100, parseInt(val, 10))), DEFAULTS.BATCH_SIZE)
|
|
321
|
+
.option('-j, --jobs <number>', 'Maximum number of languages to translate in parallel (1-10)', (val) => Math.max(1, Math.min(10, parseInt(val, 10))), DEFAULTS.CONCURRENT_JOBS)
|
|
322
|
+
.option('--max-tokens <number>', 'Maximum completion tokens for AI responses (1-32768, auto-calculated if not set)', (val) => Math.max(1, Math.min(32768, parseInt(val, 10))), DEFAULTS.MAX_TOKENS)
|
|
323
|
+
.option('--max-strings-per-job <number>', 'Limit the number of strings translated per language (for testing)', (val) => Math.max(1, parseInt(val, 10)), DEFAULTS.MAX_STRINGS_PER_JOB)
|
|
324
|
+
.option('--max-total-strings <number>', 'Limit total number of strings translated across all languages (processed sequentially)', (val) => Math.max(1, parseInt(val, 10)), DEFAULTS.MAX_TOTAL_STRINGS)
|
|
325
|
+
.option('--max-cost <number>', 'Limit total estimated translation cost in USD', (val) => parseFloat(val), DEFAULTS.MAX_COST)
|
|
326
|
+
|
|
327
|
+
// === Reliability Options ===
|
|
328
|
+
.option('--max-retries <number>', 'Number of retry attempts per batch (0-10)', (val) => Math.max(0, Math.min(10, parseInt(val, 10))), DEFAULTS.MAX_RETRIES)
|
|
329
|
+
.option('--retry-delay <number>', 'Delay between retry attempts in milliseconds (500-30000)', (val) => Math.max(500, Math.min(30000, parseInt(val, 10))), DEFAULTS.RETRY_DELAY)
|
|
330
|
+
.option('--abort-on-failure', 'Abort the entire translation run if any batch fails all retry attempts', DEFAULTS.ABORT_ON_FAILURE)
|
|
331
|
+
.option('--skip-language-on-failure', 'Skip current language on failure and continue with remaining languages', DEFAULTS.SKIP_LANGUAGE_ON_FAILURE)
|
|
332
|
+
.option('--timeout <number>', 'Timeout for API requests in seconds (10-300)', (val) => Math.max(10, Math.min(300, parseInt(val, 10))), DEFAULTS.TIMEOUT)
|
|
333
|
+
|
|
334
|
+
// === Debugging Options ===
|
|
335
|
+
.addOption(
|
|
336
|
+
new Option('-v, --verbose-level <level>', 'Verbosity level: 0=errors, 1=normal, 2=verbose, 3=debug').default(DEFAULTS.VERBOSE_LEVEL.toString()).argParser((value) => {
|
|
337
|
+
const parsed = parseInt(value, 10);
|
|
338
|
+
|
|
339
|
+
return isNaN(parsed) ? DEFAULTS.VERBOSE_LEVEL : Math.max(0, Math.min(3, parsed));
|
|
340
|
+
})
|
|
341
|
+
)
|
|
342
|
+
.option('--dry-run', 'Simulate translation without making actual API calls', DEFAULTS.DRY_RUN)
|
|
343
|
+
.option('--save-debug-info', 'Save detailed request/response logs to timestamped files in the `debug/` directory', DEFAULTS.SAVE_DEBUG_INFO)
|
|
344
|
+
.option('--test-retry-failure-rate <rate>', '[Testing] Simulate API failure rate (0.0-1.0) to test retry logic', (val) => Math.max(0, Math.min(1, parseFloat(val))), DEFAULTS.TEST_RETRY_FAILURE_RATE)
|
|
345
|
+
.option('--test-allow-complete-failure', '[Testing] Allow complete failure of a batch (disables final fallback)', DEFAULTS.TEST_ALLOW_COMPLETE_FAILURE);
|
|
346
|
+
|
|
347
|
+
const hasEnvDefaults = DEFAULTS.TARGET_LANGUAGES && DEFAULTS.POT_FILE_PATH;
|
|
348
|
+
const shouldShowHelp = process.argv.length <= 2 && !hasEnvDefaults;
|
|
349
|
+
|
|
350
|
+
if (shouldShowHelp) {
|
|
351
|
+
displayBanner();
|
|
352
|
+
|
|
353
|
+
const provider = ENV_CONFIG.PROVIDER;
|
|
354
|
+
const providerUpper = provider.toUpperCase();
|
|
355
|
+
const potomacProviderKey = ENV_CONFIG[`POTOMATIC_${providerUpper}_API_KEY`];
|
|
356
|
+
const standardProviderKey = ENV_CONFIG[`${providerUpper}_API_KEY`];
|
|
357
|
+
|
|
358
|
+
const tempOptions = {
|
|
359
|
+
provider,
|
|
360
|
+
apiKey: potomacProviderKey || standardProviderKey || ENV_CONFIG.POTOMATIC_API_KEY || ENV_CONFIG.API_KEY,
|
|
361
|
+
targetLanguages: DEFAULTS.TARGET_LANGUAGES ? DEFAULTS.TARGET_LANGUAGES.split(',').map((lang) => lang.trim()) : [],
|
|
362
|
+
potFilePath: DEFAULTS.POT_FILE_PATH,
|
|
363
|
+
dryRun: false,
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
const validation = validateConfiguration(tempOptions);
|
|
367
|
+
|
|
368
|
+
if (!validation.isValid) {
|
|
369
|
+
validation.errors.forEach((error) => {
|
|
370
|
+
console.error(chalk.yellow(` ${error}`));
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
console.error();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
program.help();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const parsed = program.parse(process.argv);
|
|
380
|
+
const options = parsed.opts();
|
|
381
|
+
|
|
382
|
+
delete options._shouldShowHelp;
|
|
383
|
+
|
|
384
|
+
return options;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Validates the configuration and checks for required parameters.
|
|
389
|
+
* Ensures all essential settings are provided either via CLI or environment.
|
|
390
|
+
*
|
|
391
|
+
* @since 1.0.0
|
|
392
|
+
*
|
|
393
|
+
* @param {Object} options - Configuration options from CLI and environment.
|
|
394
|
+
*
|
|
395
|
+
* @return {Object} Validation result with isValid flag and error messages.
|
|
396
|
+
*/
|
|
397
|
+
export function validateConfiguration(options) {
|
|
398
|
+
const errors = [];
|
|
399
|
+
|
|
400
|
+
// Check for API key with provider-aware messaging (5-tier resolution).
|
|
401
|
+
const provider = options.provider || DEFAULTS.PROVIDER;
|
|
402
|
+
const providerUpper = provider.toUpperCase();
|
|
403
|
+
const potomacProviderKey = process.env[`POTOMATIC_${providerUpper}_API_KEY`];
|
|
404
|
+
const standardProviderKey = process.env[`${providerUpper}_API_KEY`];
|
|
405
|
+
const hasApiKey = options.apiKey || potomacProviderKey || standardProviderKey || process.env.POTOMATIC_API_KEY || process.env.API_KEY;
|
|
406
|
+
|
|
407
|
+
if (!options.dryRun && !hasApiKey) {
|
|
408
|
+
const providerName = provider === 'openai' ? 'OpenAI' : provider === 'gemini' ? 'Gemini' : provider;
|
|
409
|
+
errors.push(`🔑 ${providerName} API key required. Set --api-key, ${providerUpper}_API_KEY, or POTOMATIC_API_KEY.`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (!options.targetLanguages || options.targetLanguages.length === 0) {
|
|
413
|
+
errors.push('🌍 Target language required (use --target-languages)');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (!options.potFilePath) {
|
|
417
|
+
errors.push('📄 POT file required (use --pot-file-path)');
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (options.model && options.model.trim().length === 0) {
|
|
421
|
+
errors.push('🤖 Model name cannot be empty.');
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
if (options.maxStringsPerJob && options.maxTotalStrings) {
|
|
425
|
+
console.log(chalk.yellow('⚠️ Both --max-strings-per-job and --max-total-strings specified. Using --max-total-strings (sequential processing).'));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return {
|
|
429
|
+
isValid: errors.length === 0,
|
|
430
|
+
errors,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Creates the final configuration object by merging CLI options with environment variables.
|
|
436
|
+
* CLI options take precedence over environment variables.
|
|
437
|
+
*
|
|
438
|
+
* @since 1.0.0
|
|
439
|
+
*
|
|
440
|
+
* @param {Object} options - CLI options object.
|
|
441
|
+
*
|
|
442
|
+
* @return {Object} Complete configuration object ready for use.
|
|
443
|
+
*/
|
|
444
|
+
export function createConfiguration(options) {
|
|
445
|
+
// 5-tier API key resolution chain.
|
|
446
|
+
const provider = options.provider || DEFAULTS.PROVIDER;
|
|
447
|
+
const providerUpper = provider.toUpperCase();
|
|
448
|
+
const potomacProviderKey = ENV_CONFIG[`POTOMATIC_${providerUpper}_API_KEY`];
|
|
449
|
+
const standardProviderKey = ENV_CONFIG[`${providerUpper}_API_KEY`];
|
|
450
|
+
|
|
451
|
+
const apiKey = options.apiKey || potomacProviderKey || standardProviderKey || ENV_CONFIG.POTOMATIC_API_KEY || ENV_CONFIG.API_KEY;
|
|
452
|
+
|
|
453
|
+
return {
|
|
454
|
+
provider,
|
|
455
|
+
apiKey,
|
|
456
|
+
model: options.model || DEFAULTS.MODEL,
|
|
457
|
+
allowUnknownModel: options.allowUnknownModel || DEFAULTS.ALLOW_UNKNOWN_MODEL,
|
|
458
|
+
|
|
459
|
+
potFilePath: options.potFilePath || DEFAULTS.POT_FILE_PATH,
|
|
460
|
+
targetLanguages: (options.targetLanguages || []).map((lang) => normalizeLanguageInput(lang)),
|
|
461
|
+
outputDir: options.outputDir || DEFAULTS.OUTPUT_DIR,
|
|
462
|
+
poFilePrefix: options.poFilePrefix || DEFAULTS.PO_FILE_PREFIX || '',
|
|
463
|
+
inputPoPath: options.inputPoPath || DEFAULTS.INPUT_PO_PATH,
|
|
464
|
+
|
|
465
|
+
batchSize: options.batchSize || DEFAULTS.BATCH_SIZE,
|
|
466
|
+
concurrentJobs: options.jobs || DEFAULTS.CONCURRENT_JOBS,
|
|
467
|
+
temperature: options.temperature ?? DEFAULTS.TEMPERATURE,
|
|
468
|
+
reasoningEffort: options.reasoningEffort || DEFAULTS.REASONING_EFFORT,
|
|
469
|
+
timeout: options.timeout || DEFAULTS.TIMEOUT,
|
|
470
|
+
maxTokens: options.maxTokens || DEFAULTS.MAX_TOKENS,
|
|
471
|
+
|
|
472
|
+
maxStrings: options.maxStringsPerJob || DEFAULTS.MAX_STRINGS_PER_JOB,
|
|
473
|
+
maxStringsTotal: options.maxTotalStrings || DEFAULTS.MAX_TOTAL_STRINGS,
|
|
474
|
+
maxCost: options.maxCost || DEFAULTS.MAX_COST,
|
|
475
|
+
|
|
476
|
+
maxRetries: options.maxRetries || DEFAULTS.MAX_RETRIES,
|
|
477
|
+
retryDelayMs: options.retryDelay || DEFAULTS.RETRY_DELAY,
|
|
478
|
+
stopOnMaxRetriesFailure: options.abortOnFailure || DEFAULTS.ABORT_ON_FAILURE,
|
|
479
|
+
skipJobOnMaxRetriesFailure: options.skipLanguageOnFailure || DEFAULTS.SKIP_LANGUAGE_ON_FAILURE,
|
|
480
|
+
|
|
481
|
+
forceTranslate: options.forceTranslate || DEFAULTS.FORCE_TRANSLATE,
|
|
482
|
+
dryRun: options.dryRun || DEFAULTS.DRY_RUN,
|
|
483
|
+
saveDebugInfo: options.saveDebugInfo || DEFAULTS.SAVE_DEBUG_INFO,
|
|
484
|
+
verboseLevel: options.verboseLevel || DEFAULTS.VERBOSE_LEVEL,
|
|
485
|
+
testRetryFailureRate: options.testRetryFailureRate || DEFAULTS.TEST_RETRY_FAILURE_RATE,
|
|
486
|
+
testAllowCompleteFailure: options.testAllowCompleteFailure || DEFAULTS.TEST_ALLOW_COMPLETE_FAILURE,
|
|
487
|
+
sourceLanguage: options.sourceLanguage || DEFAULTS.SOURCE_LANGUAGE,
|
|
488
|
+
outputFormat: options.outputFormat || DEFAULTS.OUTPUT_FORMAT,
|
|
489
|
+
outputFile: options.outputFile || DEFAULTS.OUTPUT_FILE,
|
|
490
|
+
localeFormat: options.localeFormat || DEFAULTS.LOCALE_FORMAT,
|
|
491
|
+
dictionaryPath: options.dictionaryPath || DEFAULTS.DICTIONARY_PATH,
|
|
492
|
+
useDictionary: options.useDictionary || DEFAULTS.USE_DICTIONARY,
|
|
493
|
+
promptFilePath: options.promptFilePath || DEFAULTS.PROMPT_FILE_PATH,
|
|
494
|
+
extraPromptPath: options.extraPromptPath || null,
|
|
495
|
+
poHeaderTemplatePath: options.poHeaderTemplatePath || DEFAULTS.PO_HEADER_TEMPLATE_PATH,
|
|
496
|
+
};
|
|
497
|
+
}
|