@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.
@@ -0,0 +1,254 @@
1
+ import { BaseReporter } from './base/BaseReporter.js';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { createSummary, calculateAggregateTotals, formatNumber } from '../utils/costCalculations.js';
5
+ import { VALIDATION_TYPES, getTotalValidationIssues } from '../utils/validationStats.js';
6
+ import { DEFAULT_MODEL } from '../providers/openai/modelCapabilities.js';
7
+
8
+ /**
9
+ * Reports translation results in JSON format.
10
+ *
11
+ * @since 1.0.0
12
+ */
13
+ export class JsonReporter extends BaseReporter {
14
+ constructor(options = {}) {
15
+ super(options);
16
+
17
+ this.results = [];
18
+ }
19
+
20
+ /**
21
+ * Main report method for generating complete translation reports.
22
+ * This is the primary interface used by the orchestrator.
23
+ *
24
+ * @param {Array} allLanguageStats - Array of language processing results.
25
+ * @param {number} startTime - Start timestamp in milliseconds.
26
+ * @param {number} endTime - End timestamp in milliseconds.
27
+ * @param {Object} logCollector - Log collector instance for detailed logs.
28
+ *
29
+ * @return {Promise<void>} Resolves when reporting is complete.
30
+ *
31
+ * @since 1.0.0
32
+ */
33
+ async report(allLanguageStats, startTime, endTime, logCollector) {
34
+ const durationMs = endTime - startTime;
35
+
36
+ // Use centralized cost calculation.
37
+ const totals = calculateAggregateTotals(allLanguageStats) || {};
38
+ const summary = createSummary(allLanguageStats) || {};
39
+
40
+ const reportData = {
41
+ metadata: {
42
+ version: '1.0.0',
43
+ timestamp: new Date(endTime).toISOString(),
44
+ duration_ms: durationMs,
45
+ source_language: this.options.sourceLanguage || 'en',
46
+ dry_run: totals.isDryRun || false,
47
+ configuration: {
48
+ model: this.options.model || DEFAULT_MODEL,
49
+ batch_size: this.options.batchSize || 20,
50
+ max_retries: this.options.maxRetries || 3,
51
+ temperature: this.options.temperature ?? 0.1,
52
+ provider: this.options.provider || 'openai',
53
+ },
54
+ },
55
+ input: {
56
+ pot_file: this.options.potFilePath || 'translations.pot',
57
+ total_strings: allLanguageStats.reduce((sum, stat) => sum + (stat.totalStringsInPot || 0), 0),
58
+ target_languages: allLanguageStats.map((stat) => stat.language),
59
+ },
60
+ jobs: allLanguageStats.map((stat) => this._formatJobResult(stat)),
61
+ summary,
62
+ };
63
+
64
+ await this._outputReport(reportData);
65
+ }
66
+
67
+ /**
68
+ * Formats a single language processing result for JSON output.
69
+ *
70
+ * @param {Object} stat - Language processing statistics.
71
+ *
72
+ * @return {Object} Formatted job result.
73
+ *
74
+ * @private
75
+ *
76
+ * @since 1.0.0
77
+ */
78
+ _formatJobResult(stat) {
79
+ const validation = {};
80
+
81
+ for (const key of Object.keys(VALIDATION_TYPES)) {
82
+ // Convert camelCase to snake_case for JSON output.
83
+ const snakeKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
84
+
85
+ validation[snakeKey] = stat.validationStats?.[key] || 0;
86
+ }
87
+
88
+ // Calculate total warnings count.
89
+ const totalWarnings = getTotalValidationIssues(stat.validationStats);
90
+
91
+ return {
92
+ language: stat.language,
93
+ status: stat.error ? 'error' : 'success',
94
+ strings: {
95
+ total: stat.totalStringsInPot || 0,
96
+ translated: stat.translatedInRun || 0,
97
+ already_translated: stat.alreadyTranslated || 0,
98
+ skipped_due_to_budget: stat.skippedDueToBudget || 0,
99
+ skipped_due_to_limits: stat.skippedDueToLimits || 0,
100
+ failed: stat.failedInRun || 0,
101
+ merged: stat.mergedFromExisting || 0,
102
+ warnings: totalWarnings,
103
+ },
104
+ cost: {
105
+ amount: stat.costData?.totalCost || 0,
106
+ input_tokens: stat.costData?.totalPromptTokens || stat.costData?.inputTokens || 0,
107
+ output_tokens: stat.costData?.totalCompletionTokens || stat.costData?.outputTokens || 0,
108
+ total_tokens: stat.costData?.totalTokens || 0,
109
+ },
110
+ validation,
111
+ output_file: stat.outputFile || `${stat.language}.po`,
112
+ method: stat.method || 'api_translation',
113
+ duration_ms: stat.duration || 0,
114
+ errors: stat.error ? [stat.error] : [],
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Outputs the report data either to console or file.
120
+ *
121
+ * @param {Object} reportData - The complete report data.
122
+ *
123
+ * @return {Promise<void>} Resolves when output is complete.
124
+ *
125
+ * @private
126
+ *
127
+ * @since 1.0.0
128
+ */
129
+ async _outputReport(reportData) {
130
+ if (this.options.outputFile) {
131
+ // For file output, use raw numbers for programmatic consumption.
132
+ const jsonOutput = JSON.stringify(reportData, null, 2);
133
+
134
+ await this._writeToFile(jsonOutput);
135
+ } else {
136
+ // For console output, format numbers for human readability.
137
+ const jsonOutput = JSON.stringify(reportData, this._createNumberFormattingReplacer(), 2);
138
+
139
+ console.log(jsonOutput);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Creates a JSON replacer function that formats numbers for human readability.
145
+ * This is used when outputting JSON to console to make large numbers more readable.
146
+ *
147
+ * @return {Function} JSON replacer function
148
+ *
149
+ * @private
150
+ *
151
+ * @since 1.0.0
152
+ */
153
+ _createNumberFormattingReplacer() {
154
+ return (key, value) => {
155
+ // Format integer values that represent counts (but not costs, durations, or version numbers.).
156
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 1000) {
157
+ // Don't format certain keys that should remain as raw numbers.
158
+ const skipFormatting = ['duration_ms', 'amount', 'version'];
159
+
160
+ if (!skipFormatting.some((skipKey) => key.includes(skipKey))) {
161
+ return formatNumber(value);
162
+ }
163
+ }
164
+
165
+ return value;
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Gets the reporter name.
171
+ *
172
+ * @return {string} Reporter name.
173
+ *
174
+ * @since 1.0.0
175
+ */
176
+ getReporterName() {
177
+ return 'json';
178
+ }
179
+
180
+ /**
181
+ * Gets supported output options for JSON reporter.
182
+ *
183
+ * @return {Array<string>} Supported output options.
184
+ *
185
+ * @since 1.0.0
186
+ */
187
+ getSupportedOptions() {
188
+ return ['outputFile', 'prettyPrint'];
189
+ }
190
+
191
+ /**
192
+ * Checks if reporter supports file output.
193
+ *
194
+ * @return {boolean} True - JSON reporter supports file output.
195
+ *
196
+ * @since 1.0.0
197
+ */
198
+ supportsFileOutput() {
199
+ return true;
200
+ }
201
+
202
+ /**
203
+ * Checks if reporter supports console output.
204
+ *
205
+ * @return {boolean} True - JSON reporter can output to console.
206
+ *
207
+ * @since 1.0.0
208
+ */
209
+ supportsConsoleOutput() {
210
+ return true;
211
+ }
212
+
213
+ /**
214
+ * Reports dry run results
215
+ *
216
+ * @since 1.0.0
217
+ */
218
+ async reportDryRun(results) {
219
+ // For dry run, we use the same report structure but mark it as dry run.
220
+ const mockStats = Array.isArray(results) ? results : [results];
221
+ const startTime = Date.now() - 1000; // Mock start time.
222
+ const endTime = Date.now();
223
+
224
+ await this.report(mockStats, startTime, endTime, null);
225
+ }
226
+
227
+ /**
228
+ * Writes JSON data to the specified output file.
229
+ *
230
+ * @param {string} jsonOutput - JSON string to write.
231
+ *
232
+ * @return {Promise<void>} Resolves when file is written.
233
+ *
234
+ * @private
235
+ *
236
+ * @since 1.0.0
237
+ */
238
+ async _writeToFile(jsonOutput) {
239
+ try {
240
+ const outputPath = path.resolve(this.options.outputFile);
241
+ const outputDir = path.dirname(outputPath);
242
+
243
+ // Ensure output directory exists.
244
+ await fs.mkdir(outputDir, { recursive: true });
245
+
246
+ // Write the JSON file.
247
+ await fs.writeFile(outputPath, jsonOutput, 'utf8');
248
+
249
+ console.log(`JSON report written to: ${outputPath}`);
250
+ } catch (error) {
251
+ throw new Error(`Failed to write JSON report: ${error.message}`);
252
+ }
253
+ }
254
+ }
@@ -0,0 +1,218 @@
1
+ import { ConsoleReporter } from './ConsoleReporter.js';
2
+ import { JsonReporter } from './JsonReporter.js';
3
+
4
+ /**
5
+ * Reporter Factory.
6
+ *
7
+ * Creates reporter instances based on configuration.
8
+ *
9
+ * @since 1.0.0
10
+ */
11
+ export class ReporterFactory {
12
+ /**
13
+ * Creates a reporter instance based on the specified type
14
+ */
15
+ static createReporter(type, options = {}) {
16
+ // Handle case where first parameter is a config object.
17
+ if (typeof type === 'object' && type !== null) {
18
+ options = type;
19
+ type = type.outputFormat || 'console';
20
+ }
21
+
22
+ // Normalize type to lowercase.
23
+ if (typeof type === 'string') {
24
+ type = type.toLowerCase();
25
+ }
26
+
27
+ const supportedFormats = this.getSupportedFormats().join(', ');
28
+
29
+ switch (type) {
30
+ case 'console':
31
+ return new ConsoleReporter(options);
32
+
33
+ case 'json':
34
+ return new JsonReporter(options);
35
+
36
+ default:
37
+ throw new Error(`Unsupported output format: ${type}. Supported formats: ${supportedFormats}`);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Gets available reporter types
43
+ */
44
+ static getAvailableTypes() {
45
+ return ['console', 'json'];
46
+ }
47
+
48
+ /**
49
+ * Validates reporter type
50
+ */
51
+ static isValidType(type) {
52
+ return this.getAvailableTypes().includes(type);
53
+ }
54
+
55
+ /**
56
+ * Gets default reporter type
57
+ */
58
+ static getDefaultType() {
59
+ return 'console';
60
+ }
61
+
62
+ /**
63
+ * Gets the list of supported output format names.
64
+ *
65
+ * @since 1.0.0
66
+ *
67
+ * @return {Array<string>} Array of supported format names.
68
+ */
69
+ static getSupportedFormats() {
70
+ return ['console', 'json'];
71
+ }
72
+
73
+ /**
74
+ * Validates that an output format is supported.
75
+ *
76
+ * @since 1.0.0
77
+ *
78
+ * @param {string} formatName - Format name to validate.
79
+ *
80
+ * @return {boolean} True if format is supported.
81
+ */
82
+ static isFormatSupported(formatName) {
83
+ return ReporterFactory.getSupportedFormats().includes(formatName.toLowerCase());
84
+ }
85
+
86
+ /**
87
+ * Gets information about all reporters including capabilities.
88
+ *
89
+ * @since 1.0.0
90
+ *
91
+ * @return {Array<Object>} Reporter information objects.
92
+ */
93
+ static getReporterInfo() {
94
+ return [
95
+ {
96
+ name: 'console',
97
+ displayName: 'Console',
98
+ description: 'Colored console output with detailed logs and summary',
99
+ supportsFileOutput: false,
100
+ supportsConsoleOutput: true,
101
+ supportedOptions: ['verboseLevel', 'colors'],
102
+ configExample: {
103
+ outputFormat: 'console',
104
+ verboseLevel: 1,
105
+ },
106
+ },
107
+ {
108
+ name: 'json',
109
+ displayName: 'JSON',
110
+ description: 'Structured JSON output for programmatic consumption',
111
+ supportsFileOutput: true,
112
+ supportsConsoleOutput: true,
113
+ supportedOptions: ['outputFile', 'prettyPrint'],
114
+ configExample: {
115
+ outputFormat: 'json',
116
+ outputFile: 'results.json',
117
+ },
118
+ },
119
+ ];
120
+ }
121
+
122
+ /**
123
+ * Creates a reporter and validates its configuration.
124
+ * Provides detailed error messages for easier troubleshooting.
125
+ *
126
+ * @since 1.0.0
127
+ *
128
+ * @param {Object} config - Configuration object.
129
+ * @param {Object} logger - Logger instance.
130
+ *
131
+ * @return {Reporter} Validated reporter instance.
132
+ *
133
+ * @throws {Error} If reporter creation or validation fails.
134
+ */
135
+ static createAndValidateReporter(config, logger) {
136
+ // Check if format is supported.
137
+ const outputFormat = config.outputFormat || 'console';
138
+
139
+ if (!ReporterFactory.isFormatSupported(outputFormat)) {
140
+ const supportedFormats = ReporterFactory.getSupportedFormats().join(', ');
141
+
142
+ throw new Error(`Unsupported output format: ${outputFormat}. Supported: ${supportedFormats}`);
143
+ }
144
+
145
+ // Create reporter with logger included in options.
146
+ const optionsWithLogger = { ...config, logger };
147
+ const reporter = ReporterFactory.createReporter(outputFormat, optionsWithLogger);
148
+
149
+ // Validate configuration.
150
+ const validation = reporter.validateConfig(config);
151
+
152
+ if (!validation.isValid) {
153
+ const errorMessage = validation.errors.join(', ');
154
+
155
+ throw new Error(`Reporter configuration invalid: ${errorMessage}`);
156
+ }
157
+
158
+ logger.debug(`Created and validated ${outputFormat} reporter`);
159
+
160
+ return reporter;
161
+ }
162
+
163
+ /**
164
+ * Gets the default configuration for a reporter.
165
+ *
166
+ * @since 1.0.0
167
+ *
168
+ * @param {string} formatName - Format name.
169
+ *
170
+ * @return {Object} Default configuration.
171
+ */
172
+ static getDefaultConfig(formatName) {
173
+ const defaults = {
174
+ console: {
175
+ verboseLevel: 1,
176
+ },
177
+ json: {
178
+ prettyPrint: true,
179
+ },
180
+ };
181
+
182
+ return defaults[formatName] || {};
183
+ }
184
+
185
+ /**
186
+ * Checks if a configuration requires file output.
187
+ *
188
+ * @since 1.0.0
189
+ *
190
+ * @param {Object} config - Configuration to check.
191
+ *
192
+ * @return {boolean} True if configuration specifies file output.
193
+ */
194
+ static requiresFileOutput(config) {
195
+ return !!config.outputFile;
196
+ }
197
+
198
+ /**
199
+ * Gets the appropriate reporter for file vs.console output.
200
+ *
201
+ * @since 1.0.0
202
+ *
203
+ * @param {Object} config - Configuration object.
204
+ * @param {Object} logger - Logger instance.
205
+ *
206
+ * @return {Reporter} Appropriate reporter instance.
207
+ */
208
+ static getReporterForOutput(config, logger) {
209
+ // If output file is specified, prefer JSON format unless explicitly set to console.
210
+ if (config.outputFile && !config.outputFormat) {
211
+ const jsonConfig = { ...config, outputFormat: 'json' };
212
+
213
+ return ReporterFactory.createAndValidateReporter(jsonConfig, logger);
214
+ }
215
+
216
+ return ReporterFactory.createAndValidateReporter(config, logger);
217
+ }
218
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Abstract base class for all reporter implementations.
3
+ * Provides common interface and functionality for reporting translation results.
4
+ *
5
+ * @since 1.0.0
6
+ */
7
+ export class BaseReporter {
8
+ constructor(options = {}) {
9
+ this.options = options;
10
+ this.outputFormat = options.outputFormat || 'console';
11
+ this.verboseLevel = options.verboseLevel || 1;
12
+ }
13
+
14
+ /**
15
+ * Reports successful translation completion.
16
+ *
17
+ * @since 1.0.0
18
+ */
19
+ reportSuccess(results) {
20
+ throw new Error('BaseReporter.reportSuccess() must be implemented by subclass');
21
+ }
22
+
23
+ /**
24
+ * Reports error during translation process.
25
+ *
26
+ * @since 1.0.0
27
+ */
28
+ reportError(_error, context = {}) {
29
+ throw new Error('BaseReporter.reportError() must be implemented by subclass');
30
+ }
31
+
32
+ /**
33
+ * Reports progress during translation.
34
+ *
35
+ * @since 1.0.0
36
+ */
37
+ reportProgress(progress) {
38
+ throw new Error('BaseReporter.reportProgress() must be implemented by subclass');
39
+ }
40
+
41
+ /**
42
+ * Reports dry run results.
43
+ *
44
+ * @since 1.0.0
45
+ */
46
+ reportDryRun(results) {
47
+ throw new Error('BaseReporter.reportDryRun() must be implemented by subclass');
48
+ }
49
+
50
+ /**
51
+ * Main report method for generating complete translation reports.
52
+ * This is the primary interface used by the orchestrator.
53
+ *
54
+ * @since 1.0.0
55
+ */
56
+ report(allLanguageStats, startTime, endTime, logCollector) {
57
+ throw new Error('BaseReporter.report() must be implemented by subclass');
58
+ }
59
+
60
+ /**
61
+ * Gets the reporter name (must be implemented by subclasses).
62
+ *
63
+ * @since 1.0.0
64
+ */
65
+ getReporterName() {
66
+ throw new Error('BaseReporter.getReporterName() must be implemented by subclass');
67
+ }
68
+
69
+ /**
70
+ * Validates reporter configuration.
71
+ *
72
+ * @since 1.0.0
73
+ */
74
+ validateConfig(config = {}) {
75
+ // Base validation - can be overridden by subclasses.
76
+ const errors = [];
77
+
78
+ if (config.verboseLevel !== undefined && (config.verboseLevel < 0 || config.verboseLevel > 3)) {
79
+ errors.push('Verbose level must be between 0 and 3');
80
+ }
81
+
82
+ return {
83
+ isValid: errors.length === 0,
84
+ errors,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Gets the output stream for writing.
90
+ *
91
+ * @since 1.0.0
92
+ */
93
+ getOutputStream() {
94
+ return process.stdout;
95
+ }
96
+
97
+ /**
98
+ * Gets the error stream for writing.
99
+ *
100
+ * @since 1.0.0
101
+ */
102
+ getErrorStream() {
103
+ return process.stderr;
104
+ }
105
+
106
+ /**
107
+ * Formats a result object for display.
108
+ *
109
+ * @since 1.0.0
110
+ */
111
+ formatResult(result) {
112
+ if (typeof result === 'string') {
113
+ return { language: 'unknown', translatedStrings: 1, totalStrings: 1 };
114
+ }
115
+
116
+ return {
117
+ language: result.language || 'unknown',
118
+ translatedStrings: result.translatedStrings || result.translated || 0,
119
+ totalStrings: result.totalStrings || result.total || 0,
120
+ cost: result.cost || null,
121
+ errors: result.errors || [],
122
+ };
123
+ }
124
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Simple color utilities for consistent styling.
3
+ * Provides direct chalk functions for common use cases.
4
+ *
5
+ * @since 1.0.0
6
+ */
7
+
8
+ import chalk from 'chalk';
9
+
10
+ export const defaultChalk = chalk;
11
+
12
+ /**
13
+ * Simple color functions for common message types
14
+ */
15
+ export const colors = {
16
+ error: chalk.red,
17
+ warn: chalk.yellow,
18
+ warning: chalk.yellow,
19
+ info: chalk.blue,
20
+ success: chalk.green,
21
+ debug: chalk.gray,
22
+ notice: chalk.cyan,
23
+ highlight: chalk.magenta,
24
+ muted: chalk.gray,
25
+ neutral: chalk.white,
26
+ };
27
+
28
+ /**
29
+ * Gets a color function for a message type.
30
+ *
31
+ * @since 1.0.0
32
+ *
33
+ * @param {string} type - Message type.
34
+ *
35
+ * @return {Function} Chalk color function.
36
+ */
37
+ export function getColor(type) {
38
+ return colors[type] || colors.neutral;
39
+ }
40
+
41
+ /**
42
+ * Gets a styled (bright) color function.
43
+ *
44
+ * @since 1.0.0
45
+ *
46
+ * @param {string} type - Message type.
47
+ *
48
+ * @return {Function} Styled chalk color function.
49
+ */
50
+ export function getStyledColor(type) {
51
+ const baseColor = getColor(type);
52
+ // For most colors, add bright variant.
53
+ if (type === 'error') return chalk.redBright;
54
+ if (type === 'warn' || type === 'warning') return chalk.yellowBright;
55
+ if (type === 'info') return chalk.blueBright;
56
+ if (type === 'success') return chalk.greenBright;
57
+ if (type === 'notice') return chalk.cyanBright;
58
+ if (type === 'highlight') return chalk.magentaBright;
59
+
60
+ return baseColor;
61
+ }
62
+
63
+ /**
64
+ * Gets a bold color function.
65
+ *
66
+ * @since 1.0.0
67
+ *
68
+ * @param {string} type - Message type.
69
+ *
70
+ * @return {Function} Bold chalk color function.
71
+ */
72
+ export function getBoldColor(type) {
73
+ return getStyledColor(type).bold;
74
+ }
75
+
76
+ /**
77
+ * Creates a simple color map for multiple types.
78
+ *
79
+ * @since 1.0.0
80
+ *
81
+ * @param {Array<string>} types - Message types.
82
+ *
83
+ * @return {Object} Color map.
84
+ */
85
+ export function createColorMap(types) {
86
+ const colorMap = {};
87
+
88
+ for (const type of types) {
89
+ colorMap[type] = getColor(type);
90
+ }
91
+
92
+ return colorMap;
93
+ }