@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,256 @@
1
+ import { encoding_for_model as encodingForModel, get_encoding as getEncoding } from 'tiktoken';
2
+
3
+ /**
4
+ * Default OpenAI model used when none is configured.
5
+ *
6
+ * @since 1.3.0
7
+ *
8
+ * @type {string}
9
+ */
10
+ export const DEFAULT_MODEL = 'gpt-5.4-mini';
11
+
12
+ /**
13
+ * Encoding used by the GPT-4o, GPT-4.1 and GPT-5 model families.
14
+ *
15
+ * @since 1.3.0
16
+ *
17
+ * @type {string}
18
+ */
19
+ const DEFAULT_ENCODING = 'o200k_base';
20
+
21
+ /**
22
+ * Encoders are ~10 MB each and expensive to build, so they are created once per model
23
+ * and shared. Callers must not free them.
24
+ *
25
+ * @since 1.3.0
26
+ *
27
+ * @type {Map<string, Object|null>}
28
+ */
29
+ const encoders = new Map();
30
+
31
+ /**
32
+ * Marks a response that hit its completion-token ceiling. Retrying the identical request
33
+ * cannot succeed, so this is treated as terminal rather than transient.
34
+ *
35
+ * @since 1.3.0
36
+ *
37
+ * @type {string}
38
+ */
39
+ export const TRUNCATED_ERROR_CODE = 'OPENAI_RESPONSE_TRUNCATED';
40
+
41
+ /**
42
+ * Extra completion budget for models that reason before answering. Measured worst case is
43
+ * ~2400 reasoning tokens on a 20-string batch, and the cost is largely fixed rather than
44
+ * proportional to batch size, so this is a flat floor rather than a multiplier.
45
+ *
46
+ * @since 1.3.0
47
+ *
48
+ * @type {number}
49
+ */
50
+ export const REASONING_HEADROOM_TOKENS = 4096;
51
+
52
+ /**
53
+ * Chat Completions `reasoning_effort` values. Omitted from the request when unset.
54
+ *
55
+ * @since 1.4.0
56
+ *
57
+ * @type {Array<string>}
58
+ */
59
+ export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
60
+
61
+ /**
62
+ * Optional dated-snapshot suffix, e.g. `gpt-5.4-mini-2026-03-17`.
63
+ *
64
+ * @since 1.3.0
65
+ *
66
+ * @type {string}
67
+ */
68
+ const SNAPSHOT_SUFFIX = '(?:-\\d{4}-\\d{2}-\\d{2})?$';
69
+
70
+ /**
71
+ * Models that accept the legacy `max_tokens` parameter. Everything else requires
72
+ * `max_completion_tokens`; sending `max_tokens` to them fails the request outright.
73
+ * Unrecognised names fall on the `max_completion_tokens` side, which is what every
74
+ * model released since the GPT-4.1 family expects.
75
+ *
76
+ * @since 1.3.0
77
+ *
78
+ * @type {RegExp}
79
+ */
80
+ const LEGACY_MAX_TOKENS_PATTERN = new RegExp('^gpt-4\\.1(?:-(?:mini|nano))?' + SNAPSHOT_SUFFIX);
81
+
82
+ /**
83
+ * Models that accept a custom `temperature`. The remaining models only allow the
84
+ * default of 1 and reject any explicit value, so the parameter must be omitted.
85
+ * Unrecognised names are treated as not supporting it, since omitting the parameter
86
+ * is accepted by every model while sending it is not.
87
+ *
88
+ * @since 1.3.0
89
+ *
90
+ * @type {RegExp}
91
+ */
92
+ const CUSTOM_TEMPERATURE_PATTERN = new RegExp('^(?:gpt-4\\.1(?:-(?:mini|nano))?|gpt-5\\.[124](?:-(?:mini|nano))?)' + SNAPSHOT_SUFFIX);
93
+
94
+ /**
95
+ * Pricing per 1,000 tokens used when `config/openai-pricing.json` cannot be read.
96
+ * Must stay in step with that file; `tests/unit/modelCapabilities.test.js` asserts it.
97
+ *
98
+ * @since 1.3.0
99
+ *
100
+ * @type {Object}
101
+ */
102
+ export const FALLBACK_PRICING = {
103
+ models: {
104
+ 'gpt-6.2-astra': { prompt: 0.008, completion: 0.04 },
105
+ 'gpt-6.2-sol': { prompt: 0.002, completion: 0.01 },
106
+ 'gpt-6-astra': { prompt: 0.01, completion: 0.05 },
107
+ 'gpt-6.1-sol': { prompt: 0.002, completion: 0.01 },
108
+ 'gpt-6.1-terra': { prompt: 0.001, completion: 0.005 },
109
+ 'gpt-6-sol': { prompt: 0.002, completion: 0.01 },
110
+ 'gpt-6-luna': { prompt: 0.0001, completion: 0.0005 },
111
+ 'gpt-5.6-sol': { prompt: 0.004, completion: 0.02 },
112
+ 'gpt-5.6-terra': { prompt: 0.002, completion: 0.012 },
113
+ 'gpt-5.6-luna': { prompt: 0.0002, completion: 0.0012 },
114
+ 'gpt-5.5': { prompt: 0.005, completion: 0.03 },
115
+ 'gpt-5.4': { prompt: 0.0025, completion: 0.015 },
116
+ 'gpt-5.4-mini': { prompt: 0.00075, completion: 0.0045 },
117
+ 'gpt-5.4-nano': { prompt: 0.0002, completion: 0.00125 },
118
+ 'gpt-5.2': { prompt: 0.00175, completion: 0.014 },
119
+ 'gpt-5.1': { prompt: 0.00125, completion: 0.01 },
120
+ 'gpt-5': { prompt: 0.00125, completion: 0.01 },
121
+ 'gpt-5-mini': { prompt: 0.00025, completion: 0.002 },
122
+ 'gpt-5-nano': { prompt: 0.00005, completion: 0.0004 },
123
+ 'gpt-4.1': { prompt: 0.002, completion: 0.008 },
124
+ 'gpt-4.1-mini': { prompt: 0.0004, completion: 0.0016 },
125
+ 'gpt-4.1-nano': { prompt: 0.0001, completion: 0.0004 },
126
+ 'o4-mini': { prompt: 0.0011, completion: 0.0044 },
127
+ o3: { prompt: 0.002, completion: 0.008 },
128
+ 'o3-mini': { prompt: 0.0011, completion: 0.0044 },
129
+ },
130
+ fallback: { prompt: 0.00075, completion: 0.0045 },
131
+ };
132
+
133
+ /**
134
+ * Every model this provider accepts, used when the pricing file cannot be read.
135
+ *
136
+ * @since 1.3.0
137
+ *
138
+ * @type {Array<string>}
139
+ */
140
+ export const KNOWN_MODELS = Object.keys(FALLBACK_PRICING.models);
141
+
142
+ /**
143
+ * Returns a tiktoken encoder for a model, falling back to the encoding shared by
144
+ * current OpenAI families when tiktoken does not recognise the model name.
145
+ *
146
+ * @since 1.3.0
147
+ *
148
+ * @param {string} model - Model identifier.
149
+ *
150
+ * @return {Object|null} Shared encoder instance that must not be freed, or null when none could be created.
151
+ */
152
+ export function getEncodingForModel(model) {
153
+ if (encoders.has(model)) {
154
+ return encoders.get(model);
155
+ }
156
+
157
+ let encoder = null;
158
+
159
+ try {
160
+ encoder = encodingForModel(model);
161
+ } catch {
162
+ try {
163
+ encoder = getEncoding(DEFAULT_ENCODING);
164
+ } catch {
165
+ encoder = null;
166
+ }
167
+ }
168
+
169
+ if (encoder) {
170
+ encoders.set(model, encoder);
171
+ }
172
+
173
+ return encoder;
174
+ }
175
+
176
+ /**
177
+ * Indicates whether a model accepts an explicit `temperature` value.
178
+ *
179
+ * @since 1.3.0
180
+ *
181
+ * @param {string} model - Model identifier.
182
+ *
183
+ * @return {boolean} True when a custom temperature may be sent.
184
+ */
185
+ export function supportsLegacyMaxTokens(model) {
186
+ return LEGACY_MAX_TOKENS_PATTERN.test(model || '');
187
+ }
188
+
189
+ /**
190
+ * Indicates whether a model accepts an explicit `temperature` value.
191
+ *
192
+ * @since 1.3.0
193
+ *
194
+ * @param {string} model - Model identifier.
195
+ *
196
+ * @return {boolean} True when a custom temperature may be sent.
197
+ */
198
+ export function supportsCustomTemperature(model) {
199
+ return CUSTOM_TEMPERATURE_PATTERN.test(model || '');
200
+ }
201
+
202
+ /**
203
+ * Completion-token headroom for hidden reasoning.
204
+ * Unset effort keeps the 1.3.0 rule. `none` skips the headroom.
205
+ *
206
+ * @since 1.4.0
207
+ *
208
+ * @param {string} model - Model identifier.
209
+ * @param {string|null} reasoningEffort - Requested effort, or unset.
210
+ *
211
+ * @return {number} Extra completion tokens.
212
+ */
213
+ export function reasoningHeadroomTokens(model, reasoningEffort) {
214
+ if (supportsLegacyMaxTokens(model) || reasoningEffort === 'none') {
215
+ return 0;
216
+ }
217
+
218
+ return REASONING_HEADROOM_TOKENS;
219
+ }
220
+
221
+ /**
222
+ * Builds the chat completion parameters for a model, applying the token-limit and
223
+ * temperature rules that differ between the GPT-4 and GPT-5 families.
224
+ *
225
+ * @since 1.3.0
226
+ *
227
+ * @param {string} model - Model identifier.
228
+ * @param {Array} messages - Chat messages for the request.
229
+ * @param {number} maxTokens - Upper bound on generated tokens.
230
+ * @param {number} temperature - Requested sampling temperature.
231
+ * @param {string|null} reasoningEffort - Requested effort, or unset.
232
+ *
233
+ * @return {Object} Parameters ready to pass to the chat completions endpoint.
234
+ */
235
+ export function buildRequestParams(model, messages, maxTokens, temperature, reasoningEffort) {
236
+ const params = { model, messages };
237
+
238
+ if (supportsLegacyMaxTokens(model)) {
239
+ params.max_tokens = maxTokens;
240
+ } else {
241
+ params.max_completion_tokens = maxTokens;
242
+ }
243
+
244
+ if (reasoningEffort) {
245
+ params.reasoning_effort = reasoningEffort;
246
+ }
247
+
248
+ // A set effort other than `none` rejects temperature. `none` allows it.
249
+ const sendTemperature = reasoningEffort === 'none' || (!reasoningEffort && supportsCustomTemperature(model));
250
+
251
+ if (sendTemperature) {
252
+ params.temperature = temperature;
253
+ }
254
+
255
+ return params;
256
+ }
@@ -0,0 +1,256 @@
1
+ import { BaseReporter } from './base/BaseReporter.js';
2
+ import { printDetailedLogs } from '../logging/index.js';
3
+ import { printTranslationRunSummary } from '../utils/reportingUtils.js';
4
+ import { defaultChalk } from '../utils/colorUtils.js';
5
+
6
+ /**
7
+ * Outputs translation results to the console using colored formatting.
8
+ * Provides detailed logs and summary information based on verbosity level.
9
+ *
10
+ * @since 1.0.0
11
+ */
12
+ export class ConsoleReporter extends BaseReporter {
13
+ /**
14
+ * Creates a new Console Reporter instance.
15
+ *
16
+ * @since 1.0.0
17
+ *
18
+ * @param {Object} options - Console reporter configuration.
19
+ */
20
+ constructor(options = {}) {
21
+ super(options);
22
+ this.config = options;
23
+ this.logger = options.logger;
24
+ }
25
+
26
+ /**
27
+ * Validates console reporter configuration.
28
+ *
29
+ * @since 1.0.0
30
+ *
31
+ * @param {Object} config - Configuration to validate.
32
+ *
33
+ * @return {Object} Validation result.
34
+ */
35
+ validateConfig(config) {
36
+ const errors = [];
37
+
38
+ // Console reporter doesn't need special validation.
39
+ // but could check for TTY support, color preferences, etc.
40
+ if (config.outputFile) {
41
+ errors.push('Console reporter does not support file output. Use JsonReporter for file output.');
42
+ }
43
+
44
+ return {
45
+ isValid: errors.length === 0,
46
+ errors,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Reports translation results to console.
52
+ *
53
+ * @since 1.0.0
54
+ *
55
+ * @param {Array} allLanguageStats - Array of language processing results.
56
+ * @param {number} startTime - Start timestamp in milliseconds.
57
+ * @param {number} endTime - End timestamp in milliseconds.
58
+ * @param {Object} logCollector - Log collector instance for detailed logs.
59
+ *
60
+ * @return {Promise<void>} Resolves when reporting is complete.
61
+ */
62
+ async report(allLanguageStats, startTime, endTime, logCollector) {
63
+ if (allLanguageStats.length === 0) {
64
+ this.logger.warn('No language tasks were processed or no statistics were collected.');
65
+
66
+ return;
67
+ }
68
+
69
+ // Print detailed logs if verbose enough.
70
+ printDetailedLogs(logCollector, this.logger, this.config.verboseLevel);
71
+
72
+ // Print summary using centralized color utility.
73
+ printTranslationRunSummary(allLanguageStats, this.logger, defaultChalk, startTime, endTime);
74
+ }
75
+
76
+ /**
77
+ * Gets the reporter name.
78
+ *
79
+ * @since 1.0.0
80
+ *
81
+ * @return {string} Reporter name.
82
+ */
83
+ getReporterName() {
84
+ return 'console';
85
+ }
86
+
87
+ /**
88
+ * Gets supported output options for console reporter.
89
+ *
90
+ * @since 1.0.0
91
+ *
92
+ * @return {Array<string>} Supported output options.
93
+ */
94
+ getSupportedOptions() {
95
+ return ['verboseLevel', 'colors'];
96
+ }
97
+
98
+ /**
99
+ * Checks if reporter supports file output.
100
+ *
101
+ * @since 1.0.0
102
+ *
103
+ * @return {boolean} False - console reporter only outputs to console.
104
+ */
105
+ supportsFileOutput() {
106
+ return false;
107
+ }
108
+
109
+ /**
110
+ * Checks if reporter supports console output.
111
+ *
112
+ * @since 1.0.0
113
+ *
114
+ * @return {boolean} True - this is the primary purpose.
115
+ */
116
+ supportsConsoleOutput() {
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Reports successful translation completion.
122
+ *
123
+ * @since 1.0.0
124
+ *
125
+ * @param {Array|Object} results - Translation results to report.
126
+ *
127
+ * @return {void}
128
+ */
129
+ reportSuccess(results) {
130
+ const output = this.getOutputStream();
131
+
132
+ output.write('\nโœ… Translation completed successfully!\n\n');
133
+
134
+ if (Array.isArray(results)) {
135
+ results.forEach((result) => {
136
+ const formatted = this.formatResult(result);
137
+
138
+ output.write(`๐Ÿ“‹ ${formatted.language}: ${formatted.translatedStrings}/${formatted.totalStrings} strings translated`);
139
+
140
+ if (formatted.cost) {
141
+ output.write(` (Cost: $${formatted.cost.toFixed(4)})`);
142
+ }
143
+
144
+ output.write('\n');
145
+ });
146
+ } else {
147
+ const formatted = this.formatResult(results);
148
+
149
+ output.write(`๐Ÿ“‹ Result: ${formatted.translatedStrings}/${formatted.totalStrings} strings translated\n`);
150
+ }
151
+
152
+ output.write('\n');
153
+ }
154
+
155
+ /**
156
+ * Reports error during translation process.
157
+ *
158
+ * @since 1.0.0
159
+ *
160
+ * @param {Error} error - Error that occurred during translation.
161
+ * @param {Object} context - Additional context about the error.
162
+ *
163
+ * @return {void}
164
+ */
165
+ reportError(error, context = {}) {
166
+ const output = this.getErrorStream();
167
+
168
+ output.write('\nโŒ Translation failed!\n\n');
169
+ output.write(`Error: ${error.message}\n`);
170
+
171
+ if (context.language) {
172
+ output.write(`Language: ${context.language}\n`);
173
+ }
174
+
175
+ if (context.batch) {
176
+ output.write(`Batch: ${context.batch}\n`);
177
+ }
178
+
179
+ if (this.verboseLevel >= 2 && error.stack) {
180
+ output.write(`\nStack trace:\n${error.stack}\n`);
181
+ }
182
+
183
+ output.write('\n');
184
+ }
185
+
186
+ /**
187
+ * Reports progress during translation.
188
+ *
189
+ * @since 1.0.0
190
+ *
191
+ * @param {Object} progress - Progress information object.
192
+ *
193
+ * @return {void}
194
+ */
195
+ reportProgress(progress) {
196
+ if (this.verboseLevel < 1) {
197
+ return;
198
+ }
199
+
200
+ const output = this.getOutputStream();
201
+
202
+ const { current, total, language, batch } = progress;
203
+
204
+ const percentage = Math.round((current / total) * 100);
205
+ const progressBar = this.createProgressBar(current, total);
206
+
207
+ output.write(`\r๐Ÿ”„ ${language}: ${progressBar} ${percentage}% (${current}/${total})`);
208
+
209
+ if (batch) {
210
+ output.write(` - Batch ${batch}`);
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Reports dry run results.
216
+ *
217
+ * @since 1.0.0
218
+ *
219
+ * @param {Array|Object} results - Dry run results to report.
220
+ *
221
+ * @return {void}
222
+ */
223
+ reportDryRun(results) {
224
+ const output = this.getOutputStream();
225
+
226
+ output.write('\n๐Ÿงช Dry run completed!\n\n');
227
+ output.write('The following translations would be performed:\n\n');
228
+
229
+ if (Array.isArray(results)) {
230
+ results.forEach((result) => {
231
+ const formatted = this.formatResult(result);
232
+
233
+ output.write(`๐Ÿ“‹ ${formatted.language}: ${formatted.totalStrings} strings would be translated\n`);
234
+ });
235
+ } else {
236
+ const formatted = this.formatResult(results);
237
+
238
+ output.write(`๐Ÿ“‹ ${formatted.totalStrings} strings would be translated\n`);
239
+ }
240
+
241
+ output.write('\nNo API calls were made.\n\n');
242
+ }
243
+
244
+ /**
245
+ * Creates a simple progress bar
246
+ *
247
+ * @since 1.0.0
248
+ */
249
+ createProgressBar(current, total, width = 20) {
250
+ const percentage = current / total;
251
+ const filled = Math.round(percentage * width);
252
+ const empty = width - filled;
253
+
254
+ return `[${'โ–ˆ'.repeat(filled)}${' '.repeat(empty)}]`;
255
+ }
256
+ }