@lingo.dev/compiler 0.3.7 → 0.3.8

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.
@@ -1,12 +1,12 @@
1
1
  import { LingoProviderProps } from "../shared/LingoProvider.mjs";
2
- import * as react_jsx_runtime1 from "react/jsx-runtime";
2
+ import * as react_jsx_runtime2 from "react/jsx-runtime";
3
3
 
4
4
  //#region src/react/server/ServerLingoProvider.d.ts
5
5
  declare function LingoProvider({
6
6
  initialLocale,
7
7
  initialTranslations,
8
8
  ...rest
9
- }: LingoProviderProps): Promise<react_jsx_runtime1.JSX.Element>;
9
+ }: LingoProviderProps): Promise<react_jsx_runtime2.JSX.Element>;
10
10
  //#endregion
11
11
  export { LingoProvider };
12
12
  //# sourceMappingURL=ServerLingoProvider.d.mts.map
@@ -1,5 +1,5 @@
1
1
  import { PropsWithChildren } from "react";
2
- import * as react_jsx_runtime3 from "react/jsx-runtime";
2
+ import * as react_jsx_runtime1 from "react/jsx-runtime";
3
3
  import { LocaleCode } from "lingo.dev/spec";
4
4
 
5
5
  //#region src/react/shared/LingoProvider.d.ts
@@ -70,7 +70,7 @@ declare function LingoProvider__Dev({
70
70
  router,
71
71
  devWidget,
72
72
  children
73
- }: LingoProviderProps): react_jsx_runtime3.JSX.Element;
73
+ }: LingoProviderProps): react_jsx_runtime1.JSX.Element;
74
74
  //#endregion
75
75
  export { LingoProvider, LingoProviderProps };
76
76
  //# sourceMappingURL=LingoProvider.d.mts.map
@@ -1,5 +1,5 @@
1
1
  import { CSSProperties } from "react";
2
- import * as react_jsx_runtime2 from "react/jsx-runtime";
2
+ import * as react_jsx_runtime3 from "react/jsx-runtime";
3
3
  import { LocaleCode } from "lingo.dev/spec";
4
4
 
5
5
  //#region src/react/shared/LocaleSwitcher.d.ts
@@ -65,7 +65,7 @@ declare function LocaleSwitcher({
65
65
  style,
66
66
  className,
67
67
  showLoadingState
68
- }: LocaleSwitcherProps): react_jsx_runtime2.JSX.Element;
68
+ }: LocaleSwitcherProps): react_jsx_runtime3.JSX.Element;
69
69
  //#endregion
70
70
  export { LocaleSwitcher };
71
71
  //# sourceMappingURL=LocaleSwitcher.d.mts.map
@@ -241,6 +241,18 @@ var TranslationServer = class {
241
241
  hashes: allHashes
242
242
  }));
243
243
  const result = await this.translationService.translate(locale, this.metadata, allHashes);
244
+ if (result.errors.length > 0) {
245
+ this.logger.error(`${result.errors.length} translation error(s) for ${locale}:`);
246
+ for (const err of result.errors) {
247
+ const prefix = ` [${locale}]`;
248
+ if (err.hash === "all") {
249
+ this.logger.error(`${prefix} ${err.error}`);
250
+ continue;
251
+ }
252
+ const source = err.sourceText.length > 200 ? err.sourceText.slice(0, 200) + "..." : err.sourceText;
253
+ this.logger.error(`${prefix} hash=${err.hash} source="${source}" error="${err.error}"`);
254
+ }
255
+ }
244
256
  const duration = Date.now() - startTime;
245
257
  this.broadcast(require_ws_events.createEvent("batch:complete", {
246
258
  locale,
@@ -238,6 +238,18 @@ var TranslationServer = class {
238
238
  hashes: allHashes
239
239
  }));
240
240
  const result = await this.translationService.translate(locale, this.metadata, allHashes);
241
+ if (result.errors.length > 0) {
242
+ this.logger.error(`${result.errors.length} translation error(s) for ${locale}:`);
243
+ for (const err of result.errors) {
244
+ const prefix = ` [${locale}]`;
245
+ if (err.hash === "all") {
246
+ this.logger.error(`${prefix} ${err.error}`);
247
+ continue;
248
+ }
249
+ const source = err.sourceText.length > 200 ? err.sourceText.slice(0, 200) + "..." : err.sourceText;
250
+ this.logger.error(`${prefix} hash=${err.hash} source="${source}" error="${err.error}"`);
251
+ }
252
+ }
241
253
  const duration = Date.now() - startTime;
242
254
  this.broadcast(createEvent("batch:complete", {
243
255
  locale,
@@ -1 +1 @@
1
- {"version":3,"file":"translation-server.mjs","names":["out: Record<string, any>"],"sources":["../../src/translation-server/translation-server.ts"],"sourcesContent":["/**\n * Simple HTTP server for serving translations during development\n *\n * This server:\n * - Finds a free port automatically\n * - Serves translations via:\n * - GET /translations/:locale - Full dictionary (cached)\n * - POST /translations/:locale (body: { hashes: string[] }) - Batch translation\n * - Uses the same translation logic as middleware\n * - Can be started/stopped programmatically\n */\n\nimport http from \"http\";\nimport crypto from \"crypto\";\nimport type { Socket } from \"net\";\nimport { URL } from \"url\";\nimport { WebSocket, WebSocketServer } from \"ws\";\nimport type { MetadataSchema, TranslationMiddlewareConfig } from \"../types\";\nimport { getLogger } from \"./logger\";\nimport { TranslationService } from \"../translators\";\nimport { getMetadataPath, loadMetadata } from \"../metadata/manager\";\nimport type { TranslationServerEvent } from \"./ws-events\";\nimport { createEvent } from \"./ws-events\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { parseLocaleOrThrow } from \"../utils/is-valid-locale\";\n\nexport interface TranslationServerOptions {\n config: TranslationMiddlewareConfig;\n translationService?: TranslationService;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n}\n\nexport class TranslationServer {\n private server: http.Server | null = null;\n private url: string | undefined = undefined;\n private logger;\n private readonly config: TranslationMiddlewareConfig;\n private readonly configHash: string;\n private readonly startPort: number;\n private readonly onReadyCallback?: (port: number) => void;\n private readonly onErrorCallback?: (error: Error) => void;\n private metadata: MetadataSchema | null = null;\n private connections: Set<Socket> = new Set();\n private wss: WebSocketServer | null = null;\n private wsClients: Set<WebSocket> = new Set();\n\n // Translation activity tracking for \"busy\" notifications\n private activeTranslations = 0;\n private isBusy = false;\n private busyTimeout: NodeJS.Timeout | null = null;\n private readonly BUSY_DEBOUNCE_MS = 500; // Time after last translation to send \"idle\" event\n private readonly translationService: TranslationService;\n\n constructor(options: TranslationServerOptions) {\n this.config = options.config;\n this.configHash = hashConfig(options.config);\n this.translationService =\n options.translationService ??\n // Fallback is for CLI start only.\n new TranslationService(options.config, getLogger(options.config));\n this.startPort = options.config.dev.translationServerStartPort;\n this.onReadyCallback = options.onReady;\n this.onErrorCallback = options.onError;\n this.logger = getLogger(this.config);\n }\n\n /**\n * Start the server and find an available port\n */\n async start(): Promise<number> {\n if (this.server) {\n throw new Error(\"Server is already running\");\n }\n\n this.logger.info(`šŸ”§ Initializing translator...`);\n\n const port = await this.findAvailablePort(this.startPort);\n\n return new Promise((resolve, reject) => {\n this.server = http.createServer((req, res) => {\n // Log that we received a request (before async handling)\n this.logger.info(`šŸ“„ Received: ${req.method} ${req.url}`);\n\n // Wrap async handler and catch errors explicitly\n this.handleRequest(req, res).catch((error) => {\n this.logger.error(`Request handler error:`, error);\n this.logger.error(error.stack);\n\n // Send error response if headers not sent\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n });\n });\n\n this.logger.debug(`Starting translation server on port ${port}`);\n\n // Track connections for graceful shutdown\n this.server.on(\"connection\", (socket) => {\n this.connections.add(socket);\n socket.once(\"close\", () => {\n this.connections.delete(socket);\n });\n });\n\n this.server.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n // Port is in use, try next one\n reject(new Error(`Port ${port} is already in use`));\n } else {\n this.logger.error(`Translation server error: ${error.message}\\n`);\n this.onErrorCallback?.(error);\n reject(error);\n }\n });\n\n this.server.listen(port, \"127.0.0.1\", () => {\n this.url = `http://127.0.0.1:${port}`;\n this.logger.info(`Translation server listening on ${this.url}`);\n\n // Initialize WebSocket server on the same port\n this.initializeWebSocket();\n\n this.onReadyCallback?.(port);\n resolve(port);\n });\n });\n }\n\n /**\n * Initialize WebSocket server for real-time dev widget updates\n */\n private initializeWebSocket(): void {\n if (!this.server) {\n throw new Error(\"HTTP server must be started before WebSocket\");\n }\n\n this.wss = new WebSocketServer({ server: this.server });\n\n this.wss.on(\"connection\", (ws: WebSocket) => {\n this.wsClients.add(ws);\n this.logger.debug(\n `WebSocket client connected. Total clients: ${this.wsClients.size}`,\n );\n\n // Send initial connected event\n this.sendToClient(ws, createEvent(\"connected\", { serverUrl: this.url! }));\n\n ws.on(\"close\", () => {\n this.wsClients.delete(ws);\n this.logger.debug(\n `WebSocket client disconnected. Total clients: ${this.wsClients.size}`,\n );\n });\n\n ws.on(\"error\", (error) => {\n this.logger.error(`WebSocket client error:`, error);\n this.wsClients.delete(ws);\n });\n });\n\n this.wss.on(\"error\", (error) => {\n this.logger.error(`WebSocket server error:`, error);\n this.onErrorCallback?.(error);\n });\n\n this.logger.info(`WebSocket server initialized`);\n }\n\n /**\n * Send event to a specific WebSocket client\n */\n private sendToClient(ws: WebSocket, event: TranslationServerEvent): void {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(event));\n }\n }\n\n /**\n * Broadcast event to all connected WebSocket clients\n */\n private broadcast(event: TranslationServerEvent): void {\n const message = JSON.stringify(event);\n for (const client of this.wsClients) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(message);\n }\n }\n }\n\n /**\n * Stop the server\n */\n async stop(): Promise<void> {\n if (!this.server) {\n this.logger.debug(\"Translation server is not running. Nothing to stop.\");\n return;\n }\n\n // Clear any pending busy timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n this.busyTimeout = null;\n }\n\n // Close all WebSocket connections\n for (const client of this.wsClients) {\n client.close();\n }\n this.wsClients.clear();\n\n // Close WebSocket server\n if (this.wss) {\n this.wss.close();\n this.wss = null;\n }\n\n // Destroy all active HTTP connections to prevent hanging\n for (const socket of this.connections) {\n socket.destroy();\n }\n this.connections.clear();\n\n return new Promise((resolve, reject) => {\n this.server!.close((error) => {\n if (error) {\n reject(error);\n } else {\n this.logger.info(`Translation server stopped`);\n this.server = null;\n this.url = undefined;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get the current port (null if not running)\n */\n getUrl(): string | undefined {\n return this.url;\n }\n\n /**\n * Start a new server or get the URL of an existing one on the preferred port.\n *\n * This method optimizes for the common case where a translation server is already\n * running on a preferred port. If that port is taken, it checks if it's our service\n * by calling the health check endpoint. If it is, we reuse it instead of starting\n * a new server on a different port.\n *\n * @returns URL of the running server (new or existing)\n */\n async startOrGetUrl(): Promise<string> {\n if (this.server && this.url) {\n this.logger.info(`Using existing server instance at ${this.url}`);\n return this.url;\n }\n\n const preferredPort = this.startPort;\n const preferredUrl = `http://127.0.0.1:${preferredPort}`;\n\n // Check if port is available\n const portAvailable = await this.isPortAvailable(preferredPort);\n\n if (portAvailable) {\n // Port is free, start a new server\n this.logger.info(\n `Port ${preferredPort} is available, starting new server...`,\n );\n await this.start();\n return this.url!;\n }\n\n // Port is taken, check if it's our translation server\n this.logger.info(\n `Port ${preferredPort} is in use, checking if it's a translation server...`,\n );\n const isOurServer = await this.checkIfTranslationServer(preferredUrl);\n\n if (isOurServer) {\n // It's our server, reuse it\n this.logger.info(\n `āœ… Found existing translation server at ${preferredUrl}, reusing it`,\n );\n this.url = preferredUrl;\n return preferredUrl;\n }\n\n // Port is taken by something else, start a new server on a different port\n this.logger.info(\n `Port ${preferredPort} is in use by another service, finding alternative...`,\n );\n await this.start();\n return this.url!;\n }\n\n /**\n * Check if server is running\n */\n isRunning(): boolean {\n return this.server !== null && this.url !== null;\n }\n\n /**\n * Reload metadata from disk\n * Useful when metadata has been updated during runtime (e.g., new transformations)\n */\n async reloadMetadata(): Promise<void> {\n try {\n this.metadata = await loadMetadata(getMetadataPath(this.config));\n this.logger.debug(\n `Reloaded metadata: ${Object.keys(this.metadata).length} entries`,\n );\n } catch (error) {\n this.logger.warn(\"Failed to reload metadata:\", error);\n this.metadata = {};\n }\n }\n\n /**\n * Translate the entire dictionary for a given locale\n *\n * This method always reloads metadata from disk before translating to ensure\n * all entries added during build-time transformations are included.\n *\n * This is the recommended method for build-time translation generation.\n */\n async translateAll(locale: LocaleCode): Promise<{\n translations: Record<string, string>;\n errors: Array<{ hash: string; error: string }>;\n }> {\n if (!this.translationService) {\n throw new Error(\"Translation server not initialized\");\n }\n\n // Always reload metadata to get the latest entries\n // This is critical for build-time translation where metadata is updated\n // continuously as files are transformed\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n const allHashes = Object.keys(this.metadata);\n\n this.logger.info(\n `Translating all ${allHashes.length} entries to ${locale}`,\n );\n\n // Broadcast batch start event\n const startTime = Date.now();\n this.broadcast(\n createEvent(\"batch:start\", {\n locale,\n total: allHashes.length,\n hashes: allHashes,\n }),\n );\n\n const result = await this.translationService.translate(\n locale,\n this.metadata,\n allHashes,\n );\n\n // Broadcast batch complete event\n const duration = Date.now() - startTime;\n this.broadcast(\n createEvent(\"batch:complete\", {\n locale,\n total: allHashes.length,\n successful: Object.keys(result.translations).length,\n failed: result.errors.length,\n duration,\n }),\n );\n\n return result;\n }\n\n /**\n * Find an available port starting from the given port\n */\n private async findAvailablePort(\n startPort: number,\n maxAttempts = 100,\n ): Promise<number> {\n for (let port = startPort; port < startPort + maxAttempts; port++) {\n if (await this.isPortAvailable(port)) {\n return port;\n }\n }\n throw new Error(\n `Could not find available port in range ${startPort}-${startPort + maxAttempts}`,\n );\n }\n\n /**\n * Check if a port is available\n */\n private async isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const testServer = http.createServer();\n\n testServer.once(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n resolve(false);\n } else {\n resolve(false);\n }\n });\n\n testServer.once(\"listening\", () => {\n testServer.close(() => {\n resolve(true);\n });\n });\n\n testServer.listen(port, \"127.0.0.1\");\n });\n }\n\n /**\n * Mark translation activity start - emits busy event if not already busy\n */\n private startTranslationActivity(): void {\n this.activeTranslations++;\n\n // Clear any pending idle timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n this.busyTimeout = null;\n }\n\n // Emit busy event if this is the first active translation\n if (!this.isBusy && this.activeTranslations > 0) {\n this.isBusy = true;\n this.broadcast(\n createEvent(\"server:busy\", {\n activeTranslations: this.activeTranslations,\n }),\n );\n this.logger.debug(\n `[BUSY] Server is now busy (${this.activeTranslations} active)`,\n );\n }\n }\n\n /**\n * Mark translation activity end - emits idle event after debounce period\n */\n private endTranslationActivity(): void {\n this.activeTranslations = Math.max(0, this.activeTranslations - 1);\n\n // If no more active translations, schedule idle notification\n if (this.activeTranslations === 0 && this.isBusy) {\n // Clear any existing timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n }\n\n // Wait for debounce period before sending idle event\n // This prevents rapid busy->idle->busy cycles when translations come in quick succession\n this.busyTimeout = setTimeout(() => {\n if (this.activeTranslations === 0) {\n this.isBusy = false;\n this.broadcast(createEvent(\"server:idle\", {}));\n this.logger.debug(\"[IDLE] Server is now idle\");\n }\n }, this.BUSY_DEBOUNCE_MS);\n }\n }\n\n /**\n * Check if a given URL is running our translation server by calling the health endpoint\n * Also verifies that the config hash matches to ensure compatible configuration\n */\n private async checkIfTranslationServer(url: string): Promise<boolean> {\n return new Promise((resolve) => {\n const healthUrl = `${url}/health`;\n\n const req = http.get(healthUrl, { timeout: 2000 }, (res) => {\n let data = \"\";\n\n res.on(\"data\", (chunk) => {\n data += chunk.toString();\n });\n\n res.on(\"end\", () => {\n try {\n if (res.statusCode === 200) {\n const json = JSON.parse(data);\n // Our translation server returns { status: \"ok\", port: ..., configHash: ... }\n // Check if config hash matches (if present)\n // If configHash is missing (old server), accept it for backward compatibility\n if (json.configHash && json.configHash !== this.configHash) {\n this.logger.warn(\n `Existing server has different config (hash: ${json.configHash} vs ${this.configHash}), will start new server`,\n );\n resolve(false);\n return;\n }\n resolve(true);\n return;\n }\n resolve(false);\n } catch (error) {\n // Failed to parse JSON or invalid response\n resolve(false);\n }\n });\n });\n\n req.on(\"error\", () => {\n // Connection failed, not our server\n resolve(false);\n });\n\n req.on(\"timeout\", () => {\n req.destroy();\n resolve(false);\n });\n });\n }\n\n /**\n * Handle incoming HTTP request\n */\n private async handleRequest(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> {\n this.logger.info(`šŸ”„ Processing: ${req.method} ${req.url}`);\n\n try {\n const url = new URL(req.url || \"\", `http://${req.headers.host}`);\n\n // Log request\n this.logger.debug(`${req.method} ${url.pathname}`);\n\n // Handle CORS for browser requests\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n \"Content-Type, Cache-Control\",\n );\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (url.pathname === \"/health\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n port: this.url,\n configHash: this.configHash,\n }),\n );\n return;\n }\n\n // Batch translation endpoint: POST /translations/:locale\n const postMatch = url.pathname.match(/^\\/translations\\/([^/]+)$/);\n if (postMatch && req.method === \"POST\") {\n const [, locale] = postMatch;\n\n await this.handleBatchTranslationRequest(locale, req, res);\n return;\n }\n\n // Translation dictionary endpoint: GET /translations/:locale\n const dictMatch = url.pathname.match(/^\\/translations\\/([^/]+)$/);\n if (dictMatch && req.method === \"GET\") {\n const [, locale] = dictMatch;\n await this.handleDictionaryRequest(locale, res);\n return;\n }\n\n // 404 for unknown routes\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Not Found\",\n message: \"Unknown endpoint\",\n availableEndpoints: [\n \"GET /health\",\n \"GET /translations/:locale\",\n \"POST /translations/:locale (with body: { hashes: string[] })\",\n ],\n }),\n );\n } catch (error) {\n this.logger.error(\"Error handling request:\", error);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Internal Server Error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n\n /**\n * Handle batch translation request\n */\n private async handleBatchTranslationRequest(\n locale: string,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> {\n try {\n const parsedLocale = parseLocaleOrThrow(locale);\n\n // Read request body\n let body = \"\";\n this.logger.debug(\"Reading request body...\");\n for await (const chunk of req) {\n body += chunk.toString();\n this.logger.debug(`Chunk read, body: ${body}`);\n }\n\n // Parse body\n const { hashes } = JSON.parse(body);\n\n this.logger.debug(`Parsed hashes: ${hashes.join(\",\")}`);\n\n if (!Array.isArray(hashes)) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Bad Request\",\n message: \"Body must contain 'hashes' array\",\n }),\n );\n return;\n }\n // Reload metadata to ensure we have the latest entries\n // (new entries may have been added since server started)\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n this.logger.info(`šŸ”„ Translating ${hashes.length} hashes to ${locale}`);\n this.logger.debug(`šŸ”„ Hashes: ${hashes.join(\", \")}`);\n\n // Mark translation activity start\n this.startTranslationActivity();\n\n try {\n const result = await this.translationService.translate(\n parsedLocale,\n this.metadata,\n hashes,\n );\n\n // Return successful response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify({\n locale,\n translations: result.translations,\n errors: result.errors,\n }),\n );\n } finally {\n // Mark translation activity end\n this.endTranslationActivity();\n }\n } catch (error) {\n this.logger.error(\n `Error getting batch translations for ${locale}:`,\n error,\n );\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Translation generation failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n\n /**\n * Handle request for full translation dictionary\n */\n private async handleDictionaryRequest(\n locale: string,\n res: http.ServerResponse,\n ): Promise<void> {\n try {\n const parsedLocale = parseLocaleOrThrow(locale);\n\n // Reload metadata to ensure we have the latest entries\n // (new entries may have been added since server started)\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n this.logger.info(`🌐 Requesting full dictionary for ${locale}`);\n\n const allHashes = Object.keys(this.metadata);\n\n // Translate all hashes\n const result = await this.translationService.translate(\n parsedLocale,\n this.metadata,\n allHashes,\n );\n\n // Return successful response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"public, max-age=3600\",\n });\n res.end(\n JSON.stringify({\n locale,\n translations: result.translations,\n errors: result.errors,\n }),\n );\n } catch (error) {\n this.logger.error(`Error getting dictionary for ${locale}:`, error);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Translation generation failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n}\n\ntype SerializablePrimitive = string | number | boolean | null | undefined;\n\ntype SerializableObject = {\n [key: string]: SerializableValue;\n};\nexport type SerializableValue =\n | SerializablePrimitive\n | SerializableValue[]\n | SerializableObject;\n\nexport function stableStringify(\n value: Record<string, SerializableValue>,\n): string {\n const normalize = (v: any): any => {\n if (v === undefined) return undefined;\n if (typeof v === \"function\") return undefined;\n if (v === null) return null;\n\n if (Array.isArray(v)) {\n return v.map(normalize).filter((x) => x !== undefined);\n }\n\n if (typeof v === \"object\") {\n const out: Record<string, any> = {};\n for (const key of Object.keys(v).sort()) {\n const next = normalize(v[key]);\n if (next !== undefined) out[key] = next;\n }\n return out;\n }\n\n return v;\n };\n\n return JSON.stringify(normalize(value));\n}\n\n/**\n * Generate a stable hash of a config object\n * Filters out functions and non-serializable values\n * Sorts keys for stability\n */\nexport function hashConfig(config: Record<string, SerializableValue>): string {\n const serialized = stableStringify(config);\n return crypto.createHash(\"md5\").update(serialized).digest(\"hex\").slice(0, 12);\n}\n\nexport async function startTranslationServer(\n options: TranslationServerOptions,\n): Promise<TranslationServer> {\n const server = new TranslationServer(options);\n await server.start();\n return server;\n}\n\n/**\n * Create a translation server and start it or reuse an existing one on the preferred port\n *\n * Since we have little control over the dev server start in next, we can start the translation server only in the async config or in the loader,\n * they both could be run in different processes, and we need a way to avoid starting multiple servers.\n * This one will try to start a server on the preferred port (which seems to be an atomic operation), and if it fails,\n * it checks if the server that is already started is ours and returns its url.\n *\n * @returns Object containing the server instance and its URL\n */\nexport async function startOrGetTranslationServer(\n options: TranslationServerOptions,\n): Promise<{ server: TranslationServer; url: string }> {\n const server = new TranslationServer(options);\n const url = await server.startOrGetUrl();\n return { server, url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B,AAAQ,SAA6B;CACrC,AAAQ,MAA0B;CAClC,AAAQ;CACR,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ,WAAkC;CAC1C,AAAQ,8BAA2B,IAAI,KAAK;CAC5C,AAAQ,MAA8B;CACtC,AAAQ,4BAA4B,IAAI,KAAK;CAG7C,AAAQ,qBAAqB;CAC7B,AAAQ,SAAS;CACjB,AAAQ,cAAqC;CAC7C,AAAiB,mBAAmB;CACpC,AAAiB;CAEjB,YAAY,SAAmC;AAC7C,OAAK,SAAS,QAAQ;AACtB,OAAK,aAAa,WAAW,QAAQ,OAAO;AAC5C,OAAK,qBACH,QAAQ,sBAER,IAAI,mBAAmB,QAAQ,QAAQ,UAAU,QAAQ,OAAO,CAAC;AACnE,OAAK,YAAY,QAAQ,OAAO,IAAI;AACpC,OAAK,kBAAkB,QAAQ;AAC/B,OAAK,kBAAkB,QAAQ;AAC/B,OAAK,SAAS,UAAU,KAAK,OAAO;;;;;CAMtC,MAAM,QAAyB;AAC7B,MAAI,KAAK,OACP,OAAM,IAAI,MAAM,4BAA4B;AAG9C,OAAK,OAAO,KAAK,gCAAgC;EAEjD,MAAM,OAAO,MAAM,KAAK,kBAAkB,KAAK,UAAU;AAEzD,SAAO,IAAI,SAAS,SAAS,WAAW;AACtC,QAAK,SAAS,KAAK,cAAc,KAAK,QAAQ;AAE5C,SAAK,OAAO,KAAK,gBAAgB,IAAI,OAAO,GAAG,IAAI,MAAM;AAGzD,SAAK,cAAc,KAAK,IAAI,CAAC,OAAO,UAAU;AAC5C,UAAK,OAAO,MAAM,0BAA0B,MAAM;AAClD,UAAK,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Ac,OAAO;IACrB,QAAQ,OAAO;IAChB,CAAC,CACH;WACM,OAAO;AACd,QAAK,OAAO,MAAM,gCAAgC,OAAO,IAAI,MAAM;AACnE,OAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,OAAI,IACF,KAAK,UAAU;IACb,OAAO;IACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;IACnD,CAAC,CACH;;;;AAeP,SAAgB,gBACd,OACQ;CACR,MAAM,aAAa,MAAgB;AACjC,MAAI,MAAM,OAAW,QAAO;AAC5B,MAAI,OAAO,MAAM,WAAY,QAAO;AACpC,MAAI,MAAM,KAAM,QAAO;AAEvB,MAAI,MAAM,QAAQ,EAAE,CAClB,QAAO,EAAE,IAAI,UAAU,CAAC,QAAQ,MAAM,MAAM,OAAU;AAGxD,MAAI,OAAO,MAAM,UAAU;GACzB,MAAMA,MAA2B,EAAE;AACnC,QAAK,MAAM,OAAO,OAAO,KAAK,EAAE,CAAC,MAAM,EAAE;IACvC,MAAM,OAAO,UAAU,EAAE,KAAK;AAC9B,QAAI,SAAS,OAAW,KAAI,OAAO;;AAErC,UAAO;;AAGT,SAAO;;AAGT,QAAO,KAAK,UAAU,UAAU,MAAM,CAAC;;;;;;;AAQzC,SAAgB,WAAW,QAAmD;CAC5E,MAAM,aAAa,gBAAgB,OAAO;AAC1C,QAAO,OAAO,WAAW,MAAM,CAAC,OAAO,WAAW,CAAC,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG;;AAG/E,eAAsB,uBACpB,SAC4B;CAC5B,MAAM,SAAS,IAAI,kBAAkB,QAAQ;AAC7C,OAAM,OAAO,OAAO;AACpB,QAAO;;;;;;;;;;;;AAaT,eAAsB,4BACpB,SACqD;CACrD,MAAM,SAAS,IAAI,kBAAkB,QAAQ;AAE7C,QAAO;EAAE;EAAQ,KADL,MAAM,OAAO,eAAe;EAClB"}
1
+ {"version":3,"file":"translation-server.mjs","names":["out: Record<string, any>"],"sources":["../../src/translation-server/translation-server.ts"],"sourcesContent":["/**\n * Simple HTTP server for serving translations during development\n *\n * This server:\n * - Finds a free port automatically\n * - Serves translations via:\n * - GET /translations/:locale - Full dictionary (cached)\n * - POST /translations/:locale (body: { hashes: string[] }) - Batch translation\n * - Uses the same translation logic as middleware\n * - Can be started/stopped programmatically\n */\n\nimport http from \"http\";\nimport crypto from \"crypto\";\nimport type { Socket } from \"net\";\nimport { URL } from \"url\";\nimport { WebSocket, WebSocketServer } from \"ws\";\nimport type { MetadataSchema, TranslationMiddlewareConfig } from \"../types\";\nimport { getLogger } from \"./logger\";\nimport { TranslationService } from \"../translators\";\nimport { getMetadataPath, loadMetadata } from \"../metadata/manager\";\nimport type { TranslationServerEvent } from \"./ws-events\";\nimport { createEvent } from \"./ws-events\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { parseLocaleOrThrow } from \"../utils/is-valid-locale\";\n\nexport interface TranslationServerOptions {\n config: TranslationMiddlewareConfig;\n translationService?: TranslationService;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n}\n\nexport class TranslationServer {\n private server: http.Server | null = null;\n private url: string | undefined = undefined;\n private logger;\n private readonly config: TranslationMiddlewareConfig;\n private readonly configHash: string;\n private readonly startPort: number;\n private readonly onReadyCallback?: (port: number) => void;\n private readonly onErrorCallback?: (error: Error) => void;\n private metadata: MetadataSchema | null = null;\n private connections: Set<Socket> = new Set();\n private wss: WebSocketServer | null = null;\n private wsClients: Set<WebSocket> = new Set();\n\n // Translation activity tracking for \"busy\" notifications\n private activeTranslations = 0;\n private isBusy = false;\n private busyTimeout: NodeJS.Timeout | null = null;\n private readonly BUSY_DEBOUNCE_MS = 500; // Time after last translation to send \"idle\" event\n private readonly translationService: TranslationService;\n\n constructor(options: TranslationServerOptions) {\n this.config = options.config;\n this.configHash = hashConfig(options.config);\n this.translationService =\n options.translationService ??\n // Fallback is for CLI start only.\n new TranslationService(options.config, getLogger(options.config));\n this.startPort = options.config.dev.translationServerStartPort;\n this.onReadyCallback = options.onReady;\n this.onErrorCallback = options.onError;\n this.logger = getLogger(this.config);\n }\n\n /**\n * Start the server and find an available port\n */\n async start(): Promise<number> {\n if (this.server) {\n throw new Error(\"Server is already running\");\n }\n\n this.logger.info(`šŸ”§ Initializing translator...`);\n\n const port = await this.findAvailablePort(this.startPort);\n\n return new Promise((resolve, reject) => {\n this.server = http.createServer((req, res) => {\n // Log that we received a request (before async handling)\n this.logger.info(`šŸ“„ Received: ${req.method} ${req.url}`);\n\n // Wrap async handler and catch errors explicitly\n this.handleRequest(req, res).catch((error) => {\n this.logger.error(`Request handler error:`, error);\n this.logger.error(error.stack);\n\n // Send error response if headers not sent\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n });\n });\n\n this.logger.debug(`Starting translation server on port ${port}`);\n\n // Track connections for graceful shutdown\n this.server.on(\"connection\", (socket) => {\n this.connections.add(socket);\n socket.once(\"close\", () => {\n this.connections.delete(socket);\n });\n });\n\n this.server.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n // Port is in use, try next one\n reject(new Error(`Port ${port} is already in use`));\n } else {\n this.logger.error(`Translation server error: ${error.message}\\n`);\n this.onErrorCallback?.(error);\n reject(error);\n }\n });\n\n this.server.listen(port, \"127.0.0.1\", () => {\n this.url = `http://127.0.0.1:${port}`;\n this.logger.info(`Translation server listening on ${this.url}`);\n\n // Initialize WebSocket server on the same port\n this.initializeWebSocket();\n\n this.onReadyCallback?.(port);\n resolve(port);\n });\n });\n }\n\n /**\n * Initialize WebSocket server for real-time dev widget updates\n */\n private initializeWebSocket(): void {\n if (!this.server) {\n throw new Error(\"HTTP server must be started before WebSocket\");\n }\n\n this.wss = new WebSocketServer({ server: this.server });\n\n this.wss.on(\"connection\", (ws: WebSocket) => {\n this.wsClients.add(ws);\n this.logger.debug(\n `WebSocket client connected. Total clients: ${this.wsClients.size}`,\n );\n\n // Send initial connected event\n this.sendToClient(ws, createEvent(\"connected\", { serverUrl: this.url! }));\n\n ws.on(\"close\", () => {\n this.wsClients.delete(ws);\n this.logger.debug(\n `WebSocket client disconnected. Total clients: ${this.wsClients.size}`,\n );\n });\n\n ws.on(\"error\", (error) => {\n this.logger.error(`WebSocket client error:`, error);\n this.wsClients.delete(ws);\n });\n });\n\n this.wss.on(\"error\", (error) => {\n this.logger.error(`WebSocket server error:`, error);\n this.onErrorCallback?.(error);\n });\n\n this.logger.info(`WebSocket server initialized`);\n }\n\n /**\n * Send event to a specific WebSocket client\n */\n private sendToClient(ws: WebSocket, event: TranslationServerEvent): void {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(event));\n }\n }\n\n /**\n * Broadcast event to all connected WebSocket clients\n */\n private broadcast(event: TranslationServerEvent): void {\n const message = JSON.stringify(event);\n for (const client of this.wsClients) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(message);\n }\n }\n }\n\n /**\n * Stop the server\n */\n async stop(): Promise<void> {\n if (!this.server) {\n this.logger.debug(\"Translation server is not running. Nothing to stop.\");\n return;\n }\n\n // Clear any pending busy timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n this.busyTimeout = null;\n }\n\n // Close all WebSocket connections\n for (const client of this.wsClients) {\n client.close();\n }\n this.wsClients.clear();\n\n // Close WebSocket server\n if (this.wss) {\n this.wss.close();\n this.wss = null;\n }\n\n // Destroy all active HTTP connections to prevent hanging\n for (const socket of this.connections) {\n socket.destroy();\n }\n this.connections.clear();\n\n return new Promise((resolve, reject) => {\n this.server!.close((error) => {\n if (error) {\n reject(error);\n } else {\n this.logger.info(`Translation server stopped`);\n this.server = null;\n this.url = undefined;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get the current port (null if not running)\n */\n getUrl(): string | undefined {\n return this.url;\n }\n\n /**\n * Start a new server or get the URL of an existing one on the preferred port.\n *\n * This method optimizes for the common case where a translation server is already\n * running on a preferred port. If that port is taken, it checks if it's our service\n * by calling the health check endpoint. If it is, we reuse it instead of starting\n * a new server on a different port.\n *\n * @returns URL of the running server (new or existing)\n */\n async startOrGetUrl(): Promise<string> {\n if (this.server && this.url) {\n this.logger.info(`Using existing server instance at ${this.url}`);\n return this.url;\n }\n\n const preferredPort = this.startPort;\n const preferredUrl = `http://127.0.0.1:${preferredPort}`;\n\n // Check if port is available\n const portAvailable = await this.isPortAvailable(preferredPort);\n\n if (portAvailable) {\n // Port is free, start a new server\n this.logger.info(\n `Port ${preferredPort} is available, starting new server...`,\n );\n await this.start();\n return this.url!;\n }\n\n // Port is taken, check if it's our translation server\n this.logger.info(\n `Port ${preferredPort} is in use, checking if it's a translation server...`,\n );\n const isOurServer = await this.checkIfTranslationServer(preferredUrl);\n\n if (isOurServer) {\n // It's our server, reuse it\n this.logger.info(\n `āœ… Found existing translation server at ${preferredUrl}, reusing it`,\n );\n this.url = preferredUrl;\n return preferredUrl;\n }\n\n // Port is taken by something else, start a new server on a different port\n this.logger.info(\n `Port ${preferredPort} is in use by another service, finding alternative...`,\n );\n await this.start();\n return this.url!;\n }\n\n /**\n * Check if server is running\n */\n isRunning(): boolean {\n return this.server !== null && this.url !== null;\n }\n\n /**\n * Reload metadata from disk\n * Useful when metadata has been updated during runtime (e.g., new transformations)\n */\n async reloadMetadata(): Promise<void> {\n try {\n this.metadata = await loadMetadata(getMetadataPath(this.config));\n this.logger.debug(\n `Reloaded metadata: ${Object.keys(this.metadata).length} entries`,\n );\n } catch (error) {\n this.logger.warn(\"Failed to reload metadata:\", error);\n this.metadata = {};\n }\n }\n\n /**\n * Translate the entire dictionary for a given locale\n *\n * This method always reloads metadata from disk before translating to ensure\n * all entries added during build-time transformations are included.\n *\n * This is the recommended method for build-time translation generation.\n */\n async translateAll(locale: LocaleCode): Promise<{\n translations: Record<string, string>;\n errors: Array<{ hash: string; sourceText: string; error: string }>;\n }> {\n if (!this.translationService) {\n throw new Error(\"Translation server not initialized\");\n }\n\n // Always reload metadata to get the latest entries\n // This is critical for build-time translation where metadata is updated\n // continuously as files are transformed\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n const allHashes = Object.keys(this.metadata);\n\n this.logger.info(\n `Translating all ${allHashes.length} entries to ${locale}`,\n );\n\n // Broadcast batch start event\n const startTime = Date.now();\n this.broadcast(\n createEvent(\"batch:start\", {\n locale,\n total: allHashes.length,\n hashes: allHashes,\n }),\n );\n\n const result = await this.translationService.translate(\n locale,\n this.metadata,\n allHashes,\n );\n\n // Log detailed error information to server log file\n if (result.errors.length > 0) {\n this.logger.error(\n `${result.errors.length} translation error(s) for ${locale}:`,\n );\n for (const err of result.errors) {\n const prefix = ` [${locale}]`;\n if (err.hash === \"all\") {\n this.logger.error(`${prefix} ${err.error}`);\n continue;\n }\n const source =\n err.sourceText.length > 200\n ? err.sourceText.slice(0, 200) + \"...\"\n : err.sourceText;\n this.logger.error(\n `${prefix} hash=${err.hash} source=\"${source}\" error=\"${err.error}\"`,\n );\n }\n }\n\n // Broadcast batch complete event\n const duration = Date.now() - startTime;\n this.broadcast(\n createEvent(\"batch:complete\", {\n locale,\n total: allHashes.length,\n successful: Object.keys(result.translations).length,\n failed: result.errors.length,\n duration,\n }),\n );\n\n return result;\n }\n\n /**\n * Find an available port starting from the given port\n */\n private async findAvailablePort(\n startPort: number,\n maxAttempts = 100,\n ): Promise<number> {\n for (let port = startPort; port < startPort + maxAttempts; port++) {\n if (await this.isPortAvailable(port)) {\n return port;\n }\n }\n throw new Error(\n `Could not find available port in range ${startPort}-${startPort + maxAttempts}`,\n );\n }\n\n /**\n * Check if a port is available\n */\n private async isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const testServer = http.createServer();\n\n testServer.once(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n resolve(false);\n } else {\n resolve(false);\n }\n });\n\n testServer.once(\"listening\", () => {\n testServer.close(() => {\n resolve(true);\n });\n });\n\n testServer.listen(port, \"127.0.0.1\");\n });\n }\n\n /**\n * Mark translation activity start - emits busy event if not already busy\n */\n private startTranslationActivity(): void {\n this.activeTranslations++;\n\n // Clear any pending idle timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n this.busyTimeout = null;\n }\n\n // Emit busy event if this is the first active translation\n if (!this.isBusy && this.activeTranslations > 0) {\n this.isBusy = true;\n this.broadcast(\n createEvent(\"server:busy\", {\n activeTranslations: this.activeTranslations,\n }),\n );\n this.logger.debug(\n `[BUSY] Server is now busy (${this.activeTranslations} active)`,\n );\n }\n }\n\n /**\n * Mark translation activity end - emits idle event after debounce period\n */\n private endTranslationActivity(): void {\n this.activeTranslations = Math.max(0, this.activeTranslations - 1);\n\n // If no more active translations, schedule idle notification\n if (this.activeTranslations === 0 && this.isBusy) {\n // Clear any existing timeout\n if (this.busyTimeout) {\n clearTimeout(this.busyTimeout);\n }\n\n // Wait for debounce period before sending idle event\n // This prevents rapid busy->idle->busy cycles when translations come in quick succession\n this.busyTimeout = setTimeout(() => {\n if (this.activeTranslations === 0) {\n this.isBusy = false;\n this.broadcast(createEvent(\"server:idle\", {}));\n this.logger.debug(\"[IDLE] Server is now idle\");\n }\n }, this.BUSY_DEBOUNCE_MS);\n }\n }\n\n /**\n * Check if a given URL is running our translation server by calling the health endpoint\n * Also verifies that the config hash matches to ensure compatible configuration\n */\n private async checkIfTranslationServer(url: string): Promise<boolean> {\n return new Promise((resolve) => {\n const healthUrl = `${url}/health`;\n\n const req = http.get(healthUrl, { timeout: 2000 }, (res) => {\n let data = \"\";\n\n res.on(\"data\", (chunk) => {\n data += chunk.toString();\n });\n\n res.on(\"end\", () => {\n try {\n if (res.statusCode === 200) {\n const json = JSON.parse(data);\n // Our translation server returns { status: \"ok\", port: ..., configHash: ... }\n // Check if config hash matches (if present)\n // If configHash is missing (old server), accept it for backward compatibility\n if (json.configHash && json.configHash !== this.configHash) {\n this.logger.warn(\n `Existing server has different config (hash: ${json.configHash} vs ${this.configHash}), will start new server`,\n );\n resolve(false);\n return;\n }\n resolve(true);\n return;\n }\n resolve(false);\n } catch (error) {\n // Failed to parse JSON or invalid response\n resolve(false);\n }\n });\n });\n\n req.on(\"error\", () => {\n // Connection failed, not our server\n resolve(false);\n });\n\n req.on(\"timeout\", () => {\n req.destroy();\n resolve(false);\n });\n });\n }\n\n /**\n * Handle incoming HTTP request\n */\n private async handleRequest(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> {\n this.logger.info(`šŸ”„ Processing: ${req.method} ${req.url}`);\n\n try {\n const url = new URL(req.url || \"\", `http://${req.headers.host}`);\n\n // Log request\n this.logger.debug(`${req.method} ${url.pathname}`);\n\n // Handle CORS for browser requests\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n \"Content-Type, Cache-Control\",\n );\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (url.pathname === \"/health\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n port: this.url,\n configHash: this.configHash,\n }),\n );\n return;\n }\n\n // Batch translation endpoint: POST /translations/:locale\n const postMatch = url.pathname.match(/^\\/translations\\/([^/]+)$/);\n if (postMatch && req.method === \"POST\") {\n const [, locale] = postMatch;\n\n await this.handleBatchTranslationRequest(locale, req, res);\n return;\n }\n\n // Translation dictionary endpoint: GET /translations/:locale\n const dictMatch = url.pathname.match(/^\\/translations\\/([^/]+)$/);\n if (dictMatch && req.method === \"GET\") {\n const [, locale] = dictMatch;\n await this.handleDictionaryRequest(locale, res);\n return;\n }\n\n // 404 for unknown routes\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Not Found\",\n message: \"Unknown endpoint\",\n availableEndpoints: [\n \"GET /health\",\n \"GET /translations/:locale\",\n \"POST /translations/:locale (with body: { hashes: string[] })\",\n ],\n }),\n );\n } catch (error) {\n this.logger.error(\"Error handling request:\", error);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Internal Server Error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n\n /**\n * Handle batch translation request\n */\n private async handleBatchTranslationRequest(\n locale: string,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> {\n try {\n const parsedLocale = parseLocaleOrThrow(locale);\n\n // Read request body\n let body = \"\";\n this.logger.debug(\"Reading request body...\");\n for await (const chunk of req) {\n body += chunk.toString();\n this.logger.debug(`Chunk read, body: ${body}`);\n }\n\n // Parse body\n const { hashes } = JSON.parse(body);\n\n this.logger.debug(`Parsed hashes: ${hashes.join(\",\")}`);\n\n if (!Array.isArray(hashes)) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Bad Request\",\n message: \"Body must contain 'hashes' array\",\n }),\n );\n return;\n }\n // Reload metadata to ensure we have the latest entries\n // (new entries may have been added since server started)\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n this.logger.info(`šŸ”„ Translating ${hashes.length} hashes to ${locale}`);\n this.logger.debug(`šŸ”„ Hashes: ${hashes.join(\", \")}`);\n\n // Mark translation activity start\n this.startTranslationActivity();\n\n try {\n const result = await this.translationService.translate(\n parsedLocale,\n this.metadata,\n hashes,\n );\n\n // Return successful response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify({\n locale,\n translations: result.translations,\n errors: result.errors,\n }),\n );\n } finally {\n // Mark translation activity end\n this.endTranslationActivity();\n }\n } catch (error) {\n this.logger.error(\n `Error getting batch translations for ${locale}:`,\n error,\n );\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Translation generation failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n\n /**\n * Handle request for full translation dictionary\n */\n private async handleDictionaryRequest(\n locale: string,\n res: http.ServerResponse,\n ): Promise<void> {\n try {\n const parsedLocale = parseLocaleOrThrow(locale);\n\n // Reload metadata to ensure we have the latest entries\n // (new entries may have been added since server started)\n await this.reloadMetadata();\n\n if (!this.metadata) {\n throw new Error(\"Failed to load metadata\");\n }\n\n this.logger.info(`🌐 Requesting full dictionary for ${locale}`);\n\n const allHashes = Object.keys(this.metadata);\n\n // Translate all hashes\n const result = await this.translationService.translate(\n parsedLocale,\n this.metadata,\n allHashes,\n );\n\n // Return successful response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"public, max-age=3600\",\n });\n res.end(\n JSON.stringify({\n locale,\n translations: result.translations,\n errors: result.errors,\n }),\n );\n } catch (error) {\n this.logger.error(`Error getting dictionary for ${locale}:`, error);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Translation generation failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n }\n }\n}\n\ntype SerializablePrimitive = string | number | boolean | null | undefined;\n\ntype SerializableObject = {\n [key: string]: SerializableValue;\n};\nexport type SerializableValue =\n | SerializablePrimitive\n | SerializableValue[]\n | SerializableObject;\n\nexport function stableStringify(\n value: Record<string, SerializableValue>,\n): string {\n const normalize = (v: any): any => {\n if (v === undefined) return undefined;\n if (typeof v === \"function\") return undefined;\n if (v === null) return null;\n\n if (Array.isArray(v)) {\n return v.map(normalize).filter((x) => x !== undefined);\n }\n\n if (typeof v === \"object\") {\n const out: Record<string, any> = {};\n for (const key of Object.keys(v).sort()) {\n const next = normalize(v[key]);\n if (next !== undefined) out[key] = next;\n }\n return out;\n }\n\n return v;\n };\n\n return JSON.stringify(normalize(value));\n}\n\n/**\n * Generate a stable hash of a config object\n * Filters out functions and non-serializable values\n * Sorts keys for stability\n */\nexport function hashConfig(config: Record<string, SerializableValue>): string {\n const serialized = stableStringify(config);\n return crypto.createHash(\"md5\").update(serialized).digest(\"hex\").slice(0, 12);\n}\n\nexport async function startTranslationServer(\n options: TranslationServerOptions,\n): Promise<TranslationServer> {\n const server = new TranslationServer(options);\n await server.start();\n return server;\n}\n\n/**\n * Create a translation server and start it or reuse an existing one on the preferred port\n *\n * Since we have little control over the dev server start in next, we can start the translation server only in the async config or in the loader,\n * they both could be run in different processes, and we need a way to avoid starting multiple servers.\n * This one will try to start a server on the preferred port (which seems to be an atomic operation), and if it fails,\n * it checks if the server that is already started is ours and returns its url.\n *\n * @returns Object containing the server instance and its URL\n */\nexport async function startOrGetTranslationServer(\n options: TranslationServerOptions,\n): Promise<{ server: TranslationServer; url: string }> {\n const server = new TranslationServer(options);\n const url = await server.startOrGetUrl();\n return { server, url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B,AAAQ,SAA6B;CACrC,AAAQ,MAA0B;CAClC,AAAQ;CACR,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ,WAAkC;CAC1C,AAAQ,8BAA2B,IAAI,KAAK;CAC5C,AAAQ,MAA8B;CACtC,AAAQ,4BAA4B,IAAI,KAAK;CAG7C,AAAQ,qBAAqB;CAC7B,AAAQ,SAAS;CACjB,AAAQ,cAAqC;CAC7C,AAAiB,mBAAmB;CACpC,AAAiB;CAEjB,YAAY,SAAmC;AAC7C,OAAK,SAAS,QAAQ;AACtB,OAAK,aAAa,WAAW,QAAQ,OAAO;AAC5C,OAAK,qBACH,QAAQ,sBAER,IAAI,mBAAmB,QAAQ,QAAQ,UAAU,QAAQ,OAAO,CAAC;AACnE,OAAK,YAAY,QAAQ,OAAO,IAAI;AACpC,OAAK,kBAAkB,QAAQ;AAC/B,OAAK,kBAAkB,QAAQ;AAC/B,OAAK,SAAS,UAAU,KAAK,OAAO;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;AACpC,MAAI,MAAM,KAAM,QAAO;AAEvB,MAAI,MAAM,QAAQ,EAAE,CAClB,QAAO,EAAE,IAAI,UAAU,CAAC,QAAQ,MAAM,MAAM,OAAU;AAGxD,MAAI,OAAO,MAAM,UAAU;GACzB,MAAMA,MAA2B,EAAE;AACnC,QAAK,MAAM,OAAO,OAAO,KAAK,EAAE,CAAC,MAAM,EAAE;IACvC,MAAM,OAAO,UAAU,EAAE,KAAK;AAC9B,QAAI,SAAS,OAAW,KAAI,OAAO;;AAErC,UAAO;;AAGT,SAAO;;AAGT,QAAO,KAAK,UAAU,UAAU,MAAM,CAAC;;;;;;;AAQzC,SAAgB,WAAW,QAAmD;CAC5E,MAAM,aAAa,gBAAgB,OAAO;AAC1C,QAAO,OAAO,WAAW,MAAM,CAAC,OAAO,WAAW,CAAC,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG;;AAG/E,eAAsB,uBACpB,SAC4B;CAC5B,MAAM,SAAS,IAAI,kBAAkB,QAAQ;AAC7C,OAAM,OAAO,OAAO;AACpB,QAAO;;;;;;;;;;;;AAaT,eAAsB,4BACpB,SACqD;CACrD,MAAM,SAAS,IAAI,kBAAkB,QAAQ;AAE7C,QAAO;EAAE;EAAQ,KADL,MAAM,OAAO,eAAe;EAClB"}
@@ -100,13 +100,15 @@ Set the required API keys for real translations.`);
100
100
  ...translatedTexts
101
101
  };
102
102
  } catch (error) {
103
- this.logger.error(`Translation failed:`, error);
103
+ const errorMessage = error instanceof Error ? error.message : String(error);
104
+ this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
105
+ if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
104
106
  return {
105
107
  translations: this.pickTranslations(cachedTranslations, workingHashes),
106
108
  errors: [{
107
109
  hash: "all",
108
110
  sourceText: "all",
109
- error: error instanceof Error ? error.message : "Unknown translation error"
111
+ error: errorMessage
110
112
  }],
111
113
  stats: {
112
114
  total: workingHashes.length,
@@ -100,13 +100,15 @@ Set the required API keys for real translations.`);
100
100
  ...translatedTexts
101
101
  };
102
102
  } catch (error) {
103
- this.logger.error(`Translation failed:`, error);
103
+ const errorMessage = error instanceof Error ? error.message : String(error);
104
+ this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
105
+ if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
104
106
  return {
105
107
  translations: this.pickTranslations(cachedTranslations, workingHashes),
106
108
  errors: [{
107
109
  hash: "all",
108
110
  sourceText: "all",
109
- error: error instanceof Error ? error.message : "Unknown translation error"
111
+ error: errorMessage
110
112
  }],
111
113
  stats: {
112
114
  total: workingHashes.length,
@@ -1 +1 @@
1
- {"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","overriddenTranslations: Record<string, string>","hashesNeedingTranslation: string[]","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 { LingoEnvironment, MetadataSchema } from \"../types\";\nimport {\n type PluralizationConfig,\n PluralizationService,\n} from \"./pluralization\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { PseudoTranslator } from \"./pseudotranslator\";\nimport { LingoTranslator } from \"./lingo\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\nimport { MemoryTranslationCache } from \"./memory-cache\";\n\nexport type TranslationServiceConfig = {\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /**\n * Pluralization configuration\n * If provided, enables automatic pluralization of source messages\n */\n pluralization: Omit<PluralizationConfig, \"sourceLocale\">;\n models: \"lingo.dev\" | Record<string, string>;\n prompt?: string;\n environment: LingoEnvironment;\n dev?: {\n usePseudotranslator?: boolean;\n };\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 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 pluralizationService?: PluralizationService;\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n const isDev = config.environment === \"development\";\n\n // 1. Explicit dev override takes precedence\n if (isDev && config.dev?.usePseudotranslator) {\n this.logger.info(\n \"šŸ“ Using pseudotranslator (dev.usePseudotranslator enabled)\",\n );\n this.translator = new PseudoTranslator({ delayMedian: 100 }, logger);\n this.cache = new MemoryTranslationCache();\n } else {\n // 2. Try to create real translator\n // LingoTranslator constructor will validate and fetch API keys\n // If validation fails, it will throw an error with helpful message\n try {\n const models = config.models;\n\n this.logger.debug(\n `Creating Lingo translator with models: ${JSON.stringify(models)}`,\n );\n\n this.cache = createCache(config);\n this.translator = new LingoTranslator(\n {\n models,\n sourceLocale: config.sourceLocale,\n prompt: config.prompt,\n },\n this.logger,\n );\n\n if (this.config.pluralization?.enabled) {\n this.pluralizationService = new PluralizationService(\n {\n ...this.config.pluralization,\n sourceLocale: this.config.sourceLocale,\n },\n this.logger,\n );\n }\n } catch (error) {\n // 3. Auto-fallback in dev mode if creation fails\n if (isDev) {\n // Use console.error to ensure visibility in all contexts (loader, server, etc.)\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(`āš ļø Translation setup error: \\n${errorMsg}\\n\nāš ļø Auto-fallback to pseudotranslator in development mode.\nSet the required API keys for real translations.`);\n\n this.translator = new PseudoTranslator(\n { delayMedian: 100 },\n this.logger,\n );\n this.cache = new MemoryTranslationCache();\n } else {\n // 4. Fail in production\n throw error;\n }\n }\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/pluralization\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: Process pluralization for filtered entries\n if (this.pluralizationService) {\n this.logger.debug(\n `Processing pluralization for ${Object.keys(filteredMetadata).length} entries...`,\n );\n const pluralStats =\n await this.pluralizationService.process(filteredMetadata);\n this.logger.debug(\n `Pluralization stats: ${pluralStats.pluralized} pluralized, ${pluralStats.rejected} rejected, ${pluralStats.failed} failed`,\n );\n }\n\n // Step 6: Separate overridden entries from entries that need translation\n const overriddenTranslations: Record<string, string> = {};\n const hashesNeedingTranslation: string[] = [];\n\n this.logger.debug(\n `Checking for overrides in ${uncachedHashes.length} entries`,\n );\n\n for (const hash of uncachedHashes) {\n const entry = filteredMetadata[hash];\n if (!entry) continue;\n\n // Check if this entry has an override for the current locale\n if (entry.overrides && entry.overrides[locale]) {\n overriddenTranslations[hash] = entry.overrides[locale];\n this.logger.debug(\n `Using override for ${hash} in locale ${locale}: \"${entry.overrides[locale]}\"`,\n );\n } else {\n hashesNeedingTranslation.push(hash);\n }\n }\n\n // Step 7: Prepare entries for translation (excluding overridden ones)\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n hashesNeedingTranslation,\n );\n\n // Step 8: Translate or return source text\n let newTranslations: Record<string, string> = { ...overriddenTranslations };\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the (possibly pluralized) sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${hashesNeedingTranslation.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 only entries without overrides\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 // Merge translated texts with overridden translations\n newTranslations = { ...overriddenTranslations, ...translatedTexts };\n } catch (error) {\n this.logger.error(`Translation failed:`, error);\n\n return {\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error:\n error instanceof Error\n ? error.message\n : \"Unknown translation error\",\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: \"Translator doesn't return translation\",\n });\n }\n }\n }\n\n // Step 5: Update cache with successful translations (skip for pseudo)\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 6: 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":";;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;EAER,MAAM,QAAQ,OAAO,gBAAgB;AAGrC,MAAI,SAAS,OAAO,KAAK,qBAAqB;AAC5C,QAAK,OAAO,KACV,8DACD;AACD,QAAK,aAAa,IAAI,iBAAiB,EAAE,aAAa,KAAK,EAAE,OAAO;AACpE,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,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","overriddenTranslations: Record<string, string>","hashesNeedingTranslation: string[]","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 { LingoEnvironment, MetadataSchema } from \"../types\";\nimport {\n type PluralizationConfig,\n PluralizationService,\n} from \"./pluralization\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { PseudoTranslator } from \"./pseudotranslator\";\nimport { LingoTranslator } from \"./lingo\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\nimport { MemoryTranslationCache } from \"./memory-cache\";\n\nexport type TranslationServiceConfig = {\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /**\n * Pluralization configuration\n * If provided, enables automatic pluralization of source messages\n */\n pluralization: Omit<PluralizationConfig, \"sourceLocale\">;\n models: \"lingo.dev\" | Record<string, string>;\n prompt?: string;\n environment: LingoEnvironment;\n dev?: {\n usePseudotranslator?: boolean;\n };\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 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 pluralizationService?: PluralizationService;\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n const isDev = config.environment === \"development\";\n\n // 1. Explicit dev override takes precedence\n if (isDev && config.dev?.usePseudotranslator) {\n this.logger.info(\n \"šŸ“ Using pseudotranslator (dev.usePseudotranslator enabled)\",\n );\n this.translator = new PseudoTranslator({ delayMedian: 100 }, logger);\n this.cache = new MemoryTranslationCache();\n } else {\n // 2. Try to create real translator\n // LingoTranslator constructor will validate and fetch API keys\n // If validation fails, it will throw an error with helpful message\n try {\n const models = config.models;\n\n this.logger.debug(\n `Creating Lingo translator with models: ${JSON.stringify(models)}`,\n );\n\n this.cache = createCache(config);\n this.translator = new LingoTranslator(\n {\n models,\n sourceLocale: config.sourceLocale,\n prompt: config.prompt,\n },\n this.logger,\n );\n\n if (this.config.pluralization?.enabled) {\n this.pluralizationService = new PluralizationService(\n {\n ...this.config.pluralization,\n sourceLocale: this.config.sourceLocale,\n },\n this.logger,\n );\n }\n } catch (error) {\n // 3. Auto-fallback in dev mode if creation fails\n if (isDev) {\n // Use console.error to ensure visibility in all contexts (loader, server, etc.)\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(`āš ļø Translation setup error: \\n${errorMsg}\\n\nāš ļø Auto-fallback to pseudotranslator in development mode.\nSet the required API keys for real translations.`);\n\n this.translator = new PseudoTranslator(\n { delayMedian: 100 },\n this.logger,\n );\n this.cache = new MemoryTranslationCache();\n } else {\n // 4. Fail in production\n throw error;\n }\n }\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/pluralization\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: Process pluralization for filtered entries\n if (this.pluralizationService) {\n this.logger.debug(\n `Processing pluralization for ${Object.keys(filteredMetadata).length} entries...`,\n );\n const pluralStats =\n await this.pluralizationService.process(filteredMetadata);\n this.logger.debug(\n `Pluralization stats: ${pluralStats.pluralized} pluralized, ${pluralStats.rejected} rejected, ${pluralStats.failed} failed`,\n );\n }\n\n // Step 6: Separate overridden entries from entries that need translation\n const overriddenTranslations: Record<string, string> = {};\n const hashesNeedingTranslation: string[] = [];\n\n this.logger.debug(\n `Checking for overrides in ${uncachedHashes.length} entries`,\n );\n\n for (const hash of uncachedHashes) {\n const entry = filteredMetadata[hash];\n if (!entry) continue;\n\n // Check if this entry has an override for the current locale\n if (entry.overrides && entry.overrides[locale]) {\n overriddenTranslations[hash] = entry.overrides[locale];\n this.logger.debug(\n `Using override for ${hash} in locale ${locale}: \"${entry.overrides[locale]}\"`,\n );\n } else {\n hashesNeedingTranslation.push(hash);\n }\n }\n\n // Step 7: Prepare entries for translation (excluding overridden ones)\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n hashesNeedingTranslation,\n );\n\n // Step 8: Translate or return source text\n let newTranslations: Record<string, string> = { ...overriddenTranslations };\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the (possibly pluralized) sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${hashesNeedingTranslation.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 only entries without overrides\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 // Merge translated texts with overridden translations\n newTranslations = { ...overriddenTranslations, ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\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: \"Translator doesn't return translation\",\n });\n }\n }\n }\n\n // Step 5: Update cache with successful translations (skip for pseudo)\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 6: 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":";;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;EAER,MAAM,QAAQ,OAAO,gBAAgB;AAGrC,MAAI,SAAS,OAAO,KAAK,qBAAqB;AAC5C,QAAK,OAAO,KACV,8DACD;AACD,QAAK,aAAa,IAAI,iBAAiB,EAAE,aAAa,KAAK,EAAE,OAAO;AACpE,QAAK,QAAQ,IAAI,wBAAwB;QAKzC,KAAI;GACF,MAAM,SAAS,OAAO;AAEtB,QAAK,OAAO,MACV,0CAA0C,KAAK,UAA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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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingo.dev/compiler",
3
- "version": "0.3.7",
3
+ "version": "0.3.8",
4
4
  "description": "Lingo.dev Compiler",
5
5
  "private": false,
6
6
  "repository": {
@@ -161,7 +161,7 @@
161
161
  "posthog-node": "5.14.0",
162
162
  "lmdb": "3.2.6",
163
163
  "ws": "8.18.3",
164
- "lingo.dev": "^0.131.1"
164
+ "lingo.dev": "^0.131.4"
165
165
  },
166
166
  "peerDependencies": {
167
167
  "next": "^15.0.0 || ^16.0.4",