@lingo.dev/compiler 0.1.0
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/LICENSE.md +201 -0
- package/README.md +192 -0
- package/build/_virtual/rolldown_runtime.cjs +29 -0
- package/build/_virtual/rolldown_runtime.mjs +7 -0
- package/build/index.cjs +0 -0
- package/build/index.d.cts +2 -0
- package/build/index.d.mts +2 -0
- package/build/index.mjs +1 -0
- package/build/metadata/manager.cjs +131 -0
- package/build/metadata/manager.mjs +123 -0
- package/build/metadata/manager.mjs.map +1 -0
- package/build/plugin/build-translator.cjs +198 -0
- package/build/plugin/build-translator.mjs +196 -0
- package/build/plugin/build-translator.mjs.map +1 -0
- package/build/plugin/cleanup.cjs +20 -0
- package/build/plugin/cleanup.mjs +20 -0
- package/build/plugin/cleanup.mjs.map +1 -0
- package/build/plugin/next-compiler-loader.cjs +41 -0
- package/build/plugin/next-compiler-loader.d.cts +12 -0
- package/build/plugin/next-compiler-loader.d.cts.map +1 -0
- package/build/plugin/next-compiler-loader.d.mts +13 -0
- package/build/plugin/next-compiler-loader.d.mts.map +1 -0
- package/build/plugin/next-compiler-loader.mjs +42 -0
- package/build/plugin/next-compiler-loader.mjs.map +1 -0
- package/build/plugin/next-config-loader.cjs +13 -0
- package/build/plugin/next-config-loader.d.cts +8 -0
- package/build/plugin/next-config-loader.d.cts.map +1 -0
- package/build/plugin/next-config-loader.d.mts +9 -0
- package/build/plugin/next-config-loader.d.mts.map +1 -0
- package/build/plugin/next-config-loader.mjs +14 -0
- package/build/plugin/next-config-loader.mjs.map +1 -0
- package/build/plugin/next-locale-client-loader.cjs +9 -0
- package/build/plugin/next-locale-client-loader.d.cts +8 -0
- package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-client-loader.d.mts +9 -0
- package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-client-loader.mjs +10 -0
- package/build/plugin/next-locale-client-loader.mjs.map +1 -0
- package/build/plugin/next-locale-server-loader.cjs +9 -0
- package/build/plugin/next-locale-server-loader.d.cts +8 -0
- package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-server-loader.d.mts +9 -0
- package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-server-loader.mjs +10 -0
- package/build/plugin/next-locale-server-loader.mjs.map +1 -0
- package/build/plugin/next.cjs +220 -0
- package/build/plugin/next.d.cts +9 -0
- package/build/plugin/next.d.cts.map +1 -0
- package/build/plugin/next.d.mts +9 -0
- package/build/plugin/next.d.mts.map +1 -0
- package/build/plugin/next.mjs +222 -0
- package/build/plugin/next.mjs.map +1 -0
- package/build/plugin/transform/babel-compat.cjs +13 -0
- package/build/plugin/transform/babel-compat.mjs +10 -0
- package/build/plugin/transform/babel-compat.mjs.map +1 -0
- package/build/plugin/transform/index.cjs +44 -0
- package/build/plugin/transform/index.mjs +42 -0
- package/build/plugin/transform/index.mjs.map +1 -0
- package/build/plugin/transform/metadata.cjs +142 -0
- package/build/plugin/transform/metadata.mjs +141 -0
- package/build/plugin/transform/metadata.mjs.map +1 -0
- package/build/plugin/transform/parse-override.cjs +145 -0
- package/build/plugin/transform/parse-override.mjs +144 -0
- package/build/plugin/transform/parse-override.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +391 -0
- package/build/plugin/transform/process-file.mjs +390 -0
- package/build/plugin/transform/process-file.mjs.map +1 -0
- package/build/plugin/transform/use-i18n.cjs +8 -0
- package/build/plugin/transform/use-i18n.mjs +7 -0
- package/build/plugin/transform/use-i18n.mjs.map +1 -0
- package/build/plugin/transform/utils.cjs +205 -0
- package/build/plugin/transform/utils.mjs +192 -0
- package/build/plugin/transform/utils.mjs.map +1 -0
- package/build/plugin/unplugin.cjs +188 -0
- package/build/plugin/unplugin.d.cts +8 -0
- package/build/plugin/unplugin.d.cts.map +1 -0
- package/build/plugin/unplugin.d.mts +8 -0
- package/build/plugin/unplugin.d.mts.map +1 -0
- package/build/plugin/unplugin.mjs +186 -0
- package/build/plugin/unplugin.mjs.map +1 -0
- package/build/plugin/vite.cjs +28 -0
- package/build/plugin/vite.d.cts +9 -0
- package/build/plugin/vite.d.cts.map +1 -0
- package/build/plugin/vite.d.mts +9 -0
- package/build/plugin/vite.d.mts.map +1 -0
- package/build/plugin/vite.mjs +29 -0
- package/build/plugin/vite.mjs.map +1 -0
- package/build/plugin/webpack.cjs +27 -0
- package/build/plugin/webpack.d.cts +8 -0
- package/build/plugin/webpack.d.cts.map +1 -0
- package/build/plugin/webpack.d.mts +8 -0
- package/build/plugin/webpack.d.mts.map +1 -0
- package/build/plugin/webpack.mjs +28 -0
- package/build/plugin/webpack.mjs.map +1 -0
- package/build/react/client/index.cjs +9 -0
- package/build/react/client/index.d.cts +5 -0
- package/build/react/client/index.d.mts +5 -0
- package/build/react/client/index.mjs +6 -0
- package/build/react/client/useTranslation.cjs +71 -0
- package/build/react/client/useTranslation.d.cts +42 -0
- package/build/react/client/useTranslation.d.cts.map +1 -0
- package/build/react/client/useTranslation.d.mts +42 -0
- package/build/react/client/useTranslation.d.mts.map +1 -0
- package/build/react/client/useTranslation.mjs +71 -0
- package/build/react/client/useTranslation.mjs.map +1 -0
- package/build/react/next/client.cjs +25 -0
- package/build/react/next/client.d.cts +9 -0
- package/build/react/next/client.d.cts.map +1 -0
- package/build/react/next/client.d.mts +9 -0
- package/build/react/next/client.d.mts.map +1 -0
- package/build/react/next/client.mjs +24 -0
- package/build/react/next/client.mjs.map +1 -0
- package/build/react/next/cookie-locale-resolver.cjs +29 -0
- package/build/react/next/cookie-locale-resolver.d.cts +33 -0
- package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
- package/build/react/next/cookie-locale-resolver.d.mts +33 -0
- package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
- package/build/react/next/cookie-locale-resolver.mjs +29 -0
- package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
- package/build/react/next/server.cjs +21 -0
- package/build/react/next/server.d.cts +13 -0
- package/build/react/next/server.d.cts.map +1 -0
- package/build/react/next/server.d.mts +14 -0
- package/build/react/next/server.d.mts.map +1 -0
- package/build/react/next/server.mjs +20 -0
- package/build/react/next/server.mjs.map +1 -0
- package/build/react/server/ServerLingoProvider.cjs +19 -0
- package/build/react/server/ServerLingoProvider.d.cts +12 -0
- package/build/react/server/ServerLingoProvider.d.cts.map +1 -0
- package/build/react/server/ServerLingoProvider.d.mts +12 -0
- package/build/react/server/ServerLingoProvider.d.mts.map +1 -0
- package/build/react/server/ServerLingoProvider.mjs +19 -0
- package/build/react/server/ServerLingoProvider.mjs.map +1 -0
- package/build/react/server/index.cjs +7 -0
- package/build/react/server/index.d.cts +4 -0
- package/build/react/server/index.d.mts +4 -0
- package/build/react/server/index.mjs +5 -0
- package/build/react/server/useTranslation.cjs +60 -0
- package/build/react/server/useTranslation.d.cts +36 -0
- package/build/react/server/useTranslation.d.cts.map +1 -0
- package/build/react/server/useTranslation.d.mts +36 -0
- package/build/react/server/useTranslation.d.mts.map +1 -0
- package/build/react/server/useTranslation.mjs +60 -0
- package/build/react/server/useTranslation.mjs.map +1 -0
- package/build/react/server-only/index.cjs +42 -0
- package/build/react/server-only/index.d.cts +38 -0
- package/build/react/server-only/index.d.cts.map +1 -0
- package/build/react/server-only/index.d.mts +38 -0
- package/build/react/server-only/index.d.mts.map +1 -0
- package/build/react/server-only/index.mjs +42 -0
- package/build/react/server-only/index.mjs.map +1 -0
- package/build/react/server-only/translations.cjs +85 -0
- package/build/react/server-only/translations.mjs +85 -0
- package/build/react/server-only/translations.mjs.map +1 -0
- package/build/react/shared/LingoContext.cjs +14 -0
- package/build/react/shared/LingoContext.d.cts +41 -0
- package/build/react/shared/LingoContext.d.cts.map +1 -0
- package/build/react/shared/LingoContext.d.mts +41 -0
- package/build/react/shared/LingoContext.d.mts.map +1 -0
- package/build/react/shared/LingoContext.mjs +13 -0
- package/build/react/shared/LingoContext.mjs.map +1 -0
- package/build/react/shared/LingoProvider.cjs +274 -0
- package/build/react/shared/LingoProvider.d.cts +76 -0
- package/build/react/shared/LingoProvider.d.cts.map +1 -0
- package/build/react/shared/LingoProvider.d.mts +76 -0
- package/build/react/shared/LingoProvider.d.mts.map +1 -0
- package/build/react/shared/LingoProvider.mjs +274 -0
- package/build/react/shared/LingoProvider.mjs.map +1 -0
- package/build/react/shared/LocaleSwitcher.cjs +61 -0
- package/build/react/shared/LocaleSwitcher.d.cts +71 -0
- package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
- package/build/react/shared/LocaleSwitcher.d.mts +71 -0
- package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
- package/build/react/shared/LocaleSwitcher.mjs +61 -0
- package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
- package/build/react/shared/render-rich-text.cjs +55 -0
- package/build/react/shared/render-rich-text.d.cts +17 -0
- package/build/react/shared/render-rich-text.d.cts.map +1 -0
- package/build/react/shared/render-rich-text.d.mts +17 -0
- package/build/react/shared/render-rich-text.d.mts.map +1 -0
- package/build/react/shared/render-rich-text.mjs +54 -0
- package/build/react/shared/render-rich-text.mjs.map +1 -0
- package/build/react/shared/utils.cjs +34 -0
- package/build/react/shared/utils.mjs +35 -0
- package/build/react/shared/utils.mjs.map +1 -0
- package/build/react/types.d.cts +16 -0
- package/build/react/types.d.cts.map +1 -0
- package/build/react/types.d.mts +16 -0
- package/build/react/types.d.mts.map +1 -0
- package/build/translation-server/logger.cjs +37 -0
- package/build/translation-server/logger.mjs +37 -0
- package/build/translation-server/logger.mjs.map +1 -0
- package/build/translation-server/translation-server.cjs +547 -0
- package/build/translation-server/translation-server.mjs +544 -0
- package/build/translation-server/translation-server.mjs.map +1 -0
- package/build/translation-server/ws-events.cjs +15 -0
- package/build/translation-server/ws-events.mjs +15 -0
- package/build/translation-server/ws-events.mjs.map +1 -0
- package/build/translators/api.cjs +12 -0
- package/build/translators/api.mjs +12 -0
- package/build/translators/api.mjs.map +1 -0
- package/build/translators/cache-factory.cjs +26 -0
- package/build/translators/cache-factory.mjs +27 -0
- package/build/translators/cache-factory.mjs.map +1 -0
- package/build/translators/lingo/model-factory.cjs +179 -0
- package/build/translators/lingo/model-factory.mjs +174 -0
- package/build/translators/lingo/model-factory.mjs.map +1 -0
- package/build/translators/lingo/prompt.cjs +43 -0
- package/build/translators/lingo/prompt.mjs +43 -0
- package/build/translators/lingo/prompt.mjs.map +1 -0
- package/build/translators/lingo/service.cjs +152 -0
- package/build/translators/lingo/service.mjs +152 -0
- package/build/translators/lingo/service.mjs.map +1 -0
- package/build/translators/lingo/shots.cjs +28 -0
- package/build/translators/lingo/shots.mjs +28 -0
- package/build/translators/lingo/shots.mjs.map +1 -0
- package/build/translators/local-cache.cjs +115 -0
- package/build/translators/local-cache.mjs +113 -0
- package/build/translators/local-cache.mjs.map +1 -0
- package/build/translators/parse-xml.cjs +109 -0
- package/build/translators/parse-xml.mjs +108 -0
- package/build/translators/parse-xml.mjs.map +1 -0
- package/build/translators/pluralization/icu-validator.cjs +36 -0
- package/build/translators/pluralization/icu-validator.mjs +36 -0
- package/build/translators/pluralization/icu-validator.mjs.map +1 -0
- package/build/translators/pluralization/pattern-detector.cjs +25 -0
- package/build/translators/pluralization/pattern-detector.mjs +25 -0
- package/build/translators/pluralization/pattern-detector.mjs.map +1 -0
- package/build/translators/pluralization/prompt.cjs +98 -0
- package/build/translators/pluralization/prompt.mjs +98 -0
- package/build/translators/pluralization/prompt.mjs.map +1 -0
- package/build/translators/pluralization/service.cjs +247 -0
- package/build/translators/pluralization/service.mjs +247 -0
- package/build/translators/pluralization/service.mjs.map +1 -0
- package/build/translators/pluralization/shots.cjs +53 -0
- package/build/translators/pluralization/shots.mjs +53 -0
- package/build/translators/pluralization/shots.mjs.map +1 -0
- package/build/translators/pluralization/types.d.cts +17 -0
- package/build/translators/pluralization/types.d.cts.map +1 -0
- package/build/translators/pluralization/types.d.mts +17 -0
- package/build/translators/pluralization/types.d.mts.map +1 -0
- package/build/translators/pseudotranslator/index.cjs +129 -0
- package/build/translators/pseudotranslator/index.mjs +129 -0
- package/build/translators/pseudotranslator/index.mjs.map +1 -0
- package/build/translators/translation-service.cjs +182 -0
- package/build/translators/translation-service.mjs +183 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/translator-factory.cjs +49 -0
- package/build/translators/translator-factory.mjs +50 -0
- package/build/translators/translator-factory.mjs.map +1 -0
- package/build/types.d.cts +161 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +161 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +58 -0
- package/build/utils/config-factory.mjs +58 -0
- package/build/utils/config-factory.mjs.map +1 -0
- package/build/utils/hash.cjs +17 -0
- package/build/utils/hash.mjs +16 -0
- package/build/utils/hash.mjs.map +1 -0
- package/build/utils/is-valid-locale.cjs +14 -0
- package/build/utils/is-valid-locale.mjs +14 -0
- package/build/utils/is-valid-locale.mjs.map +1 -0
- package/build/utils/logger.cjs +51 -0
- package/build/utils/logger.mjs +50 -0
- package/build/utils/logger.mjs.map +1 -0
- package/build/utils/path-helpers.cjs +49 -0
- package/build/utils/path-helpers.mjs +47 -0
- package/build/utils/path-helpers.mjs.map +1 -0
- package/build/utils/timeout.cjs +42 -0
- package/build/utils/timeout.mjs +41 -0
- package/build/utils/timeout.mjs.map +1 -0
- package/build/virtual/code-generator.cjs +54 -0
- package/build/virtual/code-generator.mjs +53 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +10 -0
- package/build/virtual/config.d.cts +9 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +9 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +8 -0
- package/build/virtual/config.mjs.map +1 -0
- package/build/virtual/locale/client.cjs +23 -0
- package/build/virtual/locale/client.d.cts +19 -0
- package/build/virtual/locale/client.d.cts.map +1 -0
- package/build/virtual/locale/client.d.mts +19 -0
- package/build/virtual/locale/client.d.mts.map +1 -0
- package/build/virtual/locale/client.mjs +22 -0
- package/build/virtual/locale/client.mjs.map +1 -0
- package/build/virtual/locale/server.cjs +13 -0
- package/build/virtual/locale/server.d.cts +13 -0
- package/build/virtual/locale/server.d.cts.map +1 -0
- package/build/virtual/locale/server.d.mts +13 -0
- package/build/virtual/locale/server.d.mts.map +1 -0
- package/build/virtual/locale/server.mjs +13 -0
- package/build/virtual/locale/server.mjs.map +1 -0
- package/build/widget/lingo-dev-widget.cjs +228 -0
- package/build/widget/lingo-dev-widget.mjs +229 -0
- package/build/widget/lingo-dev-widget.mjs.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { getLogger } from "./logger.mjs";
|
|
2
|
+
import { createTranslator } from "../translators/translator-factory.mjs";
|
|
3
|
+
import { TranslationService } from "../translators/translation-service.mjs";
|
|
4
|
+
import { createCache } from "../translators/cache-factory.mjs";
|
|
5
|
+
import { createEmptyMetadata, getMetadataPath, loadMetadata } from "../metadata/manager.mjs";
|
|
6
|
+
import { createEvent } from "./ws-events.mjs";
|
|
7
|
+
import { parseLocaleOrThrow } from "../utils/is-valid-locale.mjs";
|
|
8
|
+
import http from "http";
|
|
9
|
+
import crypto from "crypto";
|
|
10
|
+
import { URL } from "url";
|
|
11
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
12
|
+
|
|
13
|
+
//#region src/translation-server/translation-server.ts
|
|
14
|
+
/**
|
|
15
|
+
* Simple HTTP server for serving translations during development
|
|
16
|
+
*
|
|
17
|
+
* This server:
|
|
18
|
+
* - Finds a free port automatically
|
|
19
|
+
* - Serves translations via:
|
|
20
|
+
* - GET /translations/:locale - Full dictionary (cached)
|
|
21
|
+
* - POST /translations/:locale (body: { hashes: string[] }) - Batch translation
|
|
22
|
+
* - Uses the same translation logic as middleware
|
|
23
|
+
* - Can be started/stopped programmatically
|
|
24
|
+
*/
|
|
25
|
+
var TranslationServer = class {
|
|
26
|
+
server = null;
|
|
27
|
+
url = void 0;
|
|
28
|
+
logger;
|
|
29
|
+
config;
|
|
30
|
+
configHash;
|
|
31
|
+
startPort;
|
|
32
|
+
onReadyCallback;
|
|
33
|
+
onErrorCallback;
|
|
34
|
+
translationService = null;
|
|
35
|
+
metadata = null;
|
|
36
|
+
connections = /* @__PURE__ */ new Set();
|
|
37
|
+
wss = null;
|
|
38
|
+
wsClients = /* @__PURE__ */ new Set();
|
|
39
|
+
activeTranslations = 0;
|
|
40
|
+
isBusy = false;
|
|
41
|
+
busyTimeout = null;
|
|
42
|
+
BUSY_DEBOUNCE_MS = 500;
|
|
43
|
+
constructor(options) {
|
|
44
|
+
this.config = options.config;
|
|
45
|
+
this.configHash = hashConfig(options.config);
|
|
46
|
+
this.startPort = options.startPort || 6e4;
|
|
47
|
+
this.onReadyCallback = options.onReady;
|
|
48
|
+
this.onErrorCallback = options.onError;
|
|
49
|
+
this.logger = getLogger(this.config);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Start the server and find an available port
|
|
53
|
+
*/
|
|
54
|
+
async start() {
|
|
55
|
+
if (this.server) throw new Error("Server is already running");
|
|
56
|
+
this.logger.info(`🔧 Initializing translator...`);
|
|
57
|
+
this.translationService = new TranslationService(createTranslator(this.config, this.logger), createCache(this.config), {
|
|
58
|
+
sourceLocale: this.config.sourceLocale,
|
|
59
|
+
pluralization: this.config.pluralization
|
|
60
|
+
}, this.logger);
|
|
61
|
+
const port = await this.findAvailablePort(this.startPort);
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
this.server = http.createServer((req, res) => {
|
|
64
|
+
this.logger.info(`📥 Received: ${req.method} ${req.url}`);
|
|
65
|
+
this.handleRequest(req, res).catch((error) => {
|
|
66
|
+
this.logger.error(`Request handler error:`, error);
|
|
67
|
+
this.logger.error(error.stack);
|
|
68
|
+
if (!res.headersSent) {
|
|
69
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
70
|
+
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
this.logger.debug(`Starting translation server on port ${port}`);
|
|
75
|
+
this.server.on("connection", (socket) => {
|
|
76
|
+
this.connections.add(socket);
|
|
77
|
+
socket.once("close", () => {
|
|
78
|
+
this.connections.delete(socket);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
this.server.on("error", (error) => {
|
|
82
|
+
if (error.code === "EADDRINUSE") reject(/* @__PURE__ */ new Error(`Port ${port} is already in use`));
|
|
83
|
+
else {
|
|
84
|
+
this.logger.error(`Translation server error: ${error.message}\n`);
|
|
85
|
+
this.onErrorCallback?.(error);
|
|
86
|
+
reject(error);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
this.server.listen(port, "127.0.0.1", () => {
|
|
90
|
+
this.url = `http://127.0.0.1:${port}`;
|
|
91
|
+
this.logger.info(`Translation server listening on ${this.url}`);
|
|
92
|
+
this.initializeWebSocket();
|
|
93
|
+
this.onReadyCallback?.(port);
|
|
94
|
+
resolve(port);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Initialize WebSocket server for real-time dev widget updates
|
|
100
|
+
*/
|
|
101
|
+
initializeWebSocket() {
|
|
102
|
+
if (!this.server) throw new Error("HTTP server must be started before WebSocket");
|
|
103
|
+
this.wss = new WebSocketServer({ server: this.server });
|
|
104
|
+
this.wss.on("connection", (ws) => {
|
|
105
|
+
this.wsClients.add(ws);
|
|
106
|
+
this.logger.debug(`WebSocket client connected. Total clients: ${this.wsClients.size}`);
|
|
107
|
+
this.sendToClient(ws, createEvent("connected", { serverUrl: this.url }));
|
|
108
|
+
ws.on("close", () => {
|
|
109
|
+
this.wsClients.delete(ws);
|
|
110
|
+
this.logger.debug(`WebSocket client disconnected. Total clients: ${this.wsClients.size}`);
|
|
111
|
+
});
|
|
112
|
+
ws.on("error", (error) => {
|
|
113
|
+
this.logger.error(`WebSocket client error:`, error);
|
|
114
|
+
this.wsClients.delete(ws);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
this.wss.on("error", (error) => {
|
|
118
|
+
this.logger.error(`WebSocket server error:`, error);
|
|
119
|
+
this.onErrorCallback?.(error);
|
|
120
|
+
});
|
|
121
|
+
this.logger.info(`WebSocket server initialized`);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Send event to a specific WebSocket client
|
|
125
|
+
*/
|
|
126
|
+
sendToClient(ws, event) {
|
|
127
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(event));
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Broadcast event to all connected WebSocket clients
|
|
131
|
+
*/
|
|
132
|
+
broadcast(event) {
|
|
133
|
+
const message = JSON.stringify(event);
|
|
134
|
+
for (const client of this.wsClients) if (client.readyState === WebSocket.OPEN) client.send(message);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Stop the server
|
|
138
|
+
*/
|
|
139
|
+
async stop() {
|
|
140
|
+
if (!this.server) {
|
|
141
|
+
this.logger.debug("Translation server is not running. Nothing to stop.");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (this.busyTimeout) {
|
|
145
|
+
clearTimeout(this.busyTimeout);
|
|
146
|
+
this.busyTimeout = null;
|
|
147
|
+
}
|
|
148
|
+
for (const client of this.wsClients) client.close();
|
|
149
|
+
this.wsClients.clear();
|
|
150
|
+
if (this.wss) {
|
|
151
|
+
this.wss.close();
|
|
152
|
+
this.wss = null;
|
|
153
|
+
}
|
|
154
|
+
for (const socket of this.connections) socket.destroy();
|
|
155
|
+
this.connections.clear();
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
this.server.close((error) => {
|
|
158
|
+
if (error) reject(error);
|
|
159
|
+
else {
|
|
160
|
+
this.logger.info(`Translation server stopped`);
|
|
161
|
+
this.server = null;
|
|
162
|
+
this.url = void 0;
|
|
163
|
+
resolve();
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Get the current port (null if not running)
|
|
170
|
+
*/
|
|
171
|
+
getUrl() {
|
|
172
|
+
return this.url;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Start a new server or get the URL of an existing one on the preferred port.
|
|
176
|
+
*
|
|
177
|
+
* This method optimizes for the common case where a translation server is already
|
|
178
|
+
* running on port 60000. If that port is taken, it checks if it's our service
|
|
179
|
+
* by calling the health check endpoint. If it is, we reuse it instead of starting
|
|
180
|
+
* a new server on a different port.
|
|
181
|
+
*
|
|
182
|
+
* @returns URL of the running server (new or existing)
|
|
183
|
+
*/
|
|
184
|
+
async startOrGetUrl() {
|
|
185
|
+
if (this.server && this.url) {
|
|
186
|
+
this.logger.info(`Using existing server instance at ${this.url}`);
|
|
187
|
+
return this.url;
|
|
188
|
+
}
|
|
189
|
+
const preferredPort = this.startPort;
|
|
190
|
+
const preferredUrl = `http://127.0.0.1:${preferredPort}`;
|
|
191
|
+
if (await this.isPortAvailable(preferredPort)) {
|
|
192
|
+
this.logger.info(`Port ${preferredPort} is available, starting new server...`);
|
|
193
|
+
await this.start();
|
|
194
|
+
return this.url;
|
|
195
|
+
}
|
|
196
|
+
this.logger.info(`Port ${preferredPort} is in use, checking if it's a translation server...`);
|
|
197
|
+
if (await this.checkIfTranslationServer(preferredUrl)) {
|
|
198
|
+
this.logger.info(`✅ Found existing translation server at ${preferredUrl}, reusing it`);
|
|
199
|
+
this.url = preferredUrl;
|
|
200
|
+
return preferredUrl;
|
|
201
|
+
}
|
|
202
|
+
this.logger.info(`Port ${preferredPort} is in use by another service, finding alternative...`);
|
|
203
|
+
await this.start();
|
|
204
|
+
return this.url;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Check if server is running
|
|
208
|
+
*/
|
|
209
|
+
isRunning() {
|
|
210
|
+
return this.server !== null && this.url !== null;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Reload metadata from disk
|
|
214
|
+
* Useful when metadata has been updated during runtime (e.g., new transformations)
|
|
215
|
+
*/
|
|
216
|
+
async reloadMetadata() {
|
|
217
|
+
try {
|
|
218
|
+
this.metadata = await loadMetadata(getMetadataPath(this.config));
|
|
219
|
+
this.logger.debug(`Reloaded metadata: ${Object.keys(this.metadata.entries).length} entries`);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.logger.warn("Failed to reload metadata:", error);
|
|
222
|
+
this.metadata = createEmptyMetadata();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Translate the entire dictionary for a given locale
|
|
227
|
+
*
|
|
228
|
+
* This method always reloads metadata from disk before translating to ensure
|
|
229
|
+
* all entries added during build-time transformations are included.
|
|
230
|
+
*
|
|
231
|
+
* This is the recommended method for build-time translation generation.
|
|
232
|
+
*/
|
|
233
|
+
async translateAll(locale) {
|
|
234
|
+
if (!this.translationService) throw new Error("Translation server not initialized");
|
|
235
|
+
await this.reloadMetadata();
|
|
236
|
+
if (!this.metadata) throw new Error("Failed to load metadata");
|
|
237
|
+
const allHashes = Object.keys(this.metadata.entries);
|
|
238
|
+
this.logger.info(`Translating all ${allHashes.length} entries to ${locale}`);
|
|
239
|
+
const startTime = Date.now();
|
|
240
|
+
this.broadcast(createEvent("batch:start", {
|
|
241
|
+
locale,
|
|
242
|
+
total: allHashes.length,
|
|
243
|
+
hashes: allHashes
|
|
244
|
+
}));
|
|
245
|
+
const result = await this.translationService.translate(locale, this.metadata, allHashes);
|
|
246
|
+
const duration = Date.now() - startTime;
|
|
247
|
+
this.broadcast(createEvent("batch:complete", {
|
|
248
|
+
locale,
|
|
249
|
+
total: allHashes.length,
|
|
250
|
+
successful: Object.keys(result.translations).length,
|
|
251
|
+
failed: result.errors.length,
|
|
252
|
+
duration
|
|
253
|
+
}));
|
|
254
|
+
return result;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Find an available port starting from the given port
|
|
258
|
+
*/
|
|
259
|
+
async findAvailablePort(startPort, maxAttempts = 100) {
|
|
260
|
+
for (let port = startPort; port < startPort + maxAttempts; port++) if (await this.isPortAvailable(port)) return port;
|
|
261
|
+
throw new Error(`Could not find available port in range ${startPort}-${startPort + maxAttempts}`);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Check if a port is available
|
|
265
|
+
*/
|
|
266
|
+
async isPortAvailable(port) {
|
|
267
|
+
return new Promise((resolve) => {
|
|
268
|
+
const testServer = http.createServer();
|
|
269
|
+
testServer.once("error", (error) => {
|
|
270
|
+
if (error.code === "EADDRINUSE") resolve(false);
|
|
271
|
+
else resolve(false);
|
|
272
|
+
});
|
|
273
|
+
testServer.once("listening", () => {
|
|
274
|
+
testServer.close(() => {
|
|
275
|
+
resolve(true);
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
testServer.listen(port, "127.0.0.1");
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Mark translation activity start - emits busy event if not already busy
|
|
283
|
+
*/
|
|
284
|
+
startTranslationActivity() {
|
|
285
|
+
this.activeTranslations++;
|
|
286
|
+
if (this.busyTimeout) {
|
|
287
|
+
clearTimeout(this.busyTimeout);
|
|
288
|
+
this.busyTimeout = null;
|
|
289
|
+
}
|
|
290
|
+
if (!this.isBusy && this.activeTranslations > 0) {
|
|
291
|
+
this.isBusy = true;
|
|
292
|
+
this.broadcast(createEvent("server:busy", { activeTranslations: this.activeTranslations }));
|
|
293
|
+
this.logger.debug(`[BUSY] Server is now busy (${this.activeTranslations} active)`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Mark translation activity end - emits idle event after debounce period
|
|
298
|
+
*/
|
|
299
|
+
endTranslationActivity() {
|
|
300
|
+
this.activeTranslations = Math.max(0, this.activeTranslations - 1);
|
|
301
|
+
if (this.activeTranslations === 0 && this.isBusy) {
|
|
302
|
+
if (this.busyTimeout) clearTimeout(this.busyTimeout);
|
|
303
|
+
this.busyTimeout = setTimeout(() => {
|
|
304
|
+
if (this.activeTranslations === 0) {
|
|
305
|
+
this.isBusy = false;
|
|
306
|
+
this.broadcast(createEvent("server:idle", {}));
|
|
307
|
+
this.logger.debug("[IDLE] Server is now idle");
|
|
308
|
+
}
|
|
309
|
+
}, this.BUSY_DEBOUNCE_MS);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Check if a given URL is running our translation server by calling the health endpoint
|
|
314
|
+
* Also verifies that the config hash matches to ensure compatible configuration
|
|
315
|
+
*/
|
|
316
|
+
async checkIfTranslationServer(url) {
|
|
317
|
+
return new Promise((resolve) => {
|
|
318
|
+
const healthUrl = `${url}/health`;
|
|
319
|
+
const req = http.get(healthUrl, { timeout: 2e3 }, (res) => {
|
|
320
|
+
let data = "";
|
|
321
|
+
res.on("data", (chunk) => {
|
|
322
|
+
data += chunk.toString();
|
|
323
|
+
});
|
|
324
|
+
res.on("end", () => {
|
|
325
|
+
try {
|
|
326
|
+
if (res.statusCode === 200) {
|
|
327
|
+
const json = JSON.parse(data);
|
|
328
|
+
if (json.configHash && json.configHash !== this.configHash) {
|
|
329
|
+
this.logger.warn(`Existing server has different config (hash: ${json.configHash} vs ${this.configHash}), will start new server`);
|
|
330
|
+
resolve(false);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
resolve(true);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
resolve(false);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
resolve(false);
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
req.on("error", () => {
|
|
343
|
+
resolve(false);
|
|
344
|
+
});
|
|
345
|
+
req.on("timeout", () => {
|
|
346
|
+
req.destroy();
|
|
347
|
+
resolve(false);
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Handle incoming HTTP request
|
|
353
|
+
*/
|
|
354
|
+
async handleRequest(req, res) {
|
|
355
|
+
this.logger.info(`🔄 Processing: ${req.method} ${req.url}`);
|
|
356
|
+
try {
|
|
357
|
+
const url = new URL(req.url || "", `http://${req.headers.host}`);
|
|
358
|
+
this.logger.debug(`${req.method} ${url.pathname}`);
|
|
359
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
360
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
361
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
362
|
+
res.setHeader("Access-Control-Expose-Headers", "Content-Type, Cache-Control");
|
|
363
|
+
if (req.method === "OPTIONS") {
|
|
364
|
+
res.writeHead(204);
|
|
365
|
+
res.end();
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (url.pathname === "/health") {
|
|
369
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
370
|
+
res.end(JSON.stringify({
|
|
371
|
+
port: this.url,
|
|
372
|
+
configHash: this.configHash
|
|
373
|
+
}));
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const postMatch = url.pathname.match(/^\/translations\/([^/]+)$/);
|
|
377
|
+
if (postMatch && req.method === "POST") {
|
|
378
|
+
const [, locale] = postMatch;
|
|
379
|
+
await this.handleBatchTranslationRequest(locale, req, res);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const dictMatch = url.pathname.match(/^\/translations\/([^/]+)$/);
|
|
383
|
+
if (dictMatch && req.method === "GET") {
|
|
384
|
+
const [, locale] = dictMatch;
|
|
385
|
+
await this.handleDictionaryRequest(locale, res);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
389
|
+
res.end(JSON.stringify({
|
|
390
|
+
error: "Not Found",
|
|
391
|
+
message: "Unknown endpoint",
|
|
392
|
+
availableEndpoints: [
|
|
393
|
+
"GET /health",
|
|
394
|
+
"GET /translations/:locale",
|
|
395
|
+
"POST /translations/:locale (with body: { hashes: string[] })"
|
|
396
|
+
]
|
|
397
|
+
}));
|
|
398
|
+
} catch (error) {
|
|
399
|
+
this.logger.error("Error handling request:", error);
|
|
400
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
401
|
+
res.end(JSON.stringify({
|
|
402
|
+
error: "Internal Server Error",
|
|
403
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
404
|
+
}));
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Handle batch translation request
|
|
409
|
+
*/
|
|
410
|
+
async handleBatchTranslationRequest(locale, req, res) {
|
|
411
|
+
try {
|
|
412
|
+
const parsedLocale = parseLocaleOrThrow(locale);
|
|
413
|
+
let body = "";
|
|
414
|
+
this.logger.debug("Reading request body...");
|
|
415
|
+
for await (const chunk of req) {
|
|
416
|
+
body += chunk.toString();
|
|
417
|
+
this.logger.debug(`Chunk read, body: ${body}`);
|
|
418
|
+
}
|
|
419
|
+
const { hashes } = JSON.parse(body);
|
|
420
|
+
this.logger.debug(`Parsed hashes: ${hashes.join(",")}`);
|
|
421
|
+
if (!Array.isArray(hashes)) {
|
|
422
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
423
|
+
res.end(JSON.stringify({
|
|
424
|
+
error: "Bad Request",
|
|
425
|
+
message: "Body must contain 'hashes' array"
|
|
426
|
+
}));
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (!this.translationService) throw new Error("Translation service not initialized");
|
|
430
|
+
await this.reloadMetadata();
|
|
431
|
+
if (!this.metadata) throw new Error("Failed to load metadata");
|
|
432
|
+
this.logger.info(`🔄 Translating ${hashes.length} hashes to ${locale}`);
|
|
433
|
+
this.logger.debug(`🔄 Hashes: ${hashes.join(", ")}`);
|
|
434
|
+
this.startTranslationActivity();
|
|
435
|
+
try {
|
|
436
|
+
const result = await this.translationService.translate(parsedLocale, this.metadata, hashes);
|
|
437
|
+
res.writeHead(200, {
|
|
438
|
+
"Content-Type": "application/json",
|
|
439
|
+
"Cache-Control": "no-cache"
|
|
440
|
+
});
|
|
441
|
+
res.end(JSON.stringify({
|
|
442
|
+
locale,
|
|
443
|
+
translations: result.translations,
|
|
444
|
+
errors: result.errors
|
|
445
|
+
}));
|
|
446
|
+
} finally {
|
|
447
|
+
this.endTranslationActivity();
|
|
448
|
+
}
|
|
449
|
+
} catch (error) {
|
|
450
|
+
this.logger.error(`Error getting batch translations for ${locale}:`, error);
|
|
451
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
452
|
+
res.end(JSON.stringify({
|
|
453
|
+
error: "Translation generation failed",
|
|
454
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
455
|
+
}));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Handle request for full translation dictionary
|
|
460
|
+
*/
|
|
461
|
+
async handleDictionaryRequest(locale, res) {
|
|
462
|
+
try {
|
|
463
|
+
const parsedLocale = parseLocaleOrThrow(locale);
|
|
464
|
+
if (!this.translationService) throw new Error("Translation service not initialized");
|
|
465
|
+
await this.reloadMetadata();
|
|
466
|
+
if (!this.metadata) throw new Error("Failed to load metadata");
|
|
467
|
+
this.logger.info(`🌐 Requesting full dictionary for ${locale}`);
|
|
468
|
+
const allHashes = Object.keys(this.metadata.entries);
|
|
469
|
+
const result = await this.translationService.translate(parsedLocale, this.metadata, allHashes);
|
|
470
|
+
res.writeHead(200, {
|
|
471
|
+
"Content-Type": "application/json",
|
|
472
|
+
"Cache-Control": "public, max-age=3600"
|
|
473
|
+
});
|
|
474
|
+
res.end(JSON.stringify({
|
|
475
|
+
locale,
|
|
476
|
+
translations: result.translations,
|
|
477
|
+
errors: result.errors
|
|
478
|
+
}));
|
|
479
|
+
} catch (error) {
|
|
480
|
+
this.logger.error(`Error getting dictionary for ${locale}:`, error);
|
|
481
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
482
|
+
res.end(JSON.stringify({
|
|
483
|
+
error: "Translation generation failed",
|
|
484
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
485
|
+
}));
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
function stableStringify(value) {
|
|
490
|
+
const normalize = (v) => {
|
|
491
|
+
if (v === void 0) return void 0;
|
|
492
|
+
if (typeof v === "function") return void 0;
|
|
493
|
+
if (v === null) return null;
|
|
494
|
+
if (Array.isArray(v)) return v.map(normalize).filter((x) => x !== void 0);
|
|
495
|
+
if (typeof v === "object") {
|
|
496
|
+
const out = {};
|
|
497
|
+
for (const key of Object.keys(v).sort()) {
|
|
498
|
+
const next = normalize(v[key]);
|
|
499
|
+
if (next !== void 0) out[key] = next;
|
|
500
|
+
}
|
|
501
|
+
return out;
|
|
502
|
+
}
|
|
503
|
+
return v;
|
|
504
|
+
};
|
|
505
|
+
return JSON.stringify(normalize(value));
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Generate a stable hash of a config object
|
|
509
|
+
* Filters out functions and non-serializable values
|
|
510
|
+
* Sorts keys for stability
|
|
511
|
+
*/
|
|
512
|
+
function hashConfig(config) {
|
|
513
|
+
const serialized = stableStringify(config);
|
|
514
|
+
return crypto.createHash("md5").update(serialized).digest("hex").slice(0, 12);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Create and start a translation server
|
|
518
|
+
*/
|
|
519
|
+
async function startTranslationServer(options) {
|
|
520
|
+
const server = new TranslationServer(options);
|
|
521
|
+
await server.start();
|
|
522
|
+
return server;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Create a translation server and start it or reuse an existing one on the preferred port
|
|
526
|
+
*
|
|
527
|
+
* Since we have little control over the dev server start in next, we can start the translation server only in the loader,
|
|
528
|
+
* and loaders could be started from multiple processes (it seems) or similar we need a way to avoid starting multiple servers.
|
|
529
|
+
* This one will try to start a server on the preferred port (which seems to be an atomic operation), and if it fails,
|
|
530
|
+
* it checks if the server already started is ours and returns its url.
|
|
531
|
+
*
|
|
532
|
+
* @returns Object containing the server instance and its URL
|
|
533
|
+
*/
|
|
534
|
+
async function startOrGetTranslationServer(options) {
|
|
535
|
+
const server = new TranslationServer(options);
|
|
536
|
+
return {
|
|
537
|
+
server,
|
|
538
|
+
url: await server.startOrGetUrl()
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
//#endregion
|
|
543
|
+
export { startOrGetTranslationServer, startTranslationServer };
|
|
544
|
+
//# sourceMappingURL=translation-server.mjs.map
|
|
@@ -0,0 +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 {\n createCache,\n createTranslator,\n TranslationService,\n} from \"../translators\";\nimport {\n createEmptyMetadata,\n getMetadataPath,\n loadMetadata,\n} 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 /**\n * Starting port to try (will find next available if taken)\n * @default 3456\n */\n startPort?: number;\n\n /**\n * Configuration for translation generation\n */\n config: TranslationMiddlewareConfig;\n\n /**\n * Callback when server is ready\n */\n onReady?: (port: number) => void;\n\n /**\n * Callback on error\n */\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 config: TranslationMiddlewareConfig;\n private configHash: string;\n private startPort: number;\n private onReadyCallback?: (port: number) => void;\n private onErrorCallback?: (error: Error) => void;\n private translationService: TranslationService | null = null;\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\n constructor(options: TranslationServerOptions) {\n this.config = options.config;\n this.configHash = hashConfig(options.config);\n this.startPort = options.startPort || 60000;\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 translator = createTranslator(this.config, this.logger);\n const cache = createCache(this.config);\n\n this.translationService = new TranslationService(\n translator,\n cache,\n {\n sourceLocale: this.config.sourceLocale,\n pluralization: this.config.pluralization,\n },\n this.logger,\n );\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 port 60000. 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 instance already has a server running, return its URL\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.entries).length} entries`,\n );\n } catch (error) {\n this.logger.warn(\"Failed to reload metadata:\", error);\n this.metadata = createEmptyMetadata();\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.entries);\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 // Check if response is valid and has the expected structure\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\n if (!this.translationService) {\n throw new Error(\"Translation service not initialized\");\n }\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 if (!this.translationService) {\n throw new Error(\"Translation service not initialized\");\n }\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.entries);\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\n/**\n * Create and start a translation server\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 loader,\n * and loaders could be started from multiple processes (it seems) or similar 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 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":";;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAa,oBAAb,MAA+B;CAC7B,AAAQ,SAA6B;CACrC,AAAQ,MAA0B;CAClC,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ,qBAAgD;CACxD,AAAQ,WAAkC;C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,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;;;;;AAM/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"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/translation-server/ws-events.ts
|
|
3
|
+
/**
|
|
4
|
+
* Helper to create events with timestamp
|
|
5
|
+
*/
|
|
6
|
+
function createEvent(type, event) {
|
|
7
|
+
return {
|
|
8
|
+
...event,
|
|
9
|
+
timestamp: Date.now(),
|
|
10
|
+
type
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
exports.createEvent = createEvent;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/translation-server/ws-events.ts
|
|
2
|
+
/**
|
|
3
|
+
* Helper to create events with timestamp
|
|
4
|
+
*/
|
|
5
|
+
function createEvent(type, event) {
|
|
6
|
+
return {
|
|
7
|
+
...event,
|
|
8
|
+
timestamp: Date.now(),
|
|
9
|
+
type
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
//#endregion
|
|
14
|
+
export { createEvent };
|
|
15
|
+
//# sourceMappingURL=ws-events.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-events.mjs","names":[],"sources":["../../src/translation-server/ws-events.ts"],"sourcesContent":["/**\n * WebSocket event types for real-time translation progress\n * Sent from translation server to dev widget clients\n */\n\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\n/**\n * Base event structure\n */\ninterface BaseEvent {\n type: string;\n timestamp: number;\n}\n\n/**\n * Server connection established\n */\nexport interface ConnectedEvent extends BaseEvent {\n type: \"connected\";\n serverUrl: string;\n}\n\n/**\n * Single translation started\n */\nexport interface TranslationStartEvent extends BaseEvent {\n type: \"translation:start\";\n hash: string;\n locale: LocaleCode;\n sourceText: string;\n}\n\n/**\n * Single translation completed successfully\n */\nexport interface TranslationCompleteEvent extends BaseEvent {\n type: \"translation:complete\";\n hash: string;\n locale: LocaleCode;\n translatedText: string;\n duration: number; // ms\n}\n\n/**\n * Single translation failed\n */\nexport interface TranslationErrorEvent extends BaseEvent {\n type: \"translation:error\";\n hash: string;\n locale: LocaleCode;\n error: string;\n}\n\n/**\n * Batch translation started\n */\nexport interface BatchStartEvent extends BaseEvent {\n type: \"batch:start\";\n locale: LocaleCode;\n total: number;\n hashes: string[];\n}\n\n/**\n * Batch translation progress update\n */\nexport interface BatchProgressEvent extends BaseEvent {\n type: \"batch:progress\";\n locale: LocaleCode;\n completed: number;\n total: number;\n percent: number;\n}\n\n/**\n * Batch translation completed\n */\nexport interface BatchCompleteEvent extends BaseEvent {\n type: \"batch:complete\";\n locale: LocaleCode;\n total: number;\n successful: number;\n failed: number;\n duration: number; // ms\n}\n\n/**\n * Metadata updated (new translatable text discovered)\n */\nexport interface MetadataUpdateEvent extends BaseEvent {\n type: \"metadata:update\";\n newEntries: number;\n totalEntries: number;\n}\n\n/**\n * Cache updated\n */\nexport interface CacheUpdateEvent extends BaseEvent {\n type: \"cache:update\";\n locale: LocaleCode;\n entriesCount: number;\n}\n\n/**\n * Server is now busy processing translations\n */\nexport interface ServerBusyEvent extends BaseEvent {\n type: \"server:busy\";\n activeTranslations: number;\n}\n\n/**\n * Server is now idle (no active translations)\n */\nexport interface ServerIdleEvent extends BaseEvent {\n type: \"server:idle\";\n}\n\n/**\n * Union type of all possible events\n */\nexport type TranslationServerEvent =\n | ConnectedEvent\n | TranslationStartEvent\n | TranslationCompleteEvent\n | TranslationErrorEvent\n | BatchStartEvent\n | BatchProgressEvent\n | BatchCompleteEvent\n | MetadataUpdateEvent\n | CacheUpdateEvent\n | ServerBusyEvent\n | ServerIdleEvent;\n\ntype TranslationServerEventByType = {\n [T in TranslationServerEvent as T[\"type\"]]: T;\n};\n\n/**\n * Helper to create events with timestamp\n */\nexport function createEvent<T extends keyof TranslationServerEventByType>(\n type: T,\n event: Omit<TranslationServerEventByType[T], \"timestamp\" | \"type\">,\n): TranslationServerEventByType[T] {\n return {\n ...event,\n timestamp: Date.now(),\n type,\n } as TranslationServerEventByType[T];\n}\n"],"mappings":";;;;AA+IA,SAAgB,YACd,MACA,OACiC;AACjC,QAAO;EACL,GAAG;EACH,WAAW,KAAK,KAAK;EACrB;EACD"}
|