@babelize/engine 0.3.16 → 0.3.17
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/dist/detection/stack.d.ts +2 -0
- package/dist/detection/stack.js +10 -3
- package/dist/modules/extractor/extract.js +4 -0
- package/dist/modules/finalization/react-native-finalize.d.ts +6 -0
- package/dist/modules/finalization/react-native-finalize.js +38 -2
- package/dist/modules/lockfile/lockfile-manager.d.ts +0 -4
- package/dist/modules/lockfile/lockfile-manager.js +12 -5
- package/dist/modules/translator/client/byok.provider.d.ts +7 -0
- package/dist/modules/translator/client/byok.provider.js +24 -3
- package/dist/modules/translator/client/retry.d.ts +11 -0
- package/dist/modules/translator/client/retry.js +19 -3
- package/dist/modules/translator/translate.js +11 -0
- package/dist/modules/workspace/validate.js +13 -0
- package/dist/runtime/types.js +9 -0
- package/dist/utils/jsx-message.js +4 -2
- package/dist/utils/module-constants.js +11 -1
- package/dist/utils/untranslated.d.ts +5 -0
- package/dist/utils/untranslated.js +10 -1
- package/package.json +1 -1
|
@@ -36,6 +36,8 @@ export interface RepoFiles {
|
|
|
36
36
|
size?(relPath: string): number | undefined;
|
|
37
37
|
}
|
|
38
38
|
export declare const FRAMEWORK_DISPLAY_NAMES: Record<string, string>;
|
|
39
|
+
/** How deep a JS app's package.json may be (apps/web/package.json is 2). Shared with findWorkspaceApp. */
|
|
40
|
+
export declare const MAX_APP_DEPTH = 3;
|
|
39
41
|
/** Does a Python dependency file list Django itself (not just django-* add-ons)? */
|
|
40
42
|
export declare function mentionsPythonPackage(content: string, pkg: string): boolean;
|
|
41
43
|
/** Human list of supported stacks, for messages. */
|
package/dist/detection/stack.js
CHANGED
|
@@ -47,7 +47,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
47
47
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
48
48
|
};
|
|
49
49
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
50
|
-
exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = void 0;
|
|
50
|
+
exports.SUPPORTED_SUMMARY = exports.MAX_APP_DEPTH = exports.FRAMEWORK_DISPLAY_NAMES = void 0;
|
|
51
51
|
exports.mentionsPythonPackage = mentionsPythonPackage;
|
|
52
52
|
exports.detectPackageManagers = detectPackageManagers;
|
|
53
53
|
exports.detectStack = detectStack;
|
|
@@ -60,6 +60,8 @@ exports.FRAMEWORK_DISPLAY_NAMES = {
|
|
|
60
60
|
'react-native': 'React Native', unknown: 'Unknown',
|
|
61
61
|
};
|
|
62
62
|
const IGNORED_DIR = /(?:^|\/)(?:node_modules|\.git|venv|\.venv|env|site-packages|vendor|dist|build|\.next|__pycache__)\//;
|
|
63
|
+
/** How deep a JS app's package.json may be (apps/web/package.json is 2). Shared with findWorkspaceApp. */
|
|
64
|
+
exports.MAX_APP_DEPTH = 3;
|
|
63
65
|
function depth(p) {
|
|
64
66
|
return p.split('/').length - 1;
|
|
65
67
|
}
|
|
@@ -176,8 +178,13 @@ async function detectStack(files) {
|
|
|
176
178
|
const managePy = paths.filter((p) => p.endsWith('/manage.py') && depth(p) <= 3).sort((a, b) => depth(a) - depth(b));
|
|
177
179
|
if (managePy.length > 0 || mentionsPythonPackage(pyDeps, 'django'))
|
|
178
180
|
return result('django', true);
|
|
179
|
-
// 4. A JS framework in a
|
|
180
|
-
|
|
181
|
+
// 4. A JS framework in a subdirectory, up to three levels down (apps/web,
|
|
182
|
+
// frontend/apps/web), nearest first: the same places findWorkspaceApp looks
|
|
183
|
+
// when the run starts, so a repo that passes here can be babelized.
|
|
184
|
+
const subPkgs = paths
|
|
185
|
+
.filter((p) => p.endsWith('/package.json') && depth(p) <= exports.MAX_APP_DEPTH)
|
|
186
|
+
.sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
|
|
187
|
+
.slice(0, 40);
|
|
181
188
|
for (const p of subPkgs) {
|
|
182
189
|
const sub = jsFramework(await readJson(files, p));
|
|
183
190
|
if (SUPPORTED_JS.has(sub.id))
|
|
@@ -323,6 +323,10 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
323
323
|
}
|
|
324
324
|
let parent = path.parentPath;
|
|
325
325
|
while (parent) {
|
|
326
|
+
// A string inside a handler (`onPress={() => Alert.alert('Saved')}`) belongs to the
|
|
327
|
+
// function, not to the attribute holding it: onPress isn't copy, but the alert is.
|
|
328
|
+
if (parent.isFunction())
|
|
329
|
+
break;
|
|
326
330
|
if (parent.isJSXAttribute()) {
|
|
327
331
|
const nameNode = parent.node.name;
|
|
328
332
|
if (ast_helpers_1.t.isJSXIdentifier(nameNode) &&
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { WorkspaceInfo } from '../../runtime/types';
|
|
2
2
|
import { FinalizationWriter } from './writes';
|
|
3
|
+
/**
|
|
4
|
+
* Hermes, React Native's JavaScript engine, has no Intl.PluralRules. Without
|
|
5
|
+
* it intl-messageformat can't format a plural, and i18next-icu shows the raw
|
|
6
|
+
* message (`{count, plural, one {…} other {…}}`) instead.
|
|
7
|
+
*/
|
|
8
|
+
export declare const PLURAL_POLYFILL_DEPENDENCIES: Record<string, string>;
|
|
3
9
|
interface PackageJson {
|
|
4
10
|
main?: string;
|
|
5
11
|
dependencies?: Record<string, string>;
|
|
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.PLURAL_POLYFILL_DEPENDENCIES = void 0;
|
|
36
37
|
exports.isExpoProject = isExpoProject;
|
|
37
38
|
exports.expoSdkMajor = expoSdkMajor;
|
|
38
39
|
exports.expoLocalizationFor = expoLocalizationFor;
|
|
@@ -76,6 +77,16 @@ const EXPO_LOCALIZATION_BY_SDK = {
|
|
|
76
77
|
};
|
|
77
78
|
const FIRST_SDK_WITH_MATCHING_MAJORS = 55;
|
|
78
79
|
const REACT_NATIVE_LOCALIZE = '^3.7.2';
|
|
80
|
+
/**
|
|
81
|
+
* Hermes, React Native's JavaScript engine, has no Intl.PluralRules. Without
|
|
82
|
+
* it intl-messageformat can't format a plural, and i18next-icu shows the raw
|
|
83
|
+
* message (`{count, plural, one {…} other {…}}`) instead.
|
|
84
|
+
*/
|
|
85
|
+
exports.PLURAL_POLYFILL_DEPENDENCIES = {
|
|
86
|
+
'@formatjs/intl-getcanonicallocales': '^3.4.2',
|
|
87
|
+
'@formatjs/intl-locale': '^5.5.2',
|
|
88
|
+
'@formatjs/intl-pluralrules': '^7.1.2',
|
|
89
|
+
};
|
|
79
90
|
function allDeps(pkg) {
|
|
80
91
|
return { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
81
92
|
}
|
|
@@ -98,7 +109,7 @@ function expoLocalizationFor(expoRange) {
|
|
|
98
109
|
}
|
|
99
110
|
/** Dependencies a React Native app needs, and a warning when a version is a guess. */
|
|
100
111
|
function reactNativeDependencies(pkg) {
|
|
101
|
-
const deps = { ...dependencies_1.I18NEXT_CORE_DEPENDENCIES };
|
|
112
|
+
const deps = { ...dependencies_1.I18NEXT_CORE_DEPENDENCIES, ...exports.PLURAL_POLYFILL_DEPENDENCIES };
|
|
102
113
|
if (!isExpoProject(pkg)) {
|
|
103
114
|
deps['react-native-localize'] = REACT_NATIVE_LOCALIZE;
|
|
104
115
|
return { deps };
|
|
@@ -129,6 +140,29 @@ function messagesIdentifier(locale) {
|
|
|
129
140
|
return `${/^[0-9]/.test(camel) ? `_${camel}` : camel}Messages`;
|
|
130
141
|
}
|
|
131
142
|
const LOCALES_INDEX_MARKER = '// @babelize-generated locale index';
|
|
143
|
+
/**
|
|
144
|
+
* The Intl.PluralRules polyfill and the plural rules of each bundled language
|
|
145
|
+
* (by language: `pt-BR` uses `pt`). In the index, which is rewritten every
|
|
146
|
+
* run, so a language added later gets its rules too.
|
|
147
|
+
*
|
|
148
|
+
* Required only where the API is missing (Hermes), not imported: the
|
|
149
|
+
* FormatJS packages are ESM-only, and Node-based tests (jest-expo doesn't
|
|
150
|
+
* transform node_modules) fail to parse them. Node has Intl.PluralRules, so
|
|
151
|
+
* there they are never loaded; Metro bundles them for the app.
|
|
152
|
+
*/
|
|
153
|
+
function pluralPolyfill(locales) {
|
|
154
|
+
const languages = [...new Set(locales.map((l) => l.split(/[-_]/)[0].toLowerCase()))];
|
|
155
|
+
return [
|
|
156
|
+
'// Hermes has no Intl.PluralRules: without it plurals render as raw ICU text.',
|
|
157
|
+
"if (typeof Intl.PluralRules === 'undefined') {",
|
|
158
|
+
" require('@formatjs/intl-getcanonicallocales/polyfill.js');",
|
|
159
|
+
" require('@formatjs/intl-locale/polyfill.js');",
|
|
160
|
+
" require('@formatjs/intl-pluralrules/polyfill.js');",
|
|
161
|
+
...languages.map((l) => ` require('@formatjs/intl-pluralrules/locale-data/${l}.js');`),
|
|
162
|
+
'}',
|
|
163
|
+
'',
|
|
164
|
+
];
|
|
165
|
+
}
|
|
132
166
|
/** `<locales>/index.(ts|js)`: every bundled locale, source first. */
|
|
133
167
|
function buildLocalesIndex(locales, sourceLocale) {
|
|
134
168
|
const ordered = [sourceLocale, ...locales.filter((l) => l !== sourceLocale).sort()];
|
|
@@ -138,6 +172,7 @@ function buildLocalesIndex(locales, sourceLocale) {
|
|
|
138
172
|
`${LOCALES_INDEX_MARKER}: rewritten by Babelize on every run, edit the JSON files instead.`,
|
|
139
173
|
...imports,
|
|
140
174
|
'',
|
|
175
|
+
...pluralPolyfill(ordered),
|
|
141
176
|
'export const resources = {',
|
|
142
177
|
...entries,
|
|
143
178
|
'};',
|
|
@@ -274,7 +309,8 @@ async function finalizeReactNative(workspace, options, writer) {
|
|
|
274
309
|
warnings.push(note);
|
|
275
310
|
if (icu.userOwnsInit) {
|
|
276
311
|
warnings.push(`This app sets up i18next itself, so Babelize didn't add an i18n config. ` +
|
|
277
|
-
`Add the bundled translations (\`import { resources } from './${path.posix.relative(configDir, localesRel) || '.'}'\`) to your i18next.init()
|
|
312
|
+
`Add the bundled translations (\`import { resources } from './${path.posix.relative(configDir, localesRel) || '.'}'\`) to your i18next.init(). ` +
|
|
313
|
+
`Importing that file also loads the Intl.PluralRules polyfill Hermes needs for plurals.`);
|
|
278
314
|
return { configFileCreated, entryPointModified, userOwnsInit: true, warnings };
|
|
279
315
|
}
|
|
280
316
|
// i18n config: written once, next to the locales.
|
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
import type { LockfileEntry } from './schema';
|
|
2
2
|
import { type LockfileData, type LockfilePartition, type LockfileStats, type PartitionedKey } from './schema';
|
|
3
|
-
/**
|
|
4
|
-
* For each target locale, list of translation keys that must go through the translator
|
|
5
|
-
* (new keys, source-changed keys, or keys missing that locale in the lockfile).
|
|
6
|
-
*/
|
|
7
3
|
export declare function buildKeysToTranslateByTargetLocale(partition: LockfilePartition, targetLocales: string[]): Record<string, string[]>;
|
|
8
4
|
/**
|
|
9
5
|
* Resolve the lockfile path for a project:
|
|
@@ -53,6 +53,7 @@ const pseudo_markers_1 = require("../../utils/pseudo-markers");
|
|
|
53
53
|
const fs = __importStar(require("fs-extra"));
|
|
54
54
|
const logger_1 = require("../../utils/logger");
|
|
55
55
|
const hasher_1 = require("./hasher");
|
|
56
|
+
const untranslated_1 = require("../../utils/untranslated");
|
|
56
57
|
const schema_1 = require("./schema");
|
|
57
58
|
const LOCK_RETRIES = 20;
|
|
58
59
|
const LOCK_RETRY_DELAY_MS = 50;
|
|
@@ -84,6 +85,10 @@ async function releaseLock(lockDir) {
|
|
|
84
85
|
* For each target locale, list of translation keys that must go through the translator
|
|
85
86
|
* (new keys, source-changed keys, or keys missing that locale in the lockfile).
|
|
86
87
|
*/
|
|
88
|
+
/** Words of two or more letters, ignoring placeholders. */
|
|
89
|
+
function wordCount(text) {
|
|
90
|
+
return text.replace(/\{[^{}]*\}/g, ' ').split(/\s+/).filter((w) => /\p{L}{2,}/u.test(w)).length;
|
|
91
|
+
}
|
|
87
92
|
function buildKeysToTranslateByTargetLocale(partition, targetLocales) {
|
|
88
93
|
const byLocale = {};
|
|
89
94
|
for (const loc of targetLocales) {
|
|
@@ -473,12 +478,14 @@ function updateLockfile(lockfile, keys, translations, projectId, metadata) {
|
|
|
473
478
|
// Merge per-locale translations and metadata
|
|
474
479
|
for (const [locale, translatedKeys] of Object.entries(translations)) {
|
|
475
480
|
if (translatedKeys[key]) {
|
|
476
|
-
// Skip caching
|
|
477
|
-
//
|
|
478
|
-
//
|
|
479
|
-
//
|
|
481
|
+
// Skip caching a translation that is the source text where that can't be
|
|
482
|
+
// right: a sentence of 3+ words, or words left in Latin script for a
|
|
483
|
+
// non-Latin language. Those mean the translator fell back to the source,
|
|
484
|
+
// and caching them would skip re-translation on every later run. A word
|
|
485
|
+
// that is the same in both languages ("Version" in French, "API" in
|
|
486
|
+
// Japanese) is cached, so it isn't re-translated and re-charged every run.
|
|
480
487
|
const translated = translatedKeys[key];
|
|
481
|
-
if (translated === value && value.
|
|
488
|
+
if (translated === value && (wordCount(value) >= 3 || (0, untranslated_1.isUntranslatedInto)(value, translated, locale))) {
|
|
482
489
|
logger_1.engineLogger.warn(`Skipping cache for "${key}" → "${locale}": identity translation (same as source). Translator may be unavailable.`);
|
|
483
490
|
continue;
|
|
484
491
|
}
|
|
@@ -27,6 +27,12 @@ interface PromptEntry {
|
|
|
27
27
|
}
|
|
28
28
|
export declare class BYOKTranslatorClient implements TranslatorClient {
|
|
29
29
|
private readonly config;
|
|
30
|
+
/**
|
|
31
|
+
* Shared by every request this client makes (a run's batches and locales go
|
|
32
|
+
* out concurrently): one 429 pauses them all until the quota resets, instead
|
|
33
|
+
* of each one spending its retries against the same limit.
|
|
34
|
+
*/
|
|
35
|
+
private rateLimitedUntil;
|
|
30
36
|
constructor(config: BYOKProviderConfig);
|
|
31
37
|
health(): Promise<boolean>;
|
|
32
38
|
warmup(): Promise<boolean>;
|
|
@@ -37,6 +43,7 @@ export declare class BYOKTranslatorClient implements TranslatorClient {
|
|
|
37
43
|
/** Anthropic: force a tool call so the output is schema-shaped JSON. */
|
|
38
44
|
private callAnthropic;
|
|
39
45
|
private callOpenAICompatible;
|
|
46
|
+
private waitForQuota;
|
|
40
47
|
private httpError;
|
|
41
48
|
private formatApiError;
|
|
42
49
|
private redactApiKey;
|
|
@@ -21,10 +21,19 @@ const formality_1 = require("../formality");
|
|
|
21
21
|
const icu_message_1 = require("../../../utils/icu-message");
|
|
22
22
|
// Rough character to token ratio
|
|
23
23
|
const CHAR_TO_TOKEN_RATIO = 4;
|
|
24
|
-
const RETRY = { baseDelayMs: 1000, maxRetries: 3, timeoutMs: 120000 };
|
|
24
|
+
const RETRY = { baseDelayMs: 1000, maxRetries: 3, rateLimitRetries: 6, timeoutMs: 120000 };
|
|
25
|
+
/** Pause after a 429 that names no wait of its own. */
|
|
26
|
+
const DEFAULT_RATE_LIMIT_PAUSE_MS = 15000;
|
|
27
|
+
const MAX_RATE_LIMIT_PAUSE_MS = 60000;
|
|
25
28
|
const TOOL_NAME = 'submit_translations';
|
|
26
29
|
class BYOKTranslatorClient {
|
|
27
30
|
constructor(config) {
|
|
31
|
+
/**
|
|
32
|
+
* Shared by every request this client makes (a run's batches and locales go
|
|
33
|
+
* out concurrently): one 429 pauses them all until the quota resets, instead
|
|
34
|
+
* of each one spending its retries against the same limit.
|
|
35
|
+
*/
|
|
36
|
+
this.rateLimitedUntil = 0;
|
|
28
37
|
this.config = config;
|
|
29
38
|
}
|
|
30
39
|
async health() {
|
|
@@ -101,6 +110,7 @@ class BYOKTranslatorClient {
|
|
|
101
110
|
/** Anthropic: force a tool call so the output is schema-shaped JSON. */
|
|
102
111
|
async callAnthropic(model, system, user, retry = RETRY) {
|
|
103
112
|
const response = await (0, retry_1.withRetry)(async (signal) => {
|
|
113
|
+
await this.waitForQuota(signal);
|
|
104
114
|
const res = await fetch(this.getBaseUrl(), {
|
|
105
115
|
method: 'POST',
|
|
106
116
|
headers: {
|
|
@@ -159,6 +169,7 @@ class BYOKTranslatorClient {
|
|
|
159
169
|
body.response_format = { type: 'json_object' };
|
|
160
170
|
}
|
|
161
171
|
const response = await (0, retry_1.withRetry)(async (signal) => {
|
|
172
|
+
await this.waitForQuota(signal);
|
|
162
173
|
const res = await fetch(this.getBaseUrl(), {
|
|
163
174
|
method: 'POST',
|
|
164
175
|
headers: {
|
|
@@ -174,9 +185,19 @@ class BYOKTranslatorClient {
|
|
|
174
185
|
}, retry);
|
|
175
186
|
return { content: response.choices?.[0]?.message?.content ?? '', usage: response.usage };
|
|
176
187
|
}
|
|
188
|
+
async waitForQuota(signal) {
|
|
189
|
+
const wait = this.rateLimitedUntil - Date.now();
|
|
190
|
+
if (wait > 0)
|
|
191
|
+
await (0, retry_1.sleep)(wait, signal);
|
|
192
|
+
}
|
|
177
193
|
async httpError(res) {
|
|
178
|
-
const
|
|
179
|
-
|
|
194
|
+
const body = await res.text().catch(() => '');
|
|
195
|
+
const detail = this.redactApiKey(body.slice(0, 300));
|
|
196
|
+
const retryAfter = (0, retry_1.parseRetryAfter)(res.headers.get('retry-after')) ?? (0, retry_1.parseRetryDelayBody)(body);
|
|
197
|
+
if (res.status === 429) {
|
|
198
|
+
this.rateLimitedUntil = Math.max(this.rateLimitedUntil, Date.now() + Math.min(retryAfter ?? DEFAULT_RATE_LIMIT_PAUSE_MS, MAX_RATE_LIMIT_PAUSE_MS));
|
|
199
|
+
}
|
|
200
|
+
return new retry_1.ProviderHttpError(this.formatApiError(res.status, detail), res.status, retryAfter);
|
|
180
201
|
}
|
|
181
202
|
formatApiError(status, detail) {
|
|
182
203
|
const name = this.getProviderDisplayName();
|
|
@@ -4,9 +4,15 @@ export interface RetryOptions {
|
|
|
4
4
|
timeoutMs: number;
|
|
5
5
|
/** Upper bound for a single wait, including server-requested Retry-After. */
|
|
6
6
|
maxDelayMs?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Retries for a 429, counted apart from maxRetries: a per-minute quota needs
|
|
9
|
+
* waits that add up to a minute or more (default maxRetries).
|
|
10
|
+
*/
|
|
11
|
+
rateLimitRetries?: number;
|
|
7
12
|
/** Aborts the attempt in flight and stops any further retries. */
|
|
8
13
|
signal?: AbortSignal;
|
|
9
14
|
}
|
|
15
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
10
16
|
/** An HTTP error from a translation API, carrying what retry decisions need. */
|
|
11
17
|
export declare class ProviderHttpError extends Error {
|
|
12
18
|
readonly status: number;
|
|
@@ -16,6 +22,11 @@ export declare class ProviderHttpError extends Error {
|
|
|
16
22
|
/** Server-requested wait from a Retry-After header, in ms. */
|
|
17
23
|
retryAfterMs?: number | undefined);
|
|
18
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* The wait Gemini asks for in a 429's body (`"retryDelay": "37s"` in its
|
|
27
|
+
* RetryInfo detail), which it sends instead of a Retry-After header.
|
|
28
|
+
*/
|
|
29
|
+
export declare function parseRetryDelayBody(body: string): number | undefined;
|
|
19
30
|
/** Parse a Retry-After header (seconds or HTTP date) into milliseconds. */
|
|
20
31
|
export declare function parseRetryAfter(header: string | null): number | undefined;
|
|
21
32
|
/**
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.withRetry503 = exports.ProviderHttpError = void 0;
|
|
4
|
+
exports.sleep = sleep;
|
|
5
|
+
exports.parseRetryDelayBody = parseRetryDelayBody;
|
|
4
6
|
exports.parseRetryAfter = parseRetryAfter;
|
|
5
7
|
exports.isRetryable = isRetryable;
|
|
6
8
|
exports.withRetry = withRetry;
|
|
@@ -36,6 +38,14 @@ class ProviderHttpError extends Error {
|
|
|
36
38
|
}
|
|
37
39
|
}
|
|
38
40
|
exports.ProviderHttpError = ProviderHttpError;
|
|
41
|
+
/**
|
|
42
|
+
* The wait Gemini asks for in a 429's body (`"retryDelay": "37s"` in its
|
|
43
|
+
* RetryInfo detail), which it sends instead of a Retry-After header.
|
|
44
|
+
*/
|
|
45
|
+
function parseRetryDelayBody(body) {
|
|
46
|
+
const match = /"retryDelay"\s*:\s*"(\d+(?:\.\d+)?)s"/.exec(body);
|
|
47
|
+
return match ? Math.ceil(Number(match[1]) * 1000) : undefined;
|
|
48
|
+
}
|
|
39
49
|
/** Parse a Retry-After header (seconds or HTTP date) into milliseconds. */
|
|
40
50
|
function parseRetryAfter(header) {
|
|
41
51
|
if (!header)
|
|
@@ -61,7 +71,9 @@ function isRetryable(err) {
|
|
|
61
71
|
}
|
|
62
72
|
async function withRetry(fn, opts) {
|
|
63
73
|
const maxDelay = opts.maxDelayMs ?? 60000;
|
|
74
|
+
const rateLimitRetries = opts.rateLimitRetries ?? opts.maxRetries;
|
|
64
75
|
let attempt = 0;
|
|
76
|
+
let rateLimited = 0;
|
|
65
77
|
const outer = opts.signal;
|
|
66
78
|
while (true) {
|
|
67
79
|
if (outer?.aborted)
|
|
@@ -76,10 +88,14 @@ async function withRetry(fn, opts) {
|
|
|
76
88
|
catch (err) {
|
|
77
89
|
if (outer?.aborted)
|
|
78
90
|
throw abortError();
|
|
79
|
-
|
|
80
|
-
if (
|
|
91
|
+
const is429 = err instanceof ProviderHttpError && err.status === 429;
|
|
92
|
+
if (is429)
|
|
93
|
+
rateLimited += 1;
|
|
94
|
+
else
|
|
95
|
+
attempt += 1;
|
|
96
|
+
if (!isRetryable(err) || attempt > opts.maxRetries || rateLimited > rateLimitRetries)
|
|
81
97
|
throw err;
|
|
82
|
-
const backoff = opts.baseDelayMs * Math.pow(2, attempt - 1);
|
|
98
|
+
const backoff = opts.baseDelayMs * Math.pow(2, (is429 ? rateLimited : attempt) - 1);
|
|
83
99
|
const requested = err instanceof ProviderHttpError ? err.retryAfterMs : undefined;
|
|
84
100
|
const delay = Math.min(maxDelay, Math.max(backoff, requested ?? 0));
|
|
85
101
|
await sleep(delay, outer);
|
|
@@ -35,6 +35,8 @@ const BATCH_SIZE = 15;
|
|
|
35
35
|
exports.FALLBACK_QA_WARNING = 'translated with the backup translator; will be retried with the AI translator next run';
|
|
36
36
|
/** Keys re-sent after failing validation go in small batches with per-key notes. */
|
|
37
37
|
const REPAIR_BATCH_SIZE = 5;
|
|
38
|
+
/** Consecutive fallback batches that translate nothing before the fallback is given up on for a locale. */
|
|
39
|
+
const FALLBACK_MAX_EMPTY_BATCHES = 2;
|
|
38
40
|
const TRANSLATE_CONCURRENCY = 3; // Max concurrent locales/batches
|
|
39
41
|
/** Fragments of placeholder tokens ([#VAR_0#], the translator's {#0}) left in a translation. */
|
|
40
42
|
const PLACEHOLDER_DEBRIS = /\[#|#\]|\[\{#|\{#\d+\}|#VAR_\d+/;
|
|
@@ -1002,7 +1004,15 @@ configuredFormality) {
|
|
|
1002
1004
|
}).map((b) => (b.plain ? { ...b, ...b.plain, icu: false, countArgs: undefined, plain: undefined } : b));
|
|
1003
1005
|
if (toFallback.length > 0) {
|
|
1004
1006
|
logger_1.engineLogger.warn('LLM translator unavailable; trying the fallback translator', { count: toFallback.length, targetLang });
|
|
1007
|
+
// A fallback that is down fails every batch after a timeout: stop after
|
|
1008
|
+
// two empty batches in a row (the keys stay failed and the next run retries them).
|
|
1009
|
+
let emptyBatches = 0;
|
|
1005
1010
|
for (const batch of chunk(toFallback, BATCH_SIZE)) {
|
|
1011
|
+
if (emptyBatches >= FALLBACK_MAX_EMPTY_BATCHES) {
|
|
1012
|
+
logger_1.engineLogger.warn('Fallback translator is not producing translations; skipping the rest for this locale', { targetLang });
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
const before = fellBack.size;
|
|
1006
1016
|
try {
|
|
1007
1017
|
const keyResults = await fallback.translateBatch({
|
|
1008
1018
|
entries: batch.map((b) => ({ key: b.key, value: b.sendText, parentContext: contextMap?.[b.key] })),
|
|
@@ -1022,6 +1032,7 @@ configuredFormality) {
|
|
|
1022
1032
|
catch (error) {
|
|
1023
1033
|
logger_1.engineLogger.error('Fallback translation batch failed', { error: error instanceof Error ? error.message : String(error), targetLang });
|
|
1024
1034
|
}
|
|
1035
|
+
emptyBatches = fellBack.size > before ? 0 : emptyBatches + 1;
|
|
1025
1036
|
}
|
|
1026
1037
|
}
|
|
1027
1038
|
const icuToFallback = prepared.filter((b) => {
|
|
@@ -341,6 +341,19 @@ async function findWorkspaceApp(workspacePath, rootPackageJson) {
|
|
|
341
341
|
if (await (0, file_utils_1.isDirectory)(dir))
|
|
342
342
|
candidates.push(dir);
|
|
343
343
|
}
|
|
344
|
+
// Without a workspaces field: apps deeper down (apps/web, frontend/apps/web),
|
|
345
|
+
// nearest first, as far as detectStack looks before the project is created.
|
|
346
|
+
const nested = await (0, fast_glob_1.default)(['*/*/package.json', '*/*/*/package.json'].slice(0, stack_1.MAX_APP_DEPTH - 1), {
|
|
347
|
+
cwd: workspacePath,
|
|
348
|
+
onlyFiles: true,
|
|
349
|
+
ignore: ['**/node_modules/**', '**/.*/**'],
|
|
350
|
+
});
|
|
351
|
+
const depthOf = (p) => p.split('/').length;
|
|
352
|
+
for (const pkg of nested.sort((a, b) => depthOf(a) - depthOf(b) || a.localeCompare(b))) {
|
|
353
|
+
const dir = path.join(workspacePath, path.dirname(pkg));
|
|
354
|
+
if (!candidates.includes(dir))
|
|
355
|
+
candidates.push(dir);
|
|
356
|
+
}
|
|
344
357
|
for (const dir of candidates) {
|
|
345
358
|
const subPkg = await (0, file_utils_1.readJsonFile)(path.join(dir, 'package.json'));
|
|
346
359
|
if (!subPkg)
|
package/dist/runtime/types.js
CHANGED
|
@@ -68,4 +68,13 @@ exports.JSX_TRANSLATABLE_ATTRS = [
|
|
|
68
68
|
'accessibilityHint',
|
|
69
69
|
'label',
|
|
70
70
|
'description',
|
|
71
|
+
// Common copy props of custom components (<ScreenHeader subtitle="…" />, <Toast message="…" />).
|
|
72
|
+
'subtitle',
|
|
73
|
+
'heading',
|
|
74
|
+
'caption',
|
|
75
|
+
'message',
|
|
76
|
+
'hint',
|
|
77
|
+
'helperText',
|
|
78
|
+
'emptyText',
|
|
79
|
+
'tooltip',
|
|
71
80
|
];
|
|
@@ -51,6 +51,7 @@ exports.createMessageTCall = createMessageTCall;
|
|
|
51
51
|
const generator_1 = __importDefault(require("@babel/generator"));
|
|
52
52
|
const t = __importStar(require("@babel/types"));
|
|
53
53
|
const string_utils_1 = require("./string-utils");
|
|
54
|
+
const icu_message_1 = require("./icu-message");
|
|
54
55
|
/** Phrasing elements that live inside a sentence. Anything else is block-level. */
|
|
55
56
|
const INLINE_TAGS = new Set([
|
|
56
57
|
'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'data', 'del', 'dfn', 'em', 'i', 'ins', 'kbd',
|
|
@@ -68,7 +69,6 @@ const RESERVED_NAMES = new Set([
|
|
|
68
69
|
'context', 'defaultValue', 'fallbackLng', 'interpolation', 'joinArrays', 'keySeparator', 'lng', 'lngs',
|
|
69
70
|
'ns', 'nsSeparator', 'ordinal', 'postProcess', 'replace', 'returnDetails', 'returnObjects', 'skipInterpolation',
|
|
70
71
|
]);
|
|
71
|
-
const COUNT_NAME = /^(?:count|total|num|n|length)$|(?:Count|Length)$/;
|
|
72
72
|
/** Words ending in "s" that are not regular plural nouns. */
|
|
73
73
|
const NOT_PLURAL_NOUNS = new Set([
|
|
74
74
|
'is', 'was', 'has', 'does', 'this', 'its', 'his', 'hers', 'ours', 'yours', 'theirs', 'us', 'yes', 'plus',
|
|
@@ -587,7 +587,9 @@ function singular(word) {
|
|
|
587
587
|
* that doesn't agree with it ("in", "left", "selected", …).
|
|
588
588
|
*/
|
|
589
589
|
function makePlural(pieces, entries) {
|
|
590
|
-
|
|
590
|
+
// The same rule translations use to add plurals (`count`, `itemCount`, and counted nouns
|
|
591
|
+
// like `likes` or `files`), so the source gets a plural whenever its translations do.
|
|
592
|
+
const countLike = entries.filter((e) => e.kind === 'placeholder' && (0, icu_message_1.isCountLikeName)(e.name));
|
|
591
593
|
if (countLike.length !== 1)
|
|
592
594
|
return undefined;
|
|
593
595
|
// `data?.count` or `n ?? 0` may be undefined at runtime → "NaN items".
|
|
@@ -185,7 +185,17 @@ function analyzeModuleConstants(ast) {
|
|
|
185
185
|
});
|
|
186
186
|
return plans;
|
|
187
187
|
}
|
|
188
|
-
|
|
188
|
+
/** `[...] as const`, `{...} satisfies T`, `<T>[...]`, `([...])`: the list itself. */
|
|
189
|
+
function unwrapExpression(p) {
|
|
190
|
+
let cur = p;
|
|
191
|
+
while (cur.isTSAsExpression() || cur.isTSSatisfiesExpression() || cur.isTSTypeAssertion() || cur.isParenthesizedExpression()) {
|
|
192
|
+
cur = cur.get('expression');
|
|
193
|
+
}
|
|
194
|
+
return cur;
|
|
195
|
+
}
|
|
196
|
+
function planFor({ name, init: declared, references, reassigned, exported, anchor, insert }) {
|
|
197
|
+
// A list written `as const` (common for tab and option lists) was skipped without a report.
|
|
198
|
+
const init = unwrapExpression(declared);
|
|
189
199
|
const isCopy = (s) => (0, string_utils_1.isTranslatableText)(s.trim());
|
|
190
200
|
// Per "field" ('' for an array of strings): the UI-copy literals that would
|
|
191
201
|
// become keys, every translatable literal (reported if not provable), and
|
|
@@ -11,5 +11,10 @@
|
|
|
11
11
|
export declare function isLatinScript(locale: string): boolean;
|
|
12
12
|
/** Letters left once placeholders, tags and entities are removed. */
|
|
13
13
|
export declare function hasWords(text: string | undefined): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Only acronyms ("API", "PDF", "URL", "HTTP/2"): written the same in every
|
|
16
|
+
* script, so Japanese or Hindi keeping them is a translation, not a miss.
|
|
17
|
+
*/
|
|
18
|
+
export declare function isAcronymOnly(text: string): boolean;
|
|
14
19
|
/** `translated` is the untouched source, into a language where that cannot be a translation. */
|
|
15
20
|
export declare function isUntranslatedInto(source: string, translated: string, targetLocale: string): boolean;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.isLatinScript = isLatinScript;
|
|
13
13
|
exports.hasWords = hasWords;
|
|
14
|
+
exports.isAcronymOnly = isAcronymOnly;
|
|
14
15
|
exports.isUntranslatedInto = isUntranslatedInto;
|
|
15
16
|
/** Is the locale written in Latin script (where an unchanged word can be a real translation)? */
|
|
16
17
|
function isLatinScript(locale) {
|
|
@@ -28,7 +29,15 @@ function hasWords(text) {
|
|
|
28
29
|
const stripped = text.replace(/%\(\w+\)[-#0 +]*\d*(?:\.\d+)?[a-zA-Z]|%[sdif%]|\{[^{}]*\}|<[^>]*>|&[#\w]+;|\[\s*#\s*VAR_\d+\s*#\s*\]/gi, ' ');
|
|
29
30
|
return /\p{L}{2,}/u.test(stripped);
|
|
30
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Only acronyms ("API", "PDF", "URL", "HTTP/2"): written the same in every
|
|
34
|
+
* script, so Japanese or Hindi keeping them is a translation, not a miss.
|
|
35
|
+
*/
|
|
36
|
+
function isAcronymOnly(text) {
|
|
37
|
+
const words = text.match(/\p{L}[\p{L}\p{N}]*/gu);
|
|
38
|
+
return !!words && words.every((w) => /^\p{Lu}[\p{Lu}\p{N}]+$/u.test(w));
|
|
39
|
+
}
|
|
31
40
|
/** `translated` is the untouched source, into a language where that cannot be a translation. */
|
|
32
41
|
function isUntranslatedInto(source, translated, targetLocale) {
|
|
33
|
-
return !isLatinScript(targetLocale) && translated.trim() === source.trim() && hasWords(source);
|
|
42
|
+
return !isLatinScript(targetLocale) && translated.trim() === source.trim() && hasWords(source) && !isAcronymOnly(source);
|
|
34
43
|
}
|
package/package.json
CHANGED