@weglot/translate-react 0.2.0 → 0.2.1
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/README.md +59 -15
- package/build/plugin/build-translator.cjs +2 -1
- package/build/plugin/build-translator.mjs +2 -1
- package/build/plugin/build-translator.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/runtime/translate-dynamic.cjs +1 -1
- package/build/runtime/translate-dynamic.mjs +1 -1
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/translation-service.cjs +3 -2
- package/build/translators/translation-service.mjs +3 -2
- package/build/translators/translation-service.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +62 -34
- package/build/translators/weglot/api-client.mjs +62 -34
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/translators/weglot/translator.cjs +19 -1
- package/build/translators/weglot/translator.mjs +19 -1
- package/build/translators/weglot/translator.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,13 +9,19 @@ target languages are read from your Weglot project settings, and
|
|
|
9
9
|
translations appear in your Weglot dashboard where you can review and edit
|
|
10
10
|
them.
|
|
11
11
|
|
|
12
|
+
## Requirements
|
|
13
|
+
|
|
14
|
+
- React 19, with Vite, Webpack or Next.js 15/16
|
|
15
|
+
- Node.js 20.9 or later
|
|
16
|
+
- A Weglot project: its key is in your Weglot dashboard
|
|
17
|
+
|
|
12
18
|
## Getting started
|
|
13
19
|
|
|
14
20
|
```bash
|
|
15
|
-
npm install @weglot/translate-react
|
|
21
|
+
npm install @weglot/translate-react
|
|
16
22
|
```
|
|
17
23
|
|
|
18
|
-
Set your project key in `.env
|
|
24
|
+
Set your project key in `.env`, and keep that file out of version control:
|
|
19
25
|
|
|
20
26
|
```bash
|
|
21
27
|
WEGLOT_API_KEY=your_weglot_project_key
|
|
@@ -44,6 +50,9 @@ root.render(
|
|
|
44
50
|
);
|
|
45
51
|
```
|
|
46
52
|
|
|
53
|
+
Webpack works the same way, with `weglotPlugin` from
|
|
54
|
+
`@weglot/translate-react/webpack`.
|
|
55
|
+
|
|
47
56
|
### Next.js
|
|
48
57
|
|
|
49
58
|
```ts
|
|
@@ -57,7 +66,48 @@ export default async function (): Promise<NextConfig> {
|
|
|
57
66
|
}
|
|
58
67
|
```
|
|
59
68
|
|
|
60
|
-
Wrap your root layout with `WeglotProvider
|
|
69
|
+
Wrap your root layout with the Next.js `WeglotProvider`:
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
// app/layout.tsx
|
|
73
|
+
import { WeglotProvider } from "@weglot/translate-react/react/next";
|
|
74
|
+
|
|
75
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
76
|
+
return (
|
|
77
|
+
<html>
|
|
78
|
+
<body>
|
|
79
|
+
<WeglotProvider>{children}</WeglotProvider>
|
|
80
|
+
</body>
|
|
81
|
+
</html>
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Generated files
|
|
87
|
+
|
|
88
|
+
- `<sourceRoot>/weglot/cache/<locale>.json`: the translations received from
|
|
89
|
+
Weglot. Commit it to build without calling the API (see `cache-only` below),
|
|
90
|
+
or ignore it and let each build fetch what it lacks.
|
|
91
|
+
- `public/translations/<locale>.json`: written by every build. Add it to
|
|
92
|
+
`.gitignore`.
|
|
93
|
+
|
|
94
|
+
### Switching language
|
|
95
|
+
|
|
96
|
+
The visitor's language is kept in a `locale` cookie; URLs do not change. Let
|
|
97
|
+
visitors pick it with `LocaleSwitcher`:
|
|
98
|
+
|
|
99
|
+
```tsx
|
|
100
|
+
import { LocaleSwitcher } from "@weglot/translate-react/react";
|
|
101
|
+
|
|
102
|
+
<LocaleSwitcher
|
|
103
|
+
locales={[
|
|
104
|
+
{ code: "en", label: "English" },
|
|
105
|
+
{ code: "fr", label: "Français" },
|
|
106
|
+
]}
|
|
107
|
+
/>
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Or build your own with `useWeglotContext()` (see React API).
|
|
61
111
|
|
|
62
112
|
## What gets translated
|
|
63
113
|
|
|
@@ -129,9 +179,14 @@ Languages are not configured here: they come from your Weglot project.
|
|
|
129
179
|
Weglot generates translations with an LLM, so new strings can take a moment:
|
|
130
180
|
the build waits for them up to `translationTimeout`. If some are still not
|
|
131
181
|
ready, the build fails, keeping the ones it received in the local cache, so
|
|
132
|
-
building again
|
|
182
|
+
building again picks up where it stopped (with Next.js, delete the `.next`
|
|
183
|
+
folder first). In dev,
|
|
133
184
|
strings not ready in time show in the source language until the next reload.
|
|
134
185
|
|
|
186
|
+
A string Weglot will not translate, such as one made only of digits, does not
|
|
187
|
+
fail the build: it is served in the source language with a warning, and asked
|
|
188
|
+
for again on the next build.
|
|
189
|
+
|
|
135
190
|
## React API
|
|
136
191
|
|
|
137
192
|
```tsx
|
|
@@ -184,17 +239,6 @@ pnpm --filter @weglot/translate-react test
|
|
|
184
239
|
pnpm --filter @weglot/translate-react build
|
|
185
240
|
```
|
|
186
241
|
|
|
187
|
-
### Releasing
|
|
188
|
-
|
|
189
|
-
Bump `version` in `package.json`, merge, then push a matching tag:
|
|
190
|
-
|
|
191
|
-
```bash
|
|
192
|
-
git tag v0.1.1 && git push origin v0.1.1
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
The Release workflow tests, builds and publishes to npm under the `next`
|
|
196
|
-
dist-tag (set by `DIST_TAG` in `.github/workflows/release.yml`).
|
|
197
|
-
|
|
198
242
|
## License
|
|
199
243
|
|
|
200
244
|
Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
@@ -82,7 +82,8 @@ async function processBuildTranslations(options) {
|
|
|
82
82
|
locale,
|
|
83
83
|
error: `${result.errors.length} translation(s) failed`
|
|
84
84
|
});
|
|
85
|
-
} else require_logger.logger.
|
|
85
|
+
} else if (result.stats.untranslated) require_logger.logger.warn(`⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`);
|
|
86
|
+
else require_logger.logger.info(`✅ ${locale} completed successfully`);
|
|
86
87
|
});
|
|
87
88
|
await Promise.all(localePromises);
|
|
88
89
|
if (errors.length > 0) {
|
|
@@ -79,7 +79,8 @@ async function processBuildTranslations(options) {
|
|
|
79
79
|
locale,
|
|
80
80
|
error: `${result.errors.length} translation(s) failed`
|
|
81
81
|
});
|
|
82
|
-
} else logger.
|
|
82
|
+
} else if (result.stats.untranslated) logger.warn(`⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`);
|
|
83
|
+
else logger.info(`✅ ${locale} completed successfully`);
|
|
83
84
|
});
|
|
84
85
|
await Promise.all(localePromises);
|
|
85
86
|
if (errors.length > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-translator.mjs","names":["translationServer: TranslationServer | undefined","stats: BuildTranslationResult[\"stats\"]","errors: Array<{ locale: LocaleCode; error: string }>","skipped: LocaleCode[]","missingLocales: string[]","incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>"],"sources":["../../src/plugin/build-translator.ts"],"sourcesContent":["/**\n * Build-time translation processor\n *\n * Handles translation generation and validation at build time\n * Supports two modes:\n * - \"translate\": Generate all translations, fail if translation fails\n * - \"cache-only\": Validate cache completeness, fail if incomplete\n */\n// TODO (AleksandrSl 08/12/2025): Add ICU validation for messages? The problem is that we don't know which will be rendered as a simple text\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { WeglotConfig, MetadataSchema } from \"../types\";\nimport { logger } from \"../utils/logger\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport { loadMetadata } from \"../metadata/manager\";\nimport {\n createCache,\n type TranslationCache,\n TranslationService,\n} from \"../translators\";\nimport { dictionaryFrom } from \"../translators/api\";\nimport type { LocaleCode } from \"../locale\";\n\nexport interface BuildTranslationOptions {\n config: WeglotConfig;\n publicOutputPath: string;\n metadataFilePath: string;\n}\n\nexport interface BuildTranslationResult {\n /**\n * Whether the build succeeded\n */\n success: boolean;\n\n /**\n * Error message if build failed\n */\n error?: string;\n\n /**\n * Translation statistics per locale\n */\n stats: Record<\n string,\n {\n total: number;\n translated: number;\n failed: number;\n }\n >;\n}\n\n/**\n * Process translations at build time\n *\n * @throws Error if validation or translation fails (causes build to fail)\n */\nexport async function processBuildTranslations(\n options: BuildTranslationOptions,\n): Promise<BuildTranslationResult> {\n const { config, publicOutputPath, metadataFilePath } = options;\n\n // Determine build mode (env var > options > config)\n const buildMode =\n (process.env.WEGLOT_BUILD_MODE as \"translate\" | \"cache-only\") ||\n config.buildMode;\n\n logger.info(`🌍 Build mode: ${buildMode}`);\n\n const metadata = await loadMetadata(metadataFilePath, true);\n\n if (!metadata || Object.keys(metadata).length === 0) {\n logger.info(\"No translations to process (metadata is empty)\");\n return {\n success: true,\n stats: {},\n };\n }\n\n const totalEntries = Object.keys(metadata).length;\n logger.info(`📊 Found ${totalEntries} translatable entries`);\n\n const cache = createCache(config);\n\n // Handle cache-only mode\n if (buildMode === \"cache-only\") {\n logger.info(\"🔍 Validating translation cache...\");\n await validateCache(config, metadata, cache);\n logger.info(\"✅ Cache validation passed\");\n\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n return {\n success: true,\n stats: buildCacheStats(config, metadata),\n };\n }\n\n // Handle translate mode\n logger.info(\"🔄 Generating translations...\");\n let translationServer: TranslationServer | undefined;\n\n try {\n translationServer = await startTranslationServer({\n translationService: new TranslationService(config, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n config,\n });\n\n const allLocales = config.targetLocales;\n\n logger.info(`Processing translations for ${allLocales.length} locale(s)...`);\n\n const stats: BuildTranslationResult[\"stats\"] = {};\n const errors: Array<{ locale: LocaleCode; error: string }> = [];\n const skipped: LocaleCode[] = [];\n\n // Translate all locales in parallel\n const localePromises = allLocales.map(async (locale) => {\n logger.info(`Translating to ${locale}...`);\n\n const result = await translationServer!.translateAll(locale);\n\n stats[locale] = {\n total: totalEntries,\n translated: Object.keys(result.translations).length,\n failed: result.stats.failed,\n };\n\n if (result.unsupportedLocale) {\n // Not a build failure: the pair is refused, so the locale is served as source.\n skipped.push(locale);\n // An empty dictionary marks the locale deliberately untranslated. Never\n // overwrite one: an earlier run may hold real translations.\n if (!(await cache.has(locale))) {\n await cache.set(locale, {});\n }\n logger.warn(\n `⏭️ Skipped ${locale}: the Weglot API does not translate ${config.sourceLocale} to ${locale}. Remove the language from the project or ask Weglot support to enable the pair.`,\n );\n } else if (result.errors.length > 0) {\n logger.warn(\n `⚠️ ${result.errors.length} translation error(s) for ${locale}`,\n );\n errors.push({\n locale,\n error: `${result.errors.length} translation(s) failed`,\n });\n } else {\n logger.info(`✅ ${locale} completed successfully`);\n }\n });\n\n await Promise.all(localePromises);\n\n // Fail build if any translations failed in translate mode\n if (errors.length > 0) {\n const errorMsg = formatTranslationErrors(errors);\n logger.error(errorMsg);\n process.exit(1);\n }\n\n // Copy cache to public directory if requested\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n if (skipped.length > 0) {\n logger.warn(\n `✅ Translation generation completed, without ${skipped.join(\", \")}`,\n );\n } else {\n logger.info(\"✅ Translation generation completed successfully\");\n }\n\n return {\n success: true,\n stats,\n };\n } catch (error) {\n logger.error(\n \"❌ Translation generation failed:\\n\",\n error instanceof Error ? error.message : error,\n );\n process.exit(1);\n } finally {\n if (translationServer) {\n await translationServer.stop();\n logger.info(\"✅ Translation server stopped\");\n }\n }\n}\n\n/**\n * Validate that all required translations exist in cache\n * @throws Error if cache is incomplete or missing\n */\nasync function validateCache(\n config: WeglotConfig,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n const allHashes = Object.keys(metadata);\n const missingLocales: string[] = [];\n const incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }> = [];\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n try {\n const entries = await cache.get(locale);\n\n if (Object.keys(entries).length === 0) {\n // Emptiness is deliberate: an untranslatable locale still gets a file.\n if (await cache.has(locale)) {\n logger.warn(\n `⏭️ ${locale} holds no translations and is served untranslated`,\n );\n continue;\n }\n missingLocales.push(locale);\n logger.debug(`Cache file not found for ${locale}`);\n continue;\n }\n\n const missingHashes = allHashes.filter((hash) => !entries[hash]);\n\n if (missingHashes.length > 0) {\n incompleteLocales.push({\n locale,\n missing: missingHashes.length,\n total: allHashes.length,\n });\n\n // Log first few missing hashes for debugging\n logger.debug(\n `Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(\", \")}${\n missingHashes.length > 5 ? \"...\" : \"\"\n }`,\n );\n }\n } catch (error) {\n missingLocales.push(locale);\n logger.debug(`Failed to read cache for ${locale}:`, error);\n }\n }\n\n if (missingLocales.length > 0 || incompleteLocales.length > 0) {\n const errorMsg = formatCacheValidationError(\n missingLocales,\n incompleteLocales,\n );\n logger.error(errorMsg);\n process.exit(1);\n }\n}\n\nfunction buildCacheStats(\n config: WeglotConfig,\n metadata: MetadataSchema,\n): BuildTranslationResult[\"stats\"] {\n const totalEntries = Object.keys(metadata).length;\n const stats: BuildTranslationResult[\"stats\"] = {};\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n stats[locale] = {\n total: totalEntries,\n translated: totalEntries, // Assumed complete if validation passed\n failed: 0,\n };\n }\n\n return stats;\n}\n\nasync function copyStaticFiles(\n config: WeglotConfig,\n publicOutputPath: string,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n logger.info(`📦 Generating static translation files in ${publicOutputPath}`);\n\n await fs.mkdir(publicOutputPath, { recursive: true });\n\n const usedHashes = new Set(Object.keys(metadata));\n logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n const publicFilePath = path.join(publicOutputPath, `${locale}.json`);\n\n try {\n const entries = await cache.get(locale, Array.from(usedHashes));\n const outputData = dictionaryFrom(locale, entries);\n\n await fs.writeFile(\n publicFilePath,\n JSON.stringify(outputData, null, 2),\n \"utf-8\",\n );\n\n logger.info(\n `✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`,\n );\n } catch (error) {\n logger.error(`❌ Failed to generate ${locale}.json:`, error);\n process.exit(1);\n }\n }\n}\n\nfunction formatCacheValidationError(\n missingLocales: string[],\n incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>,\n): string {\n let msg = \"❌ Cache validation failed in cache-only mode:\\n\\n\";\n\n if (missingLocales.length > 0) {\n msg += ` 📁 Missing cache files:\\n`;\n msg += missingLocales.map((locale) => ` - ${locale}.json`).join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n if (incompleteLocales.length > 0) {\n msg += ` 📊 Incomplete cache:\\n`;\n msg += incompleteLocales\n .map(\n (item) =>\n ` - ${item.locale}: ${item.missing}/${item.total} translations missing`,\n )\n .join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n msg += ` 💡 To fix:\\n`;\n msg += ` 1. Set WEGLOT_BUILD_MODE=translate to generate translations\\n`;\n msg += ` 2. Commit the generated weglot/cache/*.json files\\n`;\n msg += ` 3. Ensure translation API keys are available if generating translations`;\n\n return msg;\n}\n\nfunction formatTranslationErrors(\n errors: Array<{ locale: LocaleCode; error: string }>,\n): string {\n let msg = \"❌ Translation generation failed:\\n\\n\";\n\n msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join(\"\\n\");\n\n msg += \"\\n\\n\";\n msg += ` 💡 Translation errors must be resolved in \"translate\" mode.\\n`;\n msg += ` If Weglot was still generating translations, build again without the\\n`;\n msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\\n`;\n msg += ` to wait longer.\\n`;\n msg += ` Otherwise, check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,yBACpB,SACiC;CACjC,MAAM,EAAE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QAAQ,MAAM,KAAK,WAAW,CAAC;GAC/D,MAAM,aAAa,eAAe,QAAQ,QAAQ;AAElD,SAAM,GAAG,UACP,gBACA,KAAK,UAAU,YAAY,MAAM,EAAE,EACnC,QACD;AAED,UAAO,KACL,eAAe,OAAO,SAAS,OAAO,KAAK,QAAQ,CAAC,OAAO,gBAC5D;WACM,OAAO;AACd,UAAO,MAAM,wBAAwB,OAAO,SAAS,MAAM;AAC3D,WAAQ,KAAK,EAAE;;;;AAKrB,SAAS,2BACP,gBACA,mBAKQ;CACR,IAAI,MAAM;AAEV,KAAI,eAAe,SAAS,GAAG;AAC7B,SAAO;AACP,SAAO,eAAe,KAAK,WAAW,SAAS,OAAO,OAAO,CAAC,KAAK,KAAK;AACxE,SAAO;;AAGT,KAAI,kBAAkB,SAAS,GAAG;AAChC,SAAO;AACP,SAAO,kBACJ,KACE,SACC,SAAS,KAAK,OAAO,IAAI,KAAK,QAAQ,GAAG,KAAK,MAAM,uBACvD,CACA,KAAK,KAAK;AACb,SAAO;;AAGT,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO;;AAGT,SAAS,wBACP,QACQ;CACR,IAAI,MAAM;AAEV,QAAO,OAAO,KAAK,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,QAAQ,CAAC,KAAK,KAAK;AAExE,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
1
|
+
{"version":3,"file":"build-translator.mjs","names":["translationServer: TranslationServer | undefined","stats: BuildTranslationResult[\"stats\"]","errors: Array<{ locale: LocaleCode; error: string }>","skipped: LocaleCode[]","missingLocales: string[]","incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>"],"sources":["../../src/plugin/build-translator.ts"],"sourcesContent":["/**\n * Build-time translation processor\n *\n * Handles translation generation and validation at build time\n * Supports two modes:\n * - \"translate\": Generate all translations, fail if translation fails\n * - \"cache-only\": Validate cache completeness, fail if incomplete\n */\n// TODO (AleksandrSl 08/12/2025): Add ICU validation for messages? The problem is that we don't know which will be rendered as a simple text\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { WeglotConfig, MetadataSchema } from \"../types\";\nimport { logger } from \"../utils/logger\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport { loadMetadata } from \"../metadata/manager\";\nimport {\n createCache,\n type TranslationCache,\n TranslationService,\n} from \"../translators\";\nimport { dictionaryFrom } from \"../translators/api\";\nimport type { LocaleCode } from \"../locale\";\n\nexport interface BuildTranslationOptions {\n config: WeglotConfig;\n publicOutputPath: string;\n metadataFilePath: string;\n}\n\nexport interface BuildTranslationResult {\n /**\n * Whether the build succeeded\n */\n success: boolean;\n\n /**\n * Error message if build failed\n */\n error?: string;\n\n /**\n * Translation statistics per locale\n */\n stats: Record<\n string,\n {\n total: number;\n translated: number;\n failed: number;\n }\n >;\n}\n\n/**\n * Process translations at build time\n *\n * @throws Error if validation or translation fails (causes build to fail)\n */\nexport async function processBuildTranslations(\n options: BuildTranslationOptions,\n): Promise<BuildTranslationResult> {\n const { config, publicOutputPath, metadataFilePath } = options;\n\n // Determine build mode (env var > options > config)\n const buildMode =\n (process.env.WEGLOT_BUILD_MODE as \"translate\" | \"cache-only\") ||\n config.buildMode;\n\n logger.info(`🌍 Build mode: ${buildMode}`);\n\n const metadata = await loadMetadata(metadataFilePath, true);\n\n if (!metadata || Object.keys(metadata).length === 0) {\n logger.info(\"No translations to process (metadata is empty)\");\n return {\n success: true,\n stats: {},\n };\n }\n\n const totalEntries = Object.keys(metadata).length;\n logger.info(`📊 Found ${totalEntries} translatable entries`);\n\n const cache = createCache(config);\n\n // Handle cache-only mode\n if (buildMode === \"cache-only\") {\n logger.info(\"🔍 Validating translation cache...\");\n await validateCache(config, metadata, cache);\n logger.info(\"✅ Cache validation passed\");\n\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n return {\n success: true,\n stats: buildCacheStats(config, metadata),\n };\n }\n\n // Handle translate mode\n logger.info(\"🔄 Generating translations...\");\n let translationServer: TranslationServer | undefined;\n\n try {\n translationServer = await startTranslationServer({\n translationService: new TranslationService(config, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n config,\n });\n\n const allLocales = config.targetLocales;\n\n logger.info(`Processing translations for ${allLocales.length} locale(s)...`);\n\n const stats: BuildTranslationResult[\"stats\"] = {};\n const errors: Array<{ locale: LocaleCode; error: string }> = [];\n const skipped: LocaleCode[] = [];\n\n // Translate all locales in parallel\n const localePromises = allLocales.map(async (locale) => {\n logger.info(`Translating to ${locale}...`);\n\n const result = await translationServer!.translateAll(locale);\n\n stats[locale] = {\n total: totalEntries,\n translated: Object.keys(result.translations).length,\n failed: result.stats.failed,\n };\n\n if (result.unsupportedLocale) {\n // Not a build failure: the pair is refused, so the locale is served as source.\n skipped.push(locale);\n // An empty dictionary marks the locale deliberately untranslated. Never\n // overwrite one: an earlier run may hold real translations.\n if (!(await cache.has(locale))) {\n await cache.set(locale, {});\n }\n logger.warn(\n `⏭️ Skipped ${locale}: the Weglot API does not translate ${config.sourceLocale} to ${locale}. Remove the language from the project or ask Weglot support to enable the pair.`,\n );\n } else if (result.errors.length > 0) {\n logger.warn(\n `⚠️ ${result.errors.length} translation error(s) for ${locale}`,\n );\n errors.push({\n locale,\n error: `${result.errors.length} translation(s) failed`,\n });\n } else if (result.stats.untranslated) {\n logger.warn(\n `⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`,\n );\n } else {\n logger.info(`✅ ${locale} completed successfully`);\n }\n });\n\n await Promise.all(localePromises);\n\n // Fail build if any translations failed in translate mode\n if (errors.length > 0) {\n const errorMsg = formatTranslationErrors(errors);\n logger.error(errorMsg);\n process.exit(1);\n }\n\n // Copy cache to public directory if requested\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n if (skipped.length > 0) {\n logger.warn(\n `✅ Translation generation completed, without ${skipped.join(\", \")}`,\n );\n } else {\n logger.info(\"✅ Translation generation completed successfully\");\n }\n\n return {\n success: true,\n stats,\n };\n } catch (error) {\n logger.error(\n \"❌ Translation generation failed:\\n\",\n error instanceof Error ? error.message : error,\n );\n process.exit(1);\n } finally {\n if (translationServer) {\n await translationServer.stop();\n logger.info(\"✅ Translation server stopped\");\n }\n }\n}\n\n/**\n * Validate that all required translations exist in cache\n * @throws Error if cache is incomplete or missing\n */\nasync function validateCache(\n config: WeglotConfig,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n const allHashes = Object.keys(metadata);\n const missingLocales: string[] = [];\n const incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }> = [];\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n try {\n const entries = await cache.get(locale);\n\n if (Object.keys(entries).length === 0) {\n // Emptiness is deliberate: an untranslatable locale still gets a file.\n if (await cache.has(locale)) {\n logger.warn(\n `⏭️ ${locale} holds no translations and is served untranslated`,\n );\n continue;\n }\n missingLocales.push(locale);\n logger.debug(`Cache file not found for ${locale}`);\n continue;\n }\n\n const missingHashes = allHashes.filter((hash) => !entries[hash]);\n\n if (missingHashes.length > 0) {\n incompleteLocales.push({\n locale,\n missing: missingHashes.length,\n total: allHashes.length,\n });\n\n // Log first few missing hashes for debugging\n logger.debug(\n `Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(\", \")}${\n missingHashes.length > 5 ? \"...\" : \"\"\n }`,\n );\n }\n } catch (error) {\n missingLocales.push(locale);\n logger.debug(`Failed to read cache for ${locale}:`, error);\n }\n }\n\n if (missingLocales.length > 0 || incompleteLocales.length > 0) {\n const errorMsg = formatCacheValidationError(\n missingLocales,\n incompleteLocales,\n );\n logger.error(errorMsg);\n process.exit(1);\n }\n}\n\nfunction buildCacheStats(\n config: WeglotConfig,\n metadata: MetadataSchema,\n): BuildTranslationResult[\"stats\"] {\n const totalEntries = Object.keys(metadata).length;\n const stats: BuildTranslationResult[\"stats\"] = {};\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n stats[locale] = {\n total: totalEntries,\n translated: totalEntries, // Assumed complete if validation passed\n failed: 0,\n };\n }\n\n return stats;\n}\n\nasync function copyStaticFiles(\n config: WeglotConfig,\n publicOutputPath: string,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n logger.info(`📦 Generating static translation files in ${publicOutputPath}`);\n\n await fs.mkdir(publicOutputPath, { recursive: true });\n\n const usedHashes = new Set(Object.keys(metadata));\n logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n const publicFilePath = path.join(publicOutputPath, `${locale}.json`);\n\n try {\n const entries = await cache.get(locale, Array.from(usedHashes));\n const outputData = dictionaryFrom(locale, entries);\n\n await fs.writeFile(\n publicFilePath,\n JSON.stringify(outputData, null, 2),\n \"utf-8\",\n );\n\n logger.info(\n `✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`,\n );\n } catch (error) {\n logger.error(`❌ Failed to generate ${locale}.json:`, error);\n process.exit(1);\n }\n }\n}\n\nfunction formatCacheValidationError(\n missingLocales: string[],\n incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>,\n): string {\n let msg = \"❌ Cache validation failed in cache-only mode:\\n\\n\";\n\n if (missingLocales.length > 0) {\n msg += ` 📁 Missing cache files:\\n`;\n msg += missingLocales.map((locale) => ` - ${locale}.json`).join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n if (incompleteLocales.length > 0) {\n msg += ` 📊 Incomplete cache:\\n`;\n msg += incompleteLocales\n .map(\n (item) =>\n ` - ${item.locale}: ${item.missing}/${item.total} translations missing`,\n )\n .join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n msg += ` 💡 To fix:\\n`;\n msg += ` 1. Set WEGLOT_BUILD_MODE=translate to generate translations\\n`;\n msg += ` 2. Commit the generated weglot/cache/*.json files\\n`;\n msg += ` 3. Ensure translation API keys are available if generating translations`;\n\n return msg;\n}\n\nfunction formatTranslationErrors(\n errors: Array<{ locale: LocaleCode; error: string }>,\n): string {\n let msg = \"❌ Translation generation failed:\\n\\n\";\n\n msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join(\"\\n\");\n\n msg += \"\\n\\n\";\n msg += ` 💡 Translation errors must be resolved in \"translate\" mode.\\n`;\n msg += ` If Weglot was still generating translations, build again without the\\n`;\n msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\\n`;\n msg += ` to wait longer.\\n`;\n msg += ` Otherwise, check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,yBACpB,SACiC;CACjC,MAAM,EAAE,QAAQ,kBAAkB,qBAAqB;CAGvD,MAAM,YACH,QAAQ,IAAI,qBACb,OAAO;AAET,QAAO,KAAK,kBAAkB,YAAY;CAE1C,MAAM,WAAW,MAAM,aAAa,kBAAkB,KAAK;AAE3D,KAAI,CAAC,YAAY,OAAO,KAAK,SAAS,CAAC,WAAW,GAAG;AACnD,SAAO,KAAK,iDAAiD;AAC7D,SAAO;GACL,SAAS;GACT,OAAO,EAAE;GACV;;CAGH,MAAM,eAAe,OAAO,KAAK,SAAS,CAAC;AAC3C,QAAO,KAAK,YAAY,aAAa,uBAAuB;CAE5D,MAAM,QAAQ,YAAY,OAAO;AAGjC,KAAI,cAAc,cAAc;AAC9B,SAAO,KAAK,qCAAqC;AACjD,QAAM,cAAc,QAAQ,UAAU,MAAM;AAC5C,SAAO,KAAK,4BAA4B;AAExC,MAAI,iBACF,OAAM,gBAAgB,QAAQ,kBAAkB,UAAU,MAAM;AAGlE,SAAO;GACL,SAAS;GACT,OAAO,gBAAgB,QAAQ,SAAS;GACzC;;AAIH,QAAO,KAAK,gCAAgC;CAC5C,IAAIA;AAEJ,KAAI;AACF,sBAAoB,MAAM,uBAAuB;GAC/C,oBAAoB,IA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,QAAO;AACP,QAAO;AAEP,QAAO;;AAGT,SAAS,wBACP,QACQ;CACR,IAAI,MAAM;AAEV,QAAO,OAAO,KAAK,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,QAAQ,CAAC,KAAK,KAAK;AAExE,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { WeglotProviderProps } from "../shared/WeglotProvider.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime3 from "react/jsx-runtime";
|
|
3
3
|
|
|
4
4
|
//#region src/react/server/ServerWeglotProvider.d.ts
|
|
5
5
|
declare function WeglotProvider({
|
|
6
6
|
initialLocale,
|
|
7
7
|
initialTranslations,
|
|
8
8
|
...rest
|
|
9
|
-
}: WeglotProviderProps): Promise<
|
|
9
|
+
}: WeglotProviderProps): Promise<react_jsx_runtime3.JSX.Element>;
|
|
10
10
|
//#endregion
|
|
11
11
|
export { WeglotProvider };
|
|
12
12
|
//# sourceMappingURL=ServerWeglotProvider.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LocaleCode } from "../../locale.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime1 from "react/jsx-runtime";
|
|
3
3
|
import { PropsWithChildren } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/react/shared/WeglotProvider.d.ts
|
|
@@ -54,7 +54,7 @@ declare function WeglotProvider__Dev({
|
|
|
54
54
|
initialTranslations,
|
|
55
55
|
router,
|
|
56
56
|
children
|
|
57
|
-
}: WeglotProviderProps):
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime1.JSX.Element;
|
|
58
58
|
//#endregion
|
|
59
59
|
export { WeglotProvider, WeglotProviderProps };
|
|
60
60
|
//# sourceMappingURL=WeglotProvider.d.cts.map
|
|
@@ -82,7 +82,7 @@ async function flush(key, locale, timeoutMs) {
|
|
|
82
82
|
continue;
|
|
83
83
|
}
|
|
84
84
|
try {
|
|
85
|
-
const translated = await require_timeout.withTimeout(client.translate({
|
|
85
|
+
const { words: translated } = await require_timeout.withTimeout(client.translate({
|
|
86
86
|
from: _weglot_translate_react_virtual_config.sourceLocale,
|
|
87
87
|
to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
|
|
88
88
|
words: chunk.map((word) => word.text),
|
|
@@ -81,7 +81,7 @@ async function flush(key, locale, timeoutMs) {
|
|
|
81
81
|
continue;
|
|
82
82
|
}
|
|
83
83
|
try {
|
|
84
|
-
const translated = await withTimeout(client.translate({
|
|
84
|
+
const { words: translated } = await withTimeout(client.translate({
|
|
85
85
|
from: sourceLocale,
|
|
86
86
|
to: apiLocales[locale] ?? locale,
|
|
87
87
|
words: chunk.map((word) => word.text),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. No cache: the API already stores repeated segments.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport {\n apiBaseUrl,\n apiLocales,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n};\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface PendingWord {\n text: string;\n type?: number;\n resolve: (translated: string) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type?: number,\n): Promise<string> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<string>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve(word.text));\n return;\n }\n\n const client = new WeglotApiClient(apiKey, apiBaseUrl);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n chunk.forEach((word) => word.resolve(word.text));\n continue;\n }\n\n try {\n const translated = await withTimeout(\n client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),\n live: true,\n }),\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === null) {\n // Still generating at Weglot; a later request gets the translation.\n logger.debug(\n `Weglot is still translating dynamic content for locale \"${locale}\".`,\n );\n } else if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(result ?? word.text);\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n chunk.forEach((word) => word.resolve(word.text));\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = enqueue(locale, text, timeoutMs);\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)),\n );\n return segmenter.apply(translated);\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,wBAAwB;;AA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Aa,OAAO;CAC9C,MAAM,OAAO,SAAS;CACtB,MAAM,MAAM,GAAG,SAAS,QAAQ,UAAU,CAAC,QAAQ;CACnD,MAAM,WAAW,MAAM,IAAI,IAAI;AAC/B,KAAI,SAAU,QAAO;CAErB,MAAM,UAAU,QAAQ,QAAQ,MAAM,UAAU;AAChD,OAAM,IAAI,KAAK,QAAQ;AACvB,QAAO;;;;;;AAOT,eAAsB,aACpB,MACA,UAAqC,EAAE,EACtB;AACjB,KAAI,CAAC,KAAK,MAAM,CAAE,QAAO;CAEzB,MAAM,SAAS,QAAQ,UAAW,MAAM,iBAAiB;AACzD,KAAI,CAAC,UAAU,WAAW,aAAc,QAAO;CAE/C,MAAM,YAAY,QAAQ,aAAa,OAAO;CAC9C,MAAM,YAAY,IAAI,cAAc,MAAM,kBAAkB;CAC5D,MAAM,WAAW,UAAU,SAAS;AACpC,KAAI,SAAS,WAAW,EAAG,QAAO;CAElC,MAAM,aAAa,MAAM,QAAQ,IAC/B,SAAS,KAAK,YAAY,QAAQ,QAAQ,QAAQ,GAAG,WAAW,QAAQ,EAAE,CAAC,CAC5E;AACD,QAAO,UAAU,MAAM,WAAW;;;AAIpC,eAAsB,YACpB,OACA,UAAqC,EAAE,EACpB;AACnB,QAAO,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. No cache: the API already stores repeated segments.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport {\n apiBaseUrl,\n apiLocales,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n};\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface PendingWord {\n text: string;\n type?: number;\n resolve: (translated: string) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type?: number,\n): Promise<string> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<string>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve(word.text));\n return;\n }\n\n const client = new WeglotApiClient(apiKey, apiBaseUrl);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n chunk.forEach((word) => word.resolve(word.text));\n continue;\n }\n\n try {\n const { words: translated } = await withTimeout(\n client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),\n live: true,\n }),\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === null) {\n // Not translated yet at Weglot; a later request gets the translation.\n logger.debug(\n `Weglot is still translating dynamic content for locale \"${locale}\".`,\n );\n } else if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(result ?? word.text);\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n chunk.forEach((word) => word.resolve(word.text));\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = enqueue(locale, text, timeoutMs);\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)),\n );\n return segmenter.apply(translated);\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,wBAAwB;;AAG9B,MAAM,0BAA0B;AAuBhC,IAAIA,SAGyC;CAC3C,QAAQ;CACR,WApByB;CAqBzB,eAzB8B;CA0B/B;;AAGD,SAAgB,4BACd,MACM;AACN,UAAS;EAAE,GAAG;EAAQ,GAAG;EAAM;;AAGjC,SAAS,gBAAoC;AAC3C,QAAO,OAAO,UAAU,QAAQ,IAAI;;AAYtC,MAAM,yBAAS,IAAI,KAA8B;AACjD,MAAM,yBAAS,IAAI,KAA8C;AAEjE,MAAM,YAAY,QAAoB,cACpC,GAAG,OAAO,QAAQ;;;AAIpB,MAAM,cAAc,4BAAY,IAAI,KAA8B,CAAC;AAEnE,SAAS,UAA+C;AACtD,KAAI;AACF,SAAO,aAAa;SACd;AACN,SAAO;;;AAIX,SAAS,QACP,QACA,MACA,WACA,MACiB;CACjB,MAAM,MAAM,SAAS,QAAQ,UAAU;AACvC,QAAO,IAAI,SAAiB,YAAY;EACtC,MAAM,QAAQ,OAAO,IAAI,IAAI,IAAI,EAAE;AACnC,QAAM,KAAK;GAAE;GAAM;GAAM;GAAS,CAAC;AACnC,SAAO,IAAI,KAAK,MAAM;AAEtB,MAAI,CAAC,OAAO,IAAI,IAAI,CAClB,QAAO,IACL,KACA,iBACQ,KAAK,MAAM,KAAK,QAAQ,UAAU,EACxC,OAAO,cACR,CACF;GAEH;;AAGJ,eAAe,MACb,KACA,QACA,WACe;AACf,QAAO,OAAO,IAAI;CAClB,MAAM,QAAQ,OAAO,IAAI,IAAI,IAAI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requestedHashes || Object.keys(metadata);
|
|
33
33
|
this.logger.debug(`Translation requested for ${workingHashes.length} hashes in locale: ${locale}`);
|
|
34
34
|
const cachedTranslations = await this.cache.get(locale);
|
|
35
|
-
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash]);
|
|
35
|
+
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash] || locale !== this.config.sourceLocale && cachedTranslations[hash] === metadata[hash]?.sourceText);
|
|
36
36
|
this.logger.debug(`${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`);
|
|
37
37
|
const cachedCount = workingHashes.length - uncachedHashes.length;
|
|
38
38
|
if (uncachedHashes.length === 0) return {
|
|
@@ -107,7 +107,8 @@ var TranslationService = class {
|
|
|
107
107
|
total: workingHashes.length,
|
|
108
108
|
cached: cachedCount,
|
|
109
109
|
translated: Object.keys(newTranslations).length,
|
|
110
|
-
failed: errors.length
|
|
110
|
+
failed: errors.length,
|
|
111
|
+
untranslated: locale === this.config.sourceLocale ? 0 : Object.entries(newTranslations).filter(([hash, text]) => text === filteredMetadata[hash]?.sourceText).length
|
|
111
112
|
}
|
|
112
113
|
};
|
|
113
114
|
}
|
|
@@ -32,7 +32,7 @@ var TranslationService = class {
|
|
|
32
32
|
const workingHashes = requestedHashes || Object.keys(metadata);
|
|
33
33
|
this.logger.debug(`Translation requested for ${workingHashes.length} hashes in locale: ${locale}`);
|
|
34
34
|
const cachedTranslations = await this.cache.get(locale);
|
|
35
|
-
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash]);
|
|
35
|
+
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash] || locale !== this.config.sourceLocale && cachedTranslations[hash] === metadata[hash]?.sourceText);
|
|
36
36
|
this.logger.debug(`${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`);
|
|
37
37
|
const cachedCount = workingHashes.length - uncachedHashes.length;
|
|
38
38
|
if (uncachedHashes.length === 0) return {
|
|
@@ -107,7 +107,8 @@ var TranslationService = class {
|
|
|
107
107
|
total: workingHashes.length,
|
|
108
108
|
cached: cachedCount,
|
|
109
109
|
translated: Object.keys(newTranslations).length,
|
|
110
|
-
failed: errors.length
|
|
110
|
+
failed: errors.length,
|
|
111
|
+
untranslated: locale === this.config.sourceLocale ? 0 : Object.entries(newTranslations).filter(([hash, text]) => text === filteredMetadata[hash]?.sourceText).length
|
|
111
112
|
}
|
|
112
113
|
};
|
|
113
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n\n /** Seconds to wait for translations Weglot is still generating. */\n translationTimeout: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n apiBaseUrl: config.apiBaseUrl,\n translationTimeoutMs: config.translationTimeout * 1000,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"No translation returned yet; Weglot may still be generating it\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAqEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,QAAQ,YAAY,OAAO;AAChC,OAAK,aAAa,IAAI,iBACpB;GACE,QAAQ,OAAO;GACf,cAAc,OAAO;GACrB,YAAY,OAAO;GACnB,mBAAmB,OAAO;GAC1B,YAAY,OAAO;GACnB,sBAAsB,OAAO,qBAAqB;GACnD,EACD,KAAK,OACN;;;;;;;;;;CAWH,MAAM,UACJ,QACA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QACmC;EACnC,MAAMC,UAA6C,EAAE;AAErD,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,QAAQ,SAAS;AACvB,OAAI,MACF,SAAQ,QAAQ;IACd,MAAM,MAAM;IACZ,SAAS,MAAM,WAAW,EAAE;IAC7B;;AAIL,SAAO;;;;;CAOT,AAAQ,iBACN,iBACA,iBACwB;EACxB,MAAMC,SAAiC,EAAE;AAEzC,OAAK,MAAM,QAAQ,gBACjB,KAAI,gBAAgB,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
|
|
1
|
+
{"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n\n /** Seconds to wait for translations Weglot is still generating. */\n translationTimeout: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n /** New entries kept as their source text: refused by Weglot or identical. */\n untranslated?: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n apiBaseUrl: config.apiBaseUrl,\n translationTimeoutMs: config.translationTimeout * 1000,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation. A cached source text is asked\n // again, as it may stand for a word Weglot had not taken in yet.\n const uncachedHashes = workingHashes.filter(\n (hash) =>\n !cachedTranslations[hash] ||\n (locale !== this.config.sourceLocale &&\n cachedTranslations[hash] === metadata[hash]?.sourceText),\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"No translation returned yet; Weglot may still be generating it\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n untranslated:\n locale === this.config.sourceLocale\n ? 0\n : Object.entries(newTranslations).filter(\n ([hash, text]) => text === filteredMetadata[hash]?.sourceText,\n ).length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAuEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQ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AAY,KAAK;AACjC,OAAK,OAAO,MACV,6BAA6B,OAAO,IAAI,OAAO,KAAK,gBAAgB,CAAC,OAAO,QAAQ,YAAY,WAAW,OAAO,OAAO,cAAc,UAAU,WAAW,QAAQ,EAAE,CAAC,IACxK;AAED,SAAO;GACL,cAAc;GACd;GACA,OAAO;IACL,OAAO,cAAc;IACrB,QAAQ;IACR,YAAY,OAAO,KAAK,gBAAgB,CAAC;IACzC,QAAQ,OAAO;IACf,cACE,WAAW,KAAK,OAAO,eACnB,IACA,OAAO,QAAQ,gBAAgB,CAAC,QAC7B,CAAC,MAAM,UAAU,SAAS,iBAAiB,OAAO,WACpD,CAAC;IACT;GACF;;;;;CAMH,AAAQ,eACN,UACA,QACmC;EACnC,MAAMC,UAA6C,EAAE;AAErD,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,QAAQ,SAAS;AACvB,OAAI,MACF,SAAQ,QAAQ;IACd,MAAM,MAAM;IACZ,SAAS,MAAM,WAAW,EAAE;IAC7B;;AAIL,SAAO;;;;;CAOT,AAAQ,iBACN,iBACA,iBACwB;EACxB,MAAMC,SAAiC,EAAE;AAEzC,OAAK,MAAM,QAAQ,gBACjB,KAAI,gBAAgB,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
|
|
@@ -14,6 +14,7 @@ const REQUEST_URL = "https://compiler.weglot.com/";
|
|
|
14
14
|
const WORD_LABEL = "translate-react";
|
|
15
15
|
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
16
|
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
17
|
+
const REFUSED_AFTER_MISSES = 2;
|
|
17
18
|
/** The API validates the pair independently of the project's languages, so
|
|
18
19
|
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
19
20
|
var UnsupportedLanguagePairError = class extends Error {
|
|
@@ -24,6 +25,9 @@ var UnsupportedLanguagePairError = class extends Error {
|
|
|
24
25
|
this.name = "UnsupportedLanguagePairError";
|
|
25
26
|
}
|
|
26
27
|
};
|
|
28
|
+
/** A 400 the API gives a whole request when one of its words is unreadable. */
|
|
29
|
+
var RefusedRequestError = class extends Error {};
|
|
30
|
+
const wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
|
|
27
31
|
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
32
|
var WeglotApiClient = class {
|
|
29
33
|
apiBaseUrl;
|
|
@@ -31,10 +35,7 @@ var WeglotApiClient = class {
|
|
|
31
35
|
this.apiKey = apiKey;
|
|
32
36
|
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
33
37
|
}
|
|
34
|
-
/**
|
|
35
|
-
* One request. A word the API has queued comes back null; a word it will
|
|
36
|
-
* never translate comes back as its source text.
|
|
37
|
-
*/
|
|
38
|
+
/** One request. A word not translated yet comes back null, with an id once the API has queued it. */
|
|
38
39
|
async translate(params) {
|
|
39
40
|
const query = params.live ? "?live=1" : "";
|
|
40
41
|
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
@@ -50,7 +51,7 @@ var WeglotApiClient = class {
|
|
|
50
51
|
request_url: REQUEST_URL,
|
|
51
52
|
words: params.words.map((w, index) => ({
|
|
52
53
|
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
53
|
-
w,
|
|
54
|
+
w: wellFormed(w),
|
|
54
55
|
l: [WORD_LABEL]
|
|
55
56
|
}))
|
|
56
57
|
})
|
|
@@ -58,56 +59,83 @@ var WeglotApiClient = class {
|
|
|
58
59
|
if (!response.ok) {
|
|
59
60
|
const body = await response.text().catch(() => "");
|
|
60
61
|
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
62
|
+
if (response.status === 400) throw new RefusedRequestError(`Weglot translate API refused the request (400): ${body || "no response body"}`);
|
|
61
63
|
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
62
64
|
}
|
|
63
65
|
const data = await response.json();
|
|
64
66
|
const toWords = data.to_words;
|
|
65
67
|
if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
|
|
66
68
|
const ids = Array.isArray(data.ids) ? data.ids : null;
|
|
67
|
-
return
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
69
|
+
return {
|
|
70
|
+
words: toWords,
|
|
71
|
+
accepted: toWords.map((value, index) => value !== null || ids === null || (ids[index] ?? null) !== null)
|
|
72
|
+
};
|
|
71
73
|
}
|
|
72
|
-
/** Re-polls
|
|
73
|
-
*
|
|
74
|
-
* one error never discards what was already received. */
|
|
74
|
+
/** Re-polls words until translated or the deadline. A failed request leaves
|
|
75
|
+
* its words pending, so one error never discards what was already received. */
|
|
75
76
|
async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
|
|
76
|
-
const
|
|
77
|
+
const words = new Array(params.words.length).fill(null);
|
|
78
|
+
const everAccepted = new Array(params.words.length).fill(false);
|
|
79
|
+
const misses = new Array(params.words.length).fill(0);
|
|
80
|
+
const refused = /* @__PURE__ */ new Set();
|
|
77
81
|
let pending = params.words.map((_, index) => index);
|
|
78
82
|
let received = false;
|
|
83
|
+
let anyAccepted = false;
|
|
79
84
|
let lastError;
|
|
80
85
|
while (true) {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
}), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
91
|
-
received = true;
|
|
92
|
-
chunk.forEach((index, k) => {
|
|
93
|
-
if (translated[k] === null) stillPending.push(index);
|
|
94
|
-
else results[index] = translated[k];
|
|
95
|
-
});
|
|
96
|
-
} catch (error) {
|
|
97
|
-
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
-
lastError = error;
|
|
99
|
-
stillPending.push(...chunk);
|
|
86
|
+
for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) try {
|
|
87
|
+
const answers = await this.sendIsolatingRefused(params, pending.slice(i, i + MAX_WORDS_PER_REQUEST), refused);
|
|
88
|
+
received = true;
|
|
89
|
+
for (const { index, word, accepted } of answers) {
|
|
90
|
+
words[index] = word;
|
|
91
|
+
if (accepted) {
|
|
92
|
+
everAccepted[index] = true;
|
|
93
|
+
anyAccepted = true;
|
|
94
|
+
} else misses[index]++;
|
|
100
95
|
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
+
lastError = error;
|
|
99
|
+
}
|
|
100
|
+
if (anyAccepted) {
|
|
101
|
+
for (const index of pending) if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);
|
|
101
102
|
}
|
|
102
|
-
pending =
|
|
103
|
+
pending = pending.filter((index) => words[index] === null && !refused.has(index));
|
|
103
104
|
const remaining = deadline - Date.now();
|
|
104
105
|
if (pending.length === 0 || remaining <= 0) {
|
|
105
106
|
if (!received && lastError !== void 0) throw lastError;
|
|
106
|
-
return
|
|
107
|
+
return {
|
|
108
|
+
words,
|
|
109
|
+
refused: [...refused].sort((a, b) => a - b)
|
|
110
|
+
};
|
|
107
111
|
}
|
|
108
112
|
await sleep(Math.min(pollIntervalMs, remaining));
|
|
109
113
|
}
|
|
110
114
|
}
|
|
115
|
+
/** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */
|
|
116
|
+
async sendIsolatingRefused(params, indexes, refused) {
|
|
117
|
+
try {
|
|
118
|
+
const { words, accepted } = await require_timeout.withTimeout(this.translate({
|
|
119
|
+
from: params.from,
|
|
120
|
+
to: params.to,
|
|
121
|
+
words: indexes.map((index) => params.words[index]),
|
|
122
|
+
types: params.types && indexes.map((index) => params.types[index])
|
|
123
|
+
}), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
124
|
+
return indexes.map((index, k) => ({
|
|
125
|
+
index,
|
|
126
|
+
word: words[k],
|
|
127
|
+
accepted: accepted[k]
|
|
128
|
+
}));
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (!(error instanceof RefusedRequestError)) throw error;
|
|
131
|
+
if (indexes.length === 1) {
|
|
132
|
+
refused.add(indexes[0]);
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
const middle = Math.ceil(indexes.length / 2);
|
|
136
|
+
return [...await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused), ...await this.sendIsolatingRefused(params, indexes.slice(middle), refused)];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
111
139
|
async fetchSettings() {
|
|
112
140
|
const response = await require_timeout.withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
113
141
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
@@ -14,6 +14,7 @@ const REQUEST_URL = "https://compiler.weglot.com/";
|
|
|
14
14
|
const WORD_LABEL = "translate-react";
|
|
15
15
|
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
16
|
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
17
|
+
const REFUSED_AFTER_MISSES = 2;
|
|
17
18
|
/** The API validates the pair independently of the project's languages, so
|
|
18
19
|
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
19
20
|
var UnsupportedLanguagePairError = class extends Error {
|
|
@@ -24,6 +25,9 @@ var UnsupportedLanguagePairError = class extends Error {
|
|
|
24
25
|
this.name = "UnsupportedLanguagePairError";
|
|
25
26
|
}
|
|
26
27
|
};
|
|
28
|
+
/** A 400 the API gives a whole request when one of its words is unreadable. */
|
|
29
|
+
var RefusedRequestError = class extends Error {};
|
|
30
|
+
const wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
|
|
27
31
|
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
32
|
var WeglotApiClient = class {
|
|
29
33
|
apiBaseUrl;
|
|
@@ -31,10 +35,7 @@ var WeglotApiClient = class {
|
|
|
31
35
|
this.apiKey = apiKey;
|
|
32
36
|
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
33
37
|
}
|
|
34
|
-
/**
|
|
35
|
-
* One request. A word the API has queued comes back null; a word it will
|
|
36
|
-
* never translate comes back as its source text.
|
|
37
|
-
*/
|
|
38
|
+
/** One request. A word not translated yet comes back null, with an id once the API has queued it. */
|
|
38
39
|
async translate(params) {
|
|
39
40
|
const query = params.live ? "?live=1" : "";
|
|
40
41
|
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
@@ -50,7 +51,7 @@ var WeglotApiClient = class {
|
|
|
50
51
|
request_url: REQUEST_URL,
|
|
51
52
|
words: params.words.map((w, index) => ({
|
|
52
53
|
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
53
|
-
w,
|
|
54
|
+
w: wellFormed(w),
|
|
54
55
|
l: [WORD_LABEL]
|
|
55
56
|
}))
|
|
56
57
|
})
|
|
@@ -58,56 +59,83 @@ var WeglotApiClient = class {
|
|
|
58
59
|
if (!response.ok) {
|
|
59
60
|
const body = await response.text().catch(() => "");
|
|
60
61
|
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
62
|
+
if (response.status === 400) throw new RefusedRequestError(`Weglot translate API refused the request (400): ${body || "no response body"}`);
|
|
61
63
|
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
62
64
|
}
|
|
63
65
|
const data = await response.json();
|
|
64
66
|
const toWords = data.to_words;
|
|
65
67
|
if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
|
|
66
68
|
const ids = Array.isArray(data.ids) ? data.ids : null;
|
|
67
|
-
return
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
69
|
+
return {
|
|
70
|
+
words: toWords,
|
|
71
|
+
accepted: toWords.map((value, index) => value !== null || ids === null || (ids[index] ?? null) !== null)
|
|
72
|
+
};
|
|
71
73
|
}
|
|
72
|
-
/** Re-polls
|
|
73
|
-
*
|
|
74
|
-
* one error never discards what was already received. */
|
|
74
|
+
/** Re-polls words until translated or the deadline. A failed request leaves
|
|
75
|
+
* its words pending, so one error never discards what was already received. */
|
|
75
76
|
async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
|
|
76
|
-
const
|
|
77
|
+
const words = new Array(params.words.length).fill(null);
|
|
78
|
+
const everAccepted = new Array(params.words.length).fill(false);
|
|
79
|
+
const misses = new Array(params.words.length).fill(0);
|
|
80
|
+
const refused = /* @__PURE__ */ new Set();
|
|
77
81
|
let pending = params.words.map((_, index) => index);
|
|
78
82
|
let received = false;
|
|
83
|
+
let anyAccepted = false;
|
|
79
84
|
let lastError;
|
|
80
85
|
while (true) {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
}), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
91
|
-
received = true;
|
|
92
|
-
chunk.forEach((index, k) => {
|
|
93
|
-
if (translated[k] === null) stillPending.push(index);
|
|
94
|
-
else results[index] = translated[k];
|
|
95
|
-
});
|
|
96
|
-
} catch (error) {
|
|
97
|
-
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
-
lastError = error;
|
|
99
|
-
stillPending.push(...chunk);
|
|
86
|
+
for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) try {
|
|
87
|
+
const answers = await this.sendIsolatingRefused(params, pending.slice(i, i + MAX_WORDS_PER_REQUEST), refused);
|
|
88
|
+
received = true;
|
|
89
|
+
for (const { index, word, accepted } of answers) {
|
|
90
|
+
words[index] = word;
|
|
91
|
+
if (accepted) {
|
|
92
|
+
everAccepted[index] = true;
|
|
93
|
+
anyAccepted = true;
|
|
94
|
+
} else misses[index]++;
|
|
100
95
|
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
+
lastError = error;
|
|
99
|
+
}
|
|
100
|
+
if (anyAccepted) {
|
|
101
|
+
for (const index of pending) if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);
|
|
101
102
|
}
|
|
102
|
-
pending =
|
|
103
|
+
pending = pending.filter((index) => words[index] === null && !refused.has(index));
|
|
103
104
|
const remaining = deadline - Date.now();
|
|
104
105
|
if (pending.length === 0 || remaining <= 0) {
|
|
105
106
|
if (!received && lastError !== void 0) throw lastError;
|
|
106
|
-
return
|
|
107
|
+
return {
|
|
108
|
+
words,
|
|
109
|
+
refused: [...refused].sort((a, b) => a - b)
|
|
110
|
+
};
|
|
107
111
|
}
|
|
108
112
|
await sleep(Math.min(pollIntervalMs, remaining));
|
|
109
113
|
}
|
|
110
114
|
}
|
|
115
|
+
/** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */
|
|
116
|
+
async sendIsolatingRefused(params, indexes, refused) {
|
|
117
|
+
try {
|
|
118
|
+
const { words, accepted } = await withTimeout(this.translate({
|
|
119
|
+
from: params.from,
|
|
120
|
+
to: params.to,
|
|
121
|
+
words: indexes.map((index) => params.words[index]),
|
|
122
|
+
types: params.types && indexes.map((index) => params.types[index])
|
|
123
|
+
}), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
124
|
+
return indexes.map((index, k) => ({
|
|
125
|
+
index,
|
|
126
|
+
word: words[k],
|
|
127
|
+
accepted: accepted[k]
|
|
128
|
+
}));
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (!(error instanceof RefusedRequestError)) throw error;
|
|
131
|
+
if (indexes.length === 1) {
|
|
132
|
+
refused.add(indexes[0]);
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
const middle = Math.ceil(indexes.length / 2);
|
|
136
|
+
return [...await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused), ...await this.sendIsolatingRefused(params, indexes.slice(middle), refused)];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
111
139
|
async fetchSettings() {
|
|
112
140
|
const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
113
141
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","results: (string | null)[]","lastError: unknown","stillPending: number[]"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n};\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /**\n * One request. A word the API has queued comes back null; a word it will\n * never translate comes back as its source text.\n */\n async translate(params: TranslateParams): Promise<(string | null)[]> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n w,\n l: [WORD_LABEL],\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return toWords.map((value, index) => {\n if (value !== null) return value;\n // Null without an id was not queued: it will never be translated.\n const queued = ids === null || (ids[index] ?? null) !== null;\n return queued ? null : params.words[index];\n });\n }\n\n /** Re-polls queued words until ready or the deadline, then returns null for\n * the rest. A failed request leaves its words queued for the next round, so\n * one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<(string | null)[]> {\n const results: (string | null)[] = new Array(params.words.length).fill(null);\n let pending = params.words.map((_, index) => index);\n let received = false;\n let lastError: unknown;\n\n while (true) {\n const stillPending: number[] = [];\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);\n try {\n const translated = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: chunk.map((index) => params.words[index]),\n types: params.types && chunk.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n received = true;\n chunk.forEach((index, k) => {\n if (translated[k] === null) stillPending.push(index);\n else results[index] = translated[k];\n });\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n stillPending.push(...chunk);\n }\n }\n pending = stillPending;\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return results;\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\" },\n }),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n product?: string;\n api_base_url?: string;\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (data.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\n }\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n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kBAAa,KAAK,GAAG,MAAM;;;AAG/B,aAAU;GAEV,MAAM,YAAY,WAAW,KAAK,KAAK;AACvC,OAAI,QAAQ,WAAW,KAAK,aAAa,GAAG;AAE1C,QAAI,CAAC,YAAY,cAAc,OAAW,OAAM;AAChD,WAAO;;AAET,SAAM,MAAM,KAAK,IAAI,gBAAgB,UAAU,CAAC;;;CAIpD,MAAM,gBAAgD;EACpD,MAAM,WAAW,MAAM,YAErB,MAAM,GAAG,QAAQ,IAAI,uBAAuB,qBAAqB,WAAW,mBAAmB,KAAK,OAAO,IAAI,EAC7G,SAAS,EAAE,QAAQ,oBAAoB,EACxC,CAAC,EACF,iBAAiB,QACjB,gCACD;AAED,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,4CAA4C,SAAS,OAAO,iDAC7D;EAGH,MAAM,OAAQ,MAAM,SAAS,MAAM;AAYnC,MAAI,KAAK,YAAY,kBACnB,OAAM,IAAI,MACR,mIACD;AAGH,MAAI,CAAC,KAAK,iBAAiB,CAAC,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,aAAa,KAAK,gBAAgB,sBAAsB,QAAQ,QAAQ,GAAG;GAC3E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
|
|
1
|
+
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","words: (string | null)[]","everAccepted: boolean[]","misses: number[]","lastError: unknown"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n// The API sometimes takes new words only on a second request; one still without an id after this many is refused.\nconst REFUSED_AFTER_MISSES = 2;\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type TranslateResponse = {\n /** Null while not translated yet. */\n words: (string | null)[];\n /** Whether the API took each word in: it was translated or given an id. */\n accepted: boolean[];\n};\n\nexport type PolledTranslation = {\n /** Null for words still queued at the deadline or refused. */\n words: (string | null)[];\n /** Indexes of the words the API will not translate. */\n refused: number[];\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n};\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\n/** A 400 the API gives a whole request when one of its words is unreadable. */\nclass RefusedRequestError extends Error {}\n\nconst wellFormed = (text: string) =>\n text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\\uFFFD\");\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /** One request. A word not translated yet comes back null, with an id once the API has queued it. */\n async translate(params: TranslateParams): Promise<TranslateResponse> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n // A lone surrogate makes the API refuse the whole request.\n w: wellFormed(w),\n l: [WORD_LABEL],\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n if (response.status === 400) {\n throw new RefusedRequestError(\n `Weglot translate API refused the request (400): ${body || \"no response body\"}`,\n );\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return {\n words: toWords,\n accepted: toWords.map(\n (value, index) => value !== null || ids === null || (ids[index] ?? null) !== null,\n ),\n };\n }\n\n /** Re-polls words until translated or the deadline. A failed request leaves\n * its words pending, so one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<PolledTranslation> {\n const words: (string | null)[] = new Array(params.words.length).fill(null);\n const everAccepted: boolean[] = new Array(params.words.length).fill(false);\n const misses: number[] = new Array(params.words.length).fill(0);\n const refused = new Set<number>();\n let pending = params.words.map((_, index) => index);\n let received = false;\n let anyAccepted = false;\n let lastError: unknown;\n\n while (true) {\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n try {\n const answers = await this.sendIsolatingRefused(\n params,\n pending.slice(i, i + MAX_WORDS_PER_REQUEST),\n refused,\n );\n received = true;\n for (const { index, word, accepted } of answers) {\n words[index] = word;\n if (accepted) {\n everAccepted[index] = true;\n anyAccepted = true;\n } else {\n misses[index]++;\n }\n }\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n }\n }\n\n // Only while the API takes other words in: otherwise it is not ready, and the words stay pending.\n if (anyAccepted) {\n for (const index of pending) {\n if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);\n }\n }\n pending = pending.filter((index) => words[index] === null && !refused.has(index));\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return { words, refused: [...refused].sort((a, b) => a - b) };\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */\n private async sendIsolatingRefused(\n params: TranslateParams,\n indexes: number[],\n refused: Set<number>,\n ): Promise<{ index: number; word: string | null; accepted: boolean }[]> {\n try {\n const { words, accepted } = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: indexes.map((index) => params.words[index]),\n types: params.types && indexes.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n return indexes.map((index, k) => ({ index, word: words[k], accepted: accepted[k] }));\n } catch (error) {\n if (!(error instanceof RefusedRequestError)) throw error;\n if (indexes.length === 1) {\n refused.add(indexes[0]);\n return [];\n }\n const middle = Math.ceil(indexes.length / 2);\n return [\n ...(await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused)),\n ...(await this.sendIsolatingRefused(params, indexes.slice(middle), refused)),\n ];\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\" },\n }),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n product?: string;\n api_base_url?: string;\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (data.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\n }\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,uBAAuB;AAC7B,MAAa,uBAAuB;AACpC,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAEpB,MAAM,aAAa;AACnB,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;AAExC,MAAM,uBAAuB;;;AA+C7B,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;;AAKhB,IAAM,sBAAN,cAAkC,MAAM;AAExC,MAAM,cAAc,SAClB,KAAK,QAAQ,2EAA2E,IAAS;AAEnG,MAAM,gBAAgB,OACpB,IAAI,SAAe,YAAY,WAAW,SAAS,GAAG,CAAC;AAEzD,IAAa,kBAAb,MAA6B;CAC3B,AAAiB;CAEjB,YACE,AAAiBC,QACjB,YACA;EAFiB;AAGjB,OAAK,aAAa,cAAc;;;CAIlC,MAAM,UAAU,QAAqD;EACnE,MAAM,QAAQ,OAAO,OAAO,YAAY;EACxC,MAAM,WAAW,MAAM,MAAM,GAAG,KAAK,WAAW,YAAY,SAAS;GACnE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,OAAO,KAAK;IAC5B;GACD,MAAM,KAAK,UAAU;IACnB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,aAAa;IACb,OAAO,OAAO,MAAM,KAAK,GAAG,WAAW;KACrC,GAAG,OAAO,QAAQ,UAAU;KAE5B,GAAG,WAAW,EAAE;KAChB,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
+
/** Texts settled as their source this process, per locale, so they are not polled again. */
|
|
10
|
+
settledAsSource = /* @__PURE__ */ new Map();
|
|
9
11
|
constructor(config, logger, client, pollOptions = {}) {
|
|
10
12
|
this.config = config;
|
|
11
13
|
this.logger = logger;
|
|
@@ -18,8 +20,14 @@ var WeglotTranslator = class {
|
|
|
18
20
|
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
19
21
|
const translations = {};
|
|
20
22
|
const protectedEntries = [];
|
|
23
|
+
const settled = this.settledAsSource.get(locale) ?? /* @__PURE__ */ new Set();
|
|
24
|
+
this.settledAsSource.set(locale, settled);
|
|
21
25
|
for (const hash of hashes) {
|
|
22
26
|
const sourceText = entriesMap[hash].text;
|
|
27
|
+
if (settled.has(sourceText)) {
|
|
28
|
+
translations[hash] = sourceText;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
23
31
|
const { wire, restore, encodable } = require_wire_format.encodeForApi(sourceText, this.engine);
|
|
24
32
|
if (!encodable) {
|
|
25
33
|
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
@@ -33,7 +41,7 @@ var WeglotTranslator = class {
|
|
|
33
41
|
});
|
|
34
42
|
}
|
|
35
43
|
if (protectedEntries.length === 0) return translations;
|
|
36
|
-
const translated = await this.client.translateUntilReady({
|
|
44
|
+
const { words: translated, refused } = await this.client.translateUntilReady({
|
|
37
45
|
from: this.config.sourceLocale,
|
|
38
46
|
to: this.config.apiLocales?.[locale] ?? locale,
|
|
39
47
|
words: protectedEntries.map((entry) => entry.text)
|
|
@@ -41,10 +49,15 @@ var WeglotTranslator = class {
|
|
|
41
49
|
...this.pollOptions,
|
|
42
50
|
deadline: Date.now() + this.config.translationTimeoutMs
|
|
43
51
|
});
|
|
52
|
+
const refusedIndexes = new Set(refused);
|
|
44
53
|
let queued = 0;
|
|
45
54
|
protectedEntries.forEach((entry, index) => {
|
|
46
55
|
const result = translated[index];
|
|
47
56
|
const sourceText = entriesMap[entry.hash].text;
|
|
57
|
+
if (refusedIndexes.has(index)) {
|
|
58
|
+
translations[entry.hash] = sourceText;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
48
61
|
if (result === null) {
|
|
49
62
|
queued++;
|
|
50
63
|
return;
|
|
@@ -58,6 +71,11 @@ var WeglotTranslator = class {
|
|
|
58
71
|
translations[entry.hash] = sourceText;
|
|
59
72
|
} else translations[entry.hash] = restored;
|
|
60
73
|
});
|
|
74
|
+
for (const [hash, text] of Object.entries(translations)) if (text === entriesMap[hash].text) settled.add(text);
|
|
75
|
+
if (refused.length > 0) {
|
|
76
|
+
const examples = refused.slice(0, 5).map((index) => `"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}"`).join(", ");
|
|
77
|
+
this.logger.warn(`Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? ", ..." : ""}`);
|
|
78
|
+
}
|
|
61
79
|
if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
|
|
62
80
|
return translations;
|
|
63
81
|
}
|
|
@@ -6,6 +6,8 @@ import { encodeForApi } from "./wire-format.mjs";
|
|
|
6
6
|
var WeglotTranslator = class {
|
|
7
7
|
client;
|
|
8
8
|
engine;
|
|
9
|
+
/** Texts settled as their source this process, per locale, so they are not polled again. */
|
|
10
|
+
settledAsSource = /* @__PURE__ */ new Map();
|
|
9
11
|
constructor(config, logger, client, pollOptions = {}) {
|
|
10
12
|
this.config = config;
|
|
11
13
|
this.logger = logger;
|
|
@@ -18,8 +20,14 @@ var WeglotTranslator = class {
|
|
|
18
20
|
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
19
21
|
const translations = {};
|
|
20
22
|
const protectedEntries = [];
|
|
23
|
+
const settled = this.settledAsSource.get(locale) ?? /* @__PURE__ */ new Set();
|
|
24
|
+
this.settledAsSource.set(locale, settled);
|
|
21
25
|
for (const hash of hashes) {
|
|
22
26
|
const sourceText = entriesMap[hash].text;
|
|
27
|
+
if (settled.has(sourceText)) {
|
|
28
|
+
translations[hash] = sourceText;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
23
31
|
const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);
|
|
24
32
|
if (!encodable) {
|
|
25
33
|
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
@@ -33,7 +41,7 @@ var WeglotTranslator = class {
|
|
|
33
41
|
});
|
|
34
42
|
}
|
|
35
43
|
if (protectedEntries.length === 0) return translations;
|
|
36
|
-
const translated = await this.client.translateUntilReady({
|
|
44
|
+
const { words: translated, refused } = await this.client.translateUntilReady({
|
|
37
45
|
from: this.config.sourceLocale,
|
|
38
46
|
to: this.config.apiLocales?.[locale] ?? locale,
|
|
39
47
|
words: protectedEntries.map((entry) => entry.text)
|
|
@@ -41,10 +49,15 @@ var WeglotTranslator = class {
|
|
|
41
49
|
...this.pollOptions,
|
|
42
50
|
deadline: Date.now() + this.config.translationTimeoutMs
|
|
43
51
|
});
|
|
52
|
+
const refusedIndexes = new Set(refused);
|
|
44
53
|
let queued = 0;
|
|
45
54
|
protectedEntries.forEach((entry, index) => {
|
|
46
55
|
const result = translated[index];
|
|
47
56
|
const sourceText = entriesMap[entry.hash].text;
|
|
57
|
+
if (refusedIndexes.has(index)) {
|
|
58
|
+
translations[entry.hash] = sourceText;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
48
61
|
if (result === null) {
|
|
49
62
|
queued++;
|
|
50
63
|
return;
|
|
@@ -58,6 +71,11 @@ var WeglotTranslator = class {
|
|
|
58
71
|
translations[entry.hash] = sourceText;
|
|
59
72
|
} else translations[entry.hash] = restored;
|
|
60
73
|
});
|
|
74
|
+
for (const [hash, text] of Object.entries(translations)) if (text === entriesMap[hash].text) settled.add(text);
|
|
75
|
+
if (refused.length > 0) {
|
|
76
|
+
const examples = refused.slice(0, 5).map((index) => `"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}"`).join(", ");
|
|
77
|
+
this.logger.warn(`Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? ", ..." : ""}`);
|
|
78
|
+
}
|
|
61
79
|
if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
|
|
62
80
|
return translations;
|
|
63
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","pollOptions: Omit<PollOptions, \"deadline\">","translations: Record<string, string>","protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[]"],"sources":["../../../src/translators/weglot/translator.ts"],"sourcesContent":["import type { LocaleCode } from \"../../locale\";\nimport type { TranslatableEntry, Translator } from \"../api\";\nimport type { Logger } from \"../../utils/logger\";\nimport { type PollOptions, WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\n\nexport interface WeglotTranslatorConfig {\n apiKey: string;\n sourceLocale: LocaleCode;\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n /** How long to wait for queued translations before leaving them out. */\n translationTimeoutMs: number;\n}\n\nexport class WeglotTranslator implements Translator<WeglotTranslatorConfig> {\n private readonly client: WeglotApiClient;\n private readonly engine: number;\n\n constructor(\n readonly config: WeglotTranslatorConfig,\n private readonly logger: Logger,\n client?: WeglotApiClient,\n private readonly pollOptions: Omit<PollOptions, \"deadline\"> = {},\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);\n this.engine = resolveTranslationEngine(config.translationEngine);\n }\n\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n const hashes = Object.keys(entriesMap);\n this.logger.debug(\n `Weglot translate() called for ${locale} with ${hashes.length} entries`,\n );\n\n const translations: Record<string, string> = {};\n const protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[] = [];\n\n for (const hash of hashes) {\n const sourceText = entriesMap[hash].text;\n const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);\n if (!encodable) {\n // Engine 1 merges nothing, so markup cannot survive the wire form.\n this.logger.warn(\n `Weglot translation engine ${this.engine} cannot carry the markup in hash \"${hash}\"; falling back to source text.`,\n );\n translations[hash] = sourceText;\n continue;\n }\n protectedEntries.push({ hash, text: wire, restore });\n }\n\n if (protectedEntries.length === 0) return translations;\n\n const translated = await this.client.translateUntilReady(\n {\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: protectedEntries.map((entry) => entry.text),\n },\n {\n ...this.pollOptions,\n deadline: Date.now() + this.config.translationTimeoutMs,\n },\n );\n\n let queued = 0;\n protectedEntries.forEach((entry, index) => {\n const result = translated[index];\n const sourceText = entriesMap[entry.hash].text;\n\n if (result === null) {\n // Left out rather than filled with source, which would be cached.\n queued++;\n return;\n }\n\n const { text: restored, damaged } = entry.restore(result);\n if (damaged) {\n this.logger.warn(\n `Weglot translation for hash \"${entry.hash}\" (locale \"${locale}\") lost an interpolation or element during restore; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else if (result === entry.text && entry.text !== sourceText) {\n // The API echoes a segment back verbatim when it rejects its markup.\n this.logger.warn(\n `Weglot API returned hash \"${entry.hash}\" (locale \"${locale}\") untranslated; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else {\n translations[entry.hash] = restored;\n }\n });\n\n if (queued > 0) {\n this.logger.warn(\n `${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1000)}s. Translations already received are cached, so running again picks up the rest.`,\n );\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB
|
|
1
|
+
{"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","pollOptions: Omit<PollOptions, \"deadline\">","translations: Record<string, string>","protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[]"],"sources":["../../../src/translators/weglot/translator.ts"],"sourcesContent":["import type { LocaleCode } from \"../../locale\";\nimport type { TranslatableEntry, Translator } from \"../api\";\nimport type { Logger } from \"../../utils/logger\";\nimport { type PollOptions, WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\n\nexport interface WeglotTranslatorConfig {\n apiKey: string;\n sourceLocale: LocaleCode;\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n /** How long to wait for queued translations before leaving them out. */\n translationTimeoutMs: number;\n}\n\nexport class WeglotTranslator implements Translator<WeglotTranslatorConfig> {\n private readonly client: WeglotApiClient;\n private readonly engine: number;\n /** Texts settled as their source this process, per locale, so they are not polled again. */\n private readonly settledAsSource = new Map<LocaleCode, Set<string>>();\n\n constructor(\n readonly config: WeglotTranslatorConfig,\n private readonly logger: Logger,\n client?: WeglotApiClient,\n private readonly pollOptions: Omit<PollOptions, \"deadline\"> = {},\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);\n this.engine = resolveTranslationEngine(config.translationEngine);\n }\n\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n const hashes = Object.keys(entriesMap);\n this.logger.debug(\n `Weglot translate() called for ${locale} with ${hashes.length} entries`,\n );\n\n const translations: Record<string, string> = {};\n const protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[] = [];\n\n const settled = this.settledAsSource.get(locale) ?? new Set<string>();\n this.settledAsSource.set(locale, settled);\n\n for (const hash of hashes) {\n const sourceText = entriesMap[hash].text;\n if (settled.has(sourceText)) {\n translations[hash] = sourceText;\n continue;\n }\n const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);\n if (!encodable) {\n // Engine 1 merges nothing, so markup cannot survive the wire form.\n this.logger.warn(\n `Weglot translation engine ${this.engine} cannot carry the markup in hash \"${hash}\"; falling back to source text.`,\n );\n translations[hash] = sourceText;\n continue;\n }\n protectedEntries.push({ hash, text: wire, restore });\n }\n\n if (protectedEntries.length === 0) return translations;\n\n const { words: translated, refused } = await this.client.translateUntilReady(\n {\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: protectedEntries.map((entry) => entry.text),\n },\n {\n ...this.pollOptions,\n deadline: Date.now() + this.config.translationTimeoutMs,\n },\n );\n\n const refusedIndexes = new Set(refused);\n let queued = 0;\n protectedEntries.forEach((entry, index) => {\n const result = translated[index];\n const sourceText = entriesMap[entry.hash].text;\n\n if (refusedIndexes.has(index)) {\n translations[entry.hash] = sourceText;\n return;\n }\n if (result === null) {\n // Left out rather than filled with source, which would be cached.\n queued++;\n return;\n }\n\n const { text: restored, damaged } = entry.restore(result);\n if (damaged) {\n this.logger.warn(\n `Weglot translation for hash \"${entry.hash}\" (locale \"${locale}\") lost an interpolation or element during restore; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else if (result === entry.text && entry.text !== sourceText) {\n // The API echoes a segment back verbatim when it rejects its markup.\n this.logger.warn(\n `Weglot API returned hash \"${entry.hash}\" (locale \"${locale}\") untranslated; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else {\n translations[entry.hash] = restored;\n }\n });\n\n for (const [hash, text] of Object.entries(translations)) {\n if (text === entriesMap[hash].text) settled.add(text);\n }\n\n if (refused.length > 0) {\n const examples = refused\n .slice(0, 5)\n .map((index) => `\"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}\"`)\n .join(\", \");\n this.logger.warn(\n `Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? \", ...\" : \"\"}`,\n );\n }\n\n if (queued > 0) {\n this.logger.warn(\n `${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1000)}s. Translations already received are cached, so running again picks up the rest.`,\n );\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB;;CAEjB,AAAiB,kCAAkB,IAAI,KAA8B;CAErE,YACE,AAASA,QACT,AAAiBC,QACjB,QACA,AAAiBC,cAA6C,EAAE,EAChE;EAJS;EACQ;EAEA;AAEjB,OAAK,SAAS,UAAU,IAAI,gBAAgB,OAAO,QAAQ,OAAO,WAAW;AAC7E,OAAK,SAAS,yBAAyB,OAAO,kBAAkB;;CAGlE,MAAM,UACJ,QACA,YACiC;EACjC,MAAM,SAAS,OAAO,KAAK,WAAW;AACtC,OAAK,OAAO,MACV,iCAAiC,OAAO,QAAQ,OAAO,OAAO,UAC/D;EAED,MAAMC,eAAuC,EAAE;EAC/C,MAAMC,mBAIA,EAAE;EAER,MAAM,UAAU,KAAK,gBAAgB,IAAI,OAAO,oBAAI,IAAI,KAAa;AACrE,OAAK,gBAAgB,IAAI,QAAQ,QAAQ;AAEzC,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,aAAa,WAAW,MAAM;AACpC,OAAI,QAAQ,IAAI,WAAW,EAAE;AAC3B,iBAAa,QAAQ;AACrB;;GAEF,MAAM,EAAE,MAAM,SAAS,cAAc,aAAa,YAAY,KAAK,OAAO;AAC1E,OAAI,CAAC,WAAW;AAEd,SAAK,OAAO,KACV,6BAA6B,KAAK,OAAO,oCAAoC,KAAK,iCACnF;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