@lingo.dev/compiler 0.1.2 → 0.1.3
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/build/metadata/manager.mjs +12 -12
- package/build/metadata/manager.mjs.map +1 -1
- package/build/plugin/build-translator.cjs +3 -3
- package/build/plugin/build-translator.mjs +6 -6
- package/build/plugin/build-translator.mjs.map +1 -1
- package/build/plugin/next.cjs +3 -3
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +3 -3
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +3 -2
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +3 -2
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/translation-server/translation-server.cjs +7 -17
- package/build/translation-server/translation-server.mjs +7 -17
- package/build/translation-server/translation-server.mjs.map +1 -1
- package/build/translators/cache-factory.mjs.map +1 -1
- package/build/translators/lingo/model-factory.cjs +5 -10
- package/build/translators/lingo/model-factory.mjs +5 -10
- package/build/translators/lingo/model-factory.mjs.map +1 -1
- package/build/translators/lingo/provider-details.cjs +69 -0
- package/build/translators/lingo/provider-details.mjs +69 -0
- package/build/translators/lingo/provider-details.mjs.map +1 -0
- package/build/translators/lingo/{service.cjs → translator.cjs} +11 -13
- package/build/translators/lingo/{service.mjs → translator.mjs} +12 -14
- package/build/translators/lingo/translator.mjs.map +1 -0
- package/build/translators/local-cache.mjs +8 -8
- package/build/translators/local-cache.mjs.map +1 -1
- package/build/translators/memory-cache.cjs +47 -0
- package/build/translators/memory-cache.mjs +47 -0
- package/build/translators/memory-cache.mjs.map +1 -0
- package/build/translators/pluralization/service.cjs +19 -44
- package/build/translators/pluralization/service.mjs +19 -44
- package/build/translators/pluralization/service.mjs.map +1 -1
- package/build/translators/pseudotranslator/index.cjs +2 -10
- package/build/translators/pseudotranslator/index.mjs +2 -10
- package/build/translators/pseudotranslator/index.mjs.map +1 -1
- package/build/translators/translation-service.cjs +55 -57
- package/build/translators/translation-service.mjs +55 -57
- package/build/translators/translation-service.mjs.map +1 -1
- package/package.json +7 -7
- package/build/translators/lingo/service.mjs.map +0 -1
- package/build/translators/translator-factory.cjs +0 -49
- package/build/translators/translator-factory.mjs +0 -50
- package/build/translators/translator-factory.mjs.map +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { logger } from "../utils/logger.mjs";
|
|
2
2
|
import { DEFAULT_TIMEOUTS, withTimeout } from "../utils/timeout.mjs";
|
|
3
3
|
import { getLingoDir } from "../utils/path-helpers.mjs";
|
|
4
|
-
import
|
|
4
|
+
import fs from "fs/promises";
|
|
5
5
|
import path from "path";
|
|
6
|
-
import fs from "fs";
|
|
6
|
+
import fs$1 from "fs";
|
|
7
7
|
import lockfile from "proper-lockfile";
|
|
8
8
|
|
|
9
9
|
//#region src/metadata/manager.ts
|
|
@@ -22,7 +22,7 @@ function loadMetadata(path$1) {
|
|
|
22
22
|
function cleanupExistingMetadata(metadataFilePath) {
|
|
23
23
|
logger.debug(`Attempting to cleanup metadata file: ${metadataFilePath}`);
|
|
24
24
|
try {
|
|
25
|
-
fs.unlinkSync(metadataFilePath);
|
|
25
|
+
fs$1.unlinkSync(metadataFilePath);
|
|
26
26
|
logger.info(`🧹 Cleaned up build metadata file: ${metadataFilePath}`);
|
|
27
27
|
} catch (error) {
|
|
28
28
|
if (error.code === "ENOENT") logger.debug(`Metadata file already deleted or doesn't exist: ${metadataFilePath}`);
|
|
@@ -50,7 +50,7 @@ var MetadataManager = class {
|
|
|
50
50
|
*/
|
|
51
51
|
async loadMetadata() {
|
|
52
52
|
try {
|
|
53
|
-
const content = await withTimeout(
|
|
53
|
+
const content = await withTimeout(fs.readFile(this.filePath, "utf-8"), DEFAULT_TIMEOUTS.METADATA, "Load metadata");
|
|
54
54
|
return JSON.parse(content);
|
|
55
55
|
} catch (error) {
|
|
56
56
|
if (error.code === "ENOENT") return createEmptyMetadata();
|
|
@@ -62,7 +62,7 @@ var MetadataManager = class {
|
|
|
62
62
|
* Times out after 15 seconds to prevent indefinite hangs
|
|
63
63
|
*/
|
|
64
64
|
async saveMetadata(metadata) {
|
|
65
|
-
await withTimeout(
|
|
65
|
+
await withTimeout(fs.mkdir(path.dirname(this.filePath), { recursive: true }), DEFAULT_TIMEOUTS.FILE_IO, "Create metadata directory");
|
|
66
66
|
metadata.stats = {
|
|
67
67
|
totalEntries: Object.keys(metadata.entries).length,
|
|
68
68
|
lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -71,17 +71,17 @@ var MetadataManager = class {
|
|
|
71
71
|
const base = path.basename(this.filePath);
|
|
72
72
|
const tmpPath = path.join(dir, `.${base}.tmp-${process.pid}-${Date.now()}`);
|
|
73
73
|
const json = JSON.stringify(metadata, null, 2);
|
|
74
|
-
await withTimeout(
|
|
74
|
+
await withTimeout(fs.writeFile(tmpPath, json, "utf-8"), DEFAULT_TIMEOUTS.METADATA, "Save metadata (tmp write)");
|
|
75
75
|
try {
|
|
76
|
-
await withTimeout(
|
|
76
|
+
await withTimeout(fs.rename(tmpPath, this.filePath), DEFAULT_TIMEOUTS.METADATA, "Save metadata (atomic rename)");
|
|
77
77
|
} catch (error) {
|
|
78
78
|
if (error && typeof error === "object" && "code" in error && error.code === "EPERM") {
|
|
79
|
-
await withTimeout(
|
|
79
|
+
await withTimeout(fs.writeFile(this.filePath, json, "utf-8"), DEFAULT_TIMEOUTS.METADATA, "Save metadata (EPERM fallback direct write)");
|
|
80
80
|
return;
|
|
81
81
|
}
|
|
82
82
|
throw error;
|
|
83
83
|
} finally {
|
|
84
|
-
await
|
|
84
|
+
await fs.unlink(tmpPath).catch(() => {});
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
@@ -93,11 +93,11 @@ var MetadataManager = class {
|
|
|
93
93
|
*/
|
|
94
94
|
async saveMetadataWithEntries(entries) {
|
|
95
95
|
const lockDir = path.dirname(this.filePath);
|
|
96
|
-
await
|
|
96
|
+
await fs.mkdir(lockDir, { recursive: true });
|
|
97
97
|
try {
|
|
98
|
-
await
|
|
98
|
+
await fs.access(this.filePath);
|
|
99
99
|
} catch {
|
|
100
|
-
await
|
|
100
|
+
await fs.writeFile(this.filePath, JSON.stringify(createEmptyMetadata(), null, 2), "utf-8");
|
|
101
101
|
}
|
|
102
102
|
const release = await lockfile.lock(this.filePath, {
|
|
103
103
|
retries: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.mjs","names":["path","error: any","filePath: string"],"sources":["../../src/metadata/manager.ts"],"sourcesContent":["import fsPromises from \"fs/promises\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport type { MetadataSchema, PathConfig, TranslationEntry } from \"../types\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../utils/timeout\";\nimport { getLingoDir } from \"../utils/path-helpers\";\nimport { logger } from \"../utils/logger\";\n\nexport function createEmptyMetadata(): MetadataSchema {\n return {\n entries: {},\n stats: {\n totalEntries: 0,\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\nexport function loadMetadata(path: string) {\n return new MetadataManager(path).loadMetadata();\n}\n\nexport function cleanupExistingMetadata(metadataFilePath: string) {\n // General cleanup. Delete metadata and stop the server if any was started.\n logger.debug(`Attempting to cleanup metadata file: ${metadataFilePath}`);\n\n try {\n fs.unlinkSync(metadataFilePath);\n logger.info(`🧹 Cleaned up build metadata file: ${metadataFilePath}`);\n } catch (error: any) {\n // Ignore if file doesn't exist\n if (error.code === \"ENOENT\") {\n logger.debug(\n `Metadata file already deleted or doesn't exist: ${metadataFilePath}`,\n );\n } else {\n logger.warn(`Failed to cleanup metadata file: ${error.message}`);\n }\n }\n}\n\n/**\n * Get the absolute path to the metadata file\n *\n * @param config - Config with sourceRoot, lingoDir, and environment\n * @returns Absolute path to metadata file\n */\nexport function getMetadataPath(config: PathConfig): string {\n const filename =\n // Similar to next keeping dev build separate, let's keep the build metadata clean of any dev mode additions\n config.environment === \"development\"\n ? \"metadata-dev.json\"\n : \"metadata-build.json\";\n return path.join(getLingoDir(config), filename);\n}\n\nexport class MetadataManager {\n constructor(private readonly filePath: string) {}\n\n /**\n * Load metadata from disk\n * Creates empty metadata if file doesn't exist\n * Times out after 15 seconds to prevent indefinite hangs\n */\n async loadMetadata(): Promise<MetadataSchema> {\n try {\n const content = await withTimeout(\n fsPromises.readFile(this.filePath, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Load metadata\",\n );\n return JSON.parse(content) as MetadataSchema;\n } catch (error: any) {\n if (error.code === \"ENOENT\") {\n // File doesn't exist, create new metadata\n return createEmptyMetadata();\n }\n throw error;\n }\n }\n\n /**\n * Save metadata to disk\n * Times out after 15 seconds to prevent indefinite hangs\n */\n private async saveMetadata(metadata: MetadataSchema): Promise<void> {\n await withTimeout(\n fsPromises.mkdir(path.dirname(this.filePath), { recursive: true }),\n DEFAULT_TIMEOUTS.FILE_IO,\n \"Create metadata directory\",\n );\n\n metadata.stats = {\n totalEntries: Object.keys(metadata.entries).length,\n lastUpdated: new Date().toISOString(),\n };\n\n // Per LLM writing to a file is not an atomic operation while rename is, so nobody should get partial content.\n // Sounds reasonable.\n const dir = path.dirname(this.filePath);\n const base = path.basename(this.filePath);\n\n // Keep temp file in the same directory to maximize chance that rename is atomic\n const tmpPath = path.join(dir, `.${base}.tmp-${process.pid}-${Date.now()}`);\n\n const json = JSON.stringify(metadata, null, 2);\n\n await withTimeout(\n fsPromises.writeFile(tmpPath, json, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (tmp write)\",\n );\n\n try {\n // TODO (AleksandrSl 14/12/2025): LLM says that we may want to remove older file first for windows, but it seems lo work fine as is.\n await withTimeout(\n fsPromises.rename(tmpPath, this.filePath),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (atomic rename)\",\n );\n } catch (error) {\n // On Windows, rename() can fail with EPERM if something briefly holds the file.\n // As a fallback, try writing directly to the destination (not atomic).\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EPERM\"\n ) {\n await withTimeout(\n fsPromises.writeFile(this.filePath, json, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (EPERM fallback direct write)\",\n );\n return;\n }\n throw error;\n } finally {\n // Best-effort cleanup if rename failed for some reason\n await fsPromises.unlink(tmpPath).catch(() => {});\n }\n }\n\n /**\n * Thread-safe save operation that atomically updates metadata with new entries\n * Uses file locking to prevent concurrent write corruption\n *\n * @param entries - Translation entries to add/update\n * @returns The updated metadata schema\n */\n async saveMetadataWithEntries(\n entries: TranslationEntry[],\n ): Promise<MetadataSchema> {\n const lockDir = path.dirname(this.filePath);\n\n await fsPromises.mkdir(lockDir, { recursive: true });\n\n try {\n await fsPromises.access(this.filePath);\n } catch {\n await fsPromises.writeFile(\n this.filePath,\n JSON.stringify(createEmptyMetadata(), null, 2),\n \"utf-8\",\n );\n }\n\n const release = await lockfile.lock(this.filePath, {\n retries: {\n retries: 10,\n minTimeout: 50,\n maxTimeout: 1000,\n },\n stale: 2000,\n });\n\n try {\n // Re-load metadata inside lock to get latest state\n const currentMetadata = await this.loadMetadata();\n for (const entry of entries) {\n currentMetadata.entries[entry.hash] = entry;\n }\n await this.saveMetadata(currentMetadata);\n return currentMetadata;\n } finally {\n await release();\n }\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,sBAAsC;AACpD,QAAO;EACL,SAAS,EAAE;EACX,OAAO;GACL,cAAc;GACd,8BAAa,IAAI,MAAM,EAAC,aAAa;GACtC;EACF;;AAGH,SAAgB,aAAa,QAAc;AACzC,QAAO,IAAI,gBAAgBA,OAAK,CAAC,cAAc;;AAGjD,SAAgB,wBAAwB,kBAA0B;AAEhE,QAAO,MAAM,wCAAwC,mBAAmB;AAExE,KAAI;AACF,
|
|
1
|
+
{"version":3,"file":"manager.mjs","names":["path","error: any","filePath: string","fsPromises"],"sources":["../../src/metadata/manager.ts"],"sourcesContent":["import fsPromises from \"fs/promises\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport type { MetadataSchema, PathConfig, TranslationEntry } from \"../types\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../utils/timeout\";\nimport { getLingoDir } from \"../utils/path-helpers\";\nimport { logger } from \"../utils/logger\";\n\nexport function createEmptyMetadata(): MetadataSchema {\n return {\n entries: {},\n stats: {\n totalEntries: 0,\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\nexport function loadMetadata(path: string) {\n return new MetadataManager(path).loadMetadata();\n}\n\nexport function cleanupExistingMetadata(metadataFilePath: string) {\n // General cleanup. Delete metadata and stop the server if any was started.\n logger.debug(`Attempting to cleanup metadata file: ${metadataFilePath}`);\n\n try {\n fs.unlinkSync(metadataFilePath);\n logger.info(`🧹 Cleaned up build metadata file: ${metadataFilePath}`);\n } catch (error: any) {\n // Ignore if file doesn't exist\n if (error.code === \"ENOENT\") {\n logger.debug(\n `Metadata file already deleted or doesn't exist: ${metadataFilePath}`,\n );\n } else {\n logger.warn(`Failed to cleanup metadata file: ${error.message}`);\n }\n }\n}\n\n/**\n * Get the absolute path to the metadata file\n *\n * @param config - Config with sourceRoot, lingoDir, and environment\n * @returns Absolute path to metadata file\n */\nexport function getMetadataPath(config: PathConfig): string {\n const filename =\n // Similar to next keeping dev build separate, let's keep the build metadata clean of any dev mode additions\n config.environment === \"development\"\n ? \"metadata-dev.json\"\n : \"metadata-build.json\";\n return path.join(getLingoDir(config), filename);\n}\n\nexport class MetadataManager {\n constructor(private readonly filePath: string) {}\n\n /**\n * Load metadata from disk\n * Creates empty metadata if file doesn't exist\n * Times out after 15 seconds to prevent indefinite hangs\n */\n async loadMetadata(): Promise<MetadataSchema> {\n try {\n const content = await withTimeout(\n fsPromises.readFile(this.filePath, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Load metadata\",\n );\n return JSON.parse(content) as MetadataSchema;\n } catch (error: any) {\n if (error.code === \"ENOENT\") {\n // File doesn't exist, create new metadata\n return createEmptyMetadata();\n }\n throw error;\n }\n }\n\n /**\n * Save metadata to disk\n * Times out after 15 seconds to prevent indefinite hangs\n */\n private async saveMetadata(metadata: MetadataSchema): Promise<void> {\n await withTimeout(\n fsPromises.mkdir(path.dirname(this.filePath), { recursive: true }),\n DEFAULT_TIMEOUTS.FILE_IO,\n \"Create metadata directory\",\n );\n\n metadata.stats = {\n totalEntries: Object.keys(metadata.entries).length,\n lastUpdated: new Date().toISOString(),\n };\n\n // Per LLM writing to a file is not an atomic operation while rename is, so nobody should get partial content.\n // Sounds reasonable.\n const dir = path.dirname(this.filePath);\n const base = path.basename(this.filePath);\n\n // Keep temp file in the same directory to maximize chance that rename is atomic\n const tmpPath = path.join(dir, `.${base}.tmp-${process.pid}-${Date.now()}`);\n\n const json = JSON.stringify(metadata, null, 2);\n\n await withTimeout(\n fsPromises.writeFile(tmpPath, json, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (tmp write)\",\n );\n\n try {\n // TODO (AleksandrSl 14/12/2025): LLM says that we may want to remove older file first for windows, but it seems lo work fine as is.\n await withTimeout(\n fsPromises.rename(tmpPath, this.filePath),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (atomic rename)\",\n );\n } catch (error) {\n // On Windows, rename() can fail with EPERM if something briefly holds the file.\n // As a fallback, try writing directly to the destination (not atomic).\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EPERM\"\n ) {\n await withTimeout(\n fsPromises.writeFile(this.filePath, json, \"utf-8\"),\n DEFAULT_TIMEOUTS.METADATA,\n \"Save metadata (EPERM fallback direct write)\",\n );\n return;\n }\n throw error;\n } finally {\n // Best-effort cleanup if rename failed for some reason\n await fsPromises.unlink(tmpPath).catch(() => {});\n }\n }\n\n /**\n * Thread-safe save operation that atomically updates metadata with new entries\n * Uses file locking to prevent concurrent write corruption\n *\n * @param entries - Translation entries to add/update\n * @returns The updated metadata schema\n */\n async saveMetadataWithEntries(\n entries: TranslationEntry[],\n ): Promise<MetadataSchema> {\n const lockDir = path.dirname(this.filePath);\n\n await fsPromises.mkdir(lockDir, { recursive: true });\n\n try {\n await fsPromises.access(this.filePath);\n } catch {\n await fsPromises.writeFile(\n this.filePath,\n JSON.stringify(createEmptyMetadata(), null, 2),\n \"utf-8\",\n );\n }\n\n const release = await lockfile.lock(this.filePath, {\n retries: {\n retries: 10,\n minTimeout: 50,\n maxTimeout: 1000,\n },\n stale: 2000,\n });\n\n try {\n // Re-load metadata inside lock to get latest state\n const currentMetadata = await this.loadMetadata();\n for (const entry of entries) {\n currentMetadata.entries[entry.hash] = entry;\n }\n await this.saveMetadata(currentMetadata);\n return currentMetadata;\n } finally {\n await release();\n }\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,sBAAsC;AACpD,QAAO;EACL,SAAS,EAAE;EACX,OAAO;GACL,cAAc;GACd,8BAAa,IAAI,MAAM,EAAC,aAAa;GACtC;EACF;;AAGH,SAAgB,aAAa,QAAc;AACzC,QAAO,IAAI,gBAAgBA,OAAK,CAAC,cAAc;;AAGjD,SAAgB,wBAAwB,kBAA0B;AAEhE,QAAO,MAAM,wCAAwC,mBAAmB;AAExE,KAAI;AACF,OAAG,WAAW,iBAAiB;AAC/B,SAAO,KAAK,sCAAsC,mBAAmB;UAC9DC,OAAY;AAEnB,MAAI,MAAM,SAAS,SACjB,QAAO,MACL,mDAAmD,mBACpD;MAED,QAAO,KAAK,oCAAoC,MAAM,UAAU;;;;;;;;;AAWtE,SAAgB,gBAAgB,QAA4B;CAC1D,MAAM,WAEJ,OAAO,gBAAgB,gBACnB,sBACA;AACN,QAAO,KAAK,KAAK,YAAY,OAAO,EAAE,SAAS;;AAGjD,IAAa,kBAAb,MAA6B;CAC3B,YAAY,AAAiBC,UAAkB;EAAlB;;;;;;;CAO7B,MAAM,eAAwC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GAAW,OAAO,KAAK,SAAS;UAChC;AACN,SAAMA,GAAW,UACf,KAAK,UACL,KAAK,UAAU,qBAAqB,EAAE,MAAM,EAAE,EAC9C,QACD;;EAGH,MAAM,UAAU,MAAM,SAAS,KAAK,KAAK,UAAU;GACjD,SAAS;IACP,SAAS;IACT,YAAY;IACZ,YAAY;IACb;GACD,OAAO;GACR,CAAC;AAEF,MAAI;GAEF,MAAM,kBAAkB,MAAM,KAAK,cAAc;AACjD,QAAK,MAAM,SAAS,QAClB,iBAAgB,QAAQ,MAAM,QAAQ;AAExC,SAAM,KAAK,aAAa,gBAAgB;AACxC,UAAO;YACC;AACR,SAAM,SAAS"}
|
|
@@ -2,6 +2,7 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
|
2
2
|
const require_logger = require('../utils/logger.cjs');
|
|
3
3
|
const require_api = require('../translators/api.cjs');
|
|
4
4
|
const require_cache_factory = require('../translators/cache-factory.cjs');
|
|
5
|
+
const require_translation_service = require('../translators/translation-service.cjs');
|
|
5
6
|
const require_manager = require('../metadata/manager.cjs');
|
|
6
7
|
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
7
8
|
let fs_promises = require("fs/promises");
|
|
@@ -27,7 +28,6 @@ async function processBuildTranslations(options) {
|
|
|
27
28
|
const { config, publicOutputPath, metadataFilePath } = options;
|
|
28
29
|
const buildMode = process.env.LINGO_BUILD_MODE || config.buildMode;
|
|
29
30
|
require_logger.logger.info(`🌍 Build mode: ${buildMode}`);
|
|
30
|
-
if (metadataFilePath) require_logger.logger.info(`📋 Using build metadata file: ${metadataFilePath}`);
|
|
31
31
|
const metadata = await require_manager.loadMetadata(metadataFilePath);
|
|
32
32
|
if (!metadata || Object.keys(metadata.entries).length === 0) {
|
|
33
33
|
require_logger.logger.info("No translations to process (metadata is empty)");
|
|
@@ -53,7 +53,7 @@ async function processBuildTranslations(options) {
|
|
|
53
53
|
let translationServer;
|
|
54
54
|
try {
|
|
55
55
|
translationServer = await require_translation_server.startTranslationServer({
|
|
56
|
-
|
|
56
|
+
translationService: new require_translation_service.TranslationService(config, require_logger.logger),
|
|
57
57
|
onError: (err) => {
|
|
58
58
|
require_logger.logger.error("Translation server error:", err);
|
|
59
59
|
},
|
|
@@ -93,7 +93,7 @@ async function processBuildTranslations(options) {
|
|
|
93
93
|
stats
|
|
94
94
|
};
|
|
95
95
|
} catch (error) {
|
|
96
|
-
require_logger.logger.error("❌ Translation generation failed
|
|
96
|
+
require_logger.logger.error("❌ Translation generation failed:\n", error instanceof Error ? error.message : error);
|
|
97
97
|
process.exit(1);
|
|
98
98
|
} finally {
|
|
99
99
|
if (translationServer) {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { logger } from "../utils/logger.mjs";
|
|
2
2
|
import { dictionaryFrom } from "../translators/api.mjs";
|
|
3
3
|
import { createCache } from "../translators/cache-factory.mjs";
|
|
4
|
+
import { TranslationService } from "../translators/translation-service.mjs";
|
|
4
5
|
import { loadMetadata } from "../metadata/manager.mjs";
|
|
5
6
|
import { startTranslationServer } from "../translation-server/translation-server.mjs";
|
|
6
|
-
import
|
|
7
|
+
import fs from "fs/promises";
|
|
7
8
|
import path from "path";
|
|
8
9
|
|
|
9
10
|
//#region src/plugin/build-translator.ts
|
|
@@ -24,7 +25,6 @@ async function processBuildTranslations(options) {
|
|
|
24
25
|
const { config, publicOutputPath, metadataFilePath } = options;
|
|
25
26
|
const buildMode = process.env.LINGO_BUILD_MODE || config.buildMode;
|
|
26
27
|
logger.info(`🌍 Build mode: ${buildMode}`);
|
|
27
|
-
if (metadataFilePath) logger.info(`📋 Using build metadata file: ${metadataFilePath}`);
|
|
28
28
|
const metadata = await loadMetadata(metadataFilePath);
|
|
29
29
|
if (!metadata || Object.keys(metadata.entries).length === 0) {
|
|
30
30
|
logger.info("No translations to process (metadata is empty)");
|
|
@@ -50,7 +50,7 @@ async function processBuildTranslations(options) {
|
|
|
50
50
|
let translationServer;
|
|
51
51
|
try {
|
|
52
52
|
translationServer = await startTranslationServer({
|
|
53
|
-
|
|
53
|
+
translationService: new TranslationService(config, logger),
|
|
54
54
|
onError: (err) => {
|
|
55
55
|
logger.error("Translation server error:", err);
|
|
56
56
|
},
|
|
@@ -90,7 +90,7 @@ async function processBuildTranslations(options) {
|
|
|
90
90
|
stats
|
|
91
91
|
};
|
|
92
92
|
} catch (error) {
|
|
93
|
-
logger.error("❌ Translation generation failed
|
|
93
|
+
logger.error("❌ Translation generation failed:\n", error instanceof Error ? error.message : error);
|
|
94
94
|
process.exit(1);
|
|
95
95
|
} finally {
|
|
96
96
|
if (translationServer) {
|
|
@@ -147,7 +147,7 @@ function buildCacheStats(config, metadata) {
|
|
|
147
147
|
}
|
|
148
148
|
async function copyStaticFiles(config, publicOutputPath, metadata, cache) {
|
|
149
149
|
logger.info(`📦 Generating static translation files in ${publicOutputPath}`);
|
|
150
|
-
await
|
|
150
|
+
await fs.mkdir(publicOutputPath, { recursive: true });
|
|
151
151
|
const usedHashes = new Set(Object.keys(metadata.entries));
|
|
152
152
|
logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);
|
|
153
153
|
const allLocales = config.pluralization?.enabled !== false ? [config.sourceLocale, ...config.targetLocales] : config.targetLocales;
|
|
@@ -156,7 +156,7 @@ async function copyStaticFiles(config, publicOutputPath, metadata, cache) {
|
|
|
156
156
|
try {
|
|
157
157
|
const entries = await cache.get(locale, Array.from(usedHashes));
|
|
158
158
|
const outputData = dictionaryFrom(locale, entries);
|
|
159
|
-
await
|
|
159
|
+
await fs.writeFile(publicFilePath, JSON.stringify(outputData, null, 2), "utf-8");
|
|
160
160
|
logger.info(`✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`);
|
|
161
161
|
} catch (error) {
|
|
162
162
|
logger.error(`❌ Failed to generate ${locale}.json:`, error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-translator.mjs","names":["translationServer: TranslationServer | undefined","stats: BuildTranslationResult[\"stats\"]","errors: Array<{ locale: LocaleCode; error: string }>","missingLocales: string[]","incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>","fs"],"sources":["../../src/plugin/build-translator.ts"],"sourcesContent":["/**\n * Build-time translation processor\n *\n * Handles translation generation and validation at build time\n * Supports two modes:\n * - \"translate\": Generate all translations, fail if translation fails\n * - \"cache-only\": Validate cache completeness, fail if incomplete\n */\n// TODO (AleksandrSl 08/12/2025): Add ICU validation for messages? The problem is that we don't know which will be rendered as a simple text\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { LingoConfig, MetadataSchema } from \"../types\";\nimport { logger } from \"../utils/logger\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport { loadMetadata } from \"../metadata/manager\";\nimport { createCache, type TranslationCache } from \"../translators\";\nimport { dictionaryFrom } from \"../translators/api\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\nexport interface BuildTranslationOptions {\n config: LingoConfig;\n publicOutputPath: string;\n metadataFilePath: string;\n}\n\nexport interface BuildTranslationResult {\n /**\n * Whether the build succeeded\n */\n success: boolean;\n\n /**\n * Error message if build failed\n */\n error?: string;\n\n /**\n * Translation statistics per locale\n */\n stats: Record<\n string,\n {\n total: number;\n translated: number;\n failed: number;\n }\n >;\n}\n\n/**\n * Process translations at build time\n *\n * @throws Error if validation or translation fails (causes build to fail)\n */\nexport async function processBuildTranslations(\n options: BuildTranslationOptions,\n): Promise<BuildTranslationResult> {\n const { config, publicOutputPath, metadataFilePath } = options;\n\n // Determine build mode (env var > options > config)\n const buildMode =\n (process.env.LINGO_BUILD_MODE as \"translate\" | \"cache-only\") ||\n config.buildMode;\n\n logger.info(`🌍 Build mode: ${buildMode}`);\n\n if (metadataFilePath) {\n logger.info(`📋 Using build metadata file: ${metadataFilePath}`);\n }\n\n const metadata = await loadMetadata(metadataFilePath);\n\n if (!metadata || Object.keys(metadata.entries).length === 0) {\n logger.info(\"No translations to process (metadata is empty)\");\n return {\n success: true,\n stats: {},\n };\n }\n\n const totalEntries = Object.keys(metadata.entries).length;\n logger.info(`📊 Found ${totalEntries} translatable entries`);\n\n const cache = createCache(config);\n\n // Handle cache-only mode\n if (buildMode === \"cache-only\") {\n logger.info(\"🔍 Validating translation cache...\");\n await validateCache(config, metadata, cache);\n logger.info(\"✅ Cache validation passed\");\n\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n return {\n success: true,\n stats: buildCacheStats(config, metadata),\n };\n }\n\n // Handle translate mode\n logger.info(\"🔄 Generating translations...\");\n let translationServer: TranslationServer | undefined;\n\n try {\n translationServer = await startTranslationServer({\n startPort: config.dev.translationServerStartPort,\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n config,\n });\n\n // When pluralization is enabled, we need to generate the source locale file too\n // because pluralization modifies the sourceText\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n logger.info(\n `Processing translations for ${allLocales.length} locale(s)${needsSourceLocale ? \" (including source locale for pluralization)\" : \"\"}...`,\n );\n\n const stats: BuildTranslationResult[\"stats\"] = {};\n const errors: Array<{ locale: LocaleCode; error: string }> = [];\n\n // Translate all locales in parallel\n const localePromises = allLocales.map(async (locale) => {\n logger.info(`Translating to ${locale}...`);\n\n const result = await translationServer!.translateAll(locale);\n\n stats[locale] = {\n total: totalEntries,\n translated: Object.keys(result.translations).length,\n failed: result.errors.length,\n };\n\n if (result.errors.length > 0) {\n logger.warn(\n `⚠️ ${result.errors.length} translation error(s) for ${locale}`,\n );\n errors.push({\n locale,\n error: `${result.errors.length} translation(s) failed`,\n });\n } else {\n logger.info(`✅ ${locale} completed successfully`);\n }\n });\n\n await Promise.all(localePromises);\n\n // Fail build if any translations failed in translate mode\n if (errors.length > 0) {\n const errorMsg = formatTranslationErrors(errors);\n logger.error(errorMsg);\n process.exit(1);\n }\n\n // Copy cache to public directory if requested\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n logger.info(\"✅ Translation generation completed successfully\");\n\n return {\n success: true,\n stats,\n };\n } catch (error) {\n logger.error(\"❌ Translation generation failed:\", error);\n process.exit(1);\n } finally {\n if (translationServer) {\n await translationServer.stop();\n logger.info(\"✅ Translation server stopped\");\n }\n }\n}\n\n/**\n * Validate that all required translations exist in cache\n * @throws Error if cache is incomplete or missing\n */\nasync function validateCache(\n config: LingoConfig,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n const allHashes = Object.keys(metadata.entries);\n const missingLocales: string[] = [];\n const incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }> = [];\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n try {\n const entries = await cache.get(locale);\n\n if (Object.keys(entries).length === 0) {\n missingLocales.push(locale);\n logger.debug(`Cache file not found or empty for ${locale}`);\n continue;\n }\n\n const missingHashes = allHashes.filter((hash) => !entries[hash]);\n\n if (missingHashes.length > 0) {\n incompleteLocales.push({\n locale,\n missing: missingHashes.length,\n total: allHashes.length,\n });\n\n // Log first few missing hashes for debugging\n logger.debug(\n `Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(\", \")}${\n missingHashes.length > 5 ? \"...\" : \"\"\n }`,\n );\n }\n } catch (error) {\n missingLocales.push(locale);\n logger.debug(`Failed to read cache for ${locale}:`, error);\n }\n }\n\n if (missingLocales.length > 0 || incompleteLocales.length > 0) {\n const errorMsg = formatCacheValidationError(\n missingLocales,\n incompleteLocales,\n );\n logger.error(errorMsg);\n process.exit(1);\n }\n}\n\nfunction buildCacheStats(\n config: LingoConfig,\n metadata: MetadataSchema,\n): BuildTranslationResult[\"stats\"] {\n const totalEntries = Object.keys(metadata.entries).length;\n const stats: BuildTranslationResult[\"stats\"] = {};\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n stats[locale] = {\n total: totalEntries,\n translated: totalEntries, // Assumed complete if validation passed\n failed: 0,\n };\n }\n\n return stats;\n}\n\nasync function copyStaticFiles(\n config: LingoConfig,\n publicOutputPath: string,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n logger.info(`📦 Generating static translation files in ${publicOutputPath}`);\n\n await fs.mkdir(publicOutputPath, { recursive: true });\n\n const usedHashes = new Set(Object.keys(metadata.entries));\n logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n const publicFilePath = path.join(publicOutputPath, `${locale}.json`);\n\n try {\n const entries = await cache.get(locale, Array.from(usedHashes));\n const outputData = dictionaryFrom(locale, entries);\n\n await fs.writeFile(\n publicFilePath,\n JSON.stringify(outputData, null, 2),\n \"utf-8\",\n );\n\n logger.info(\n `✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`,\n );\n } catch (error) {\n logger.error(`❌ Failed to generate ${locale}.json:`, error);\n process.exit(1);\n }\n }\n}\n\nfunction formatCacheValidationError(\n missingLocales: string[],\n incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>,\n): string {\n let msg = \"❌ Cache validation failed in cache-only mode:\\n\\n\";\n\n if (missingLocales.length > 0) {\n msg += ` 📁 Missing cache files:\\n`;\n msg += missingLocales.map((locale) => ` - ${locale}.json`).join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n if (incompleteLocales.length > 0) {\n msg += ` 📊 Incomplete cache:\\n`;\n msg += incompleteLocales\n .map(\n (item) =>\n ` - ${item.locale}: ${item.missing}/${item.total} translations missing`,\n )\n .join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n msg += ` 💡 To fix:\\n`;\n msg += ` 1. Set LINGO_BUILD_MODE=translate to generate translations\\n`;\n msg += ` 2. Commit the generated .lingo/cache/*.json files\\n`;\n msg += ` 3. Ensure translation API keys are available if generating translations`;\n\n return msg;\n}\n\nfunction formatTranslationErrors(\n errors: Array<{ locale: LocaleCode; error: string }>,\n): string {\n let msg = \"❌ Translation generation failed:\\n\\n\";\n\n msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join(\"\\n\");\n\n msg += \"\\n\\n\";\n msg += ` 💡 Translation errors must be resolved in \"translate\" mode.\\n`;\n msg += ` Check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,yBACpB,SACiC;CACjC,MAAM,EAAE,QAAQ,kBAAkB,qBAAqB;CAGvD,MAAM,YACH,QAAQ,IAAI,oBACb,OAAO;AAET,QAAO,KAAK,kBAAkB,YAAY;AAE1C,KAAI,iBACF,QAAO,KAAK,iCAAiC,mBAAmB;CAGlE,MAAM,WAAW,MAAM,aAAa,iBAAiB;AAErD,KAAI,CAAC,YAAY,OAAO,KAAK,SAAS,QAAQ,CAAC,WAAW,GAAG;AAC3D,SAAO,KAAK,iDAAiD;AAC7D,SAAO;GACL,SAAS;GACT,OAAO,EAAE;GACV;;CAGH,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,CAAC;AACnD,QAAO,KAAK,YAAY,aAAa,uBAAuB;CAE5D,MAAM,QAAQ,YAAY,OAAO;AAGjC,KAAI,cAAc,cAAc;AAC9B,SAAO,KAAK,qCAAqC;AACjD,QAAM,cAAc,QAAQ,UAAU,MAAM;AAC5C,SAAO,KAAK,4BAA4B;AAExC,MAAI,iBACF,OAAM,gBAAgB,QAAQ,kBAAkB,UAAU,MAAM;AAGlE,SAAO;GACL,SAAS;GACT,OAAO,gBAAgB,QAAQ,SAAS;GACzC;;AAIH,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AO,OAAO,KAAK,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,QAAQ,CAAC,KAAK,KAAK;AAExE,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
1
|
+
{"version":3,"file":"build-translator.mjs","names":["translationServer: TranslationServer | undefined","stats: BuildTranslationResult[\"stats\"]","errors: Array<{ locale: LocaleCode; error: string }>","missingLocales: string[]","incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>"],"sources":["../../src/plugin/build-translator.ts"],"sourcesContent":["/**\n * Build-time translation processor\n *\n * Handles translation generation and validation at build time\n * Supports two modes:\n * - \"translate\": Generate all translations, fail if translation fails\n * - \"cache-only\": Validate cache completeness, fail if incomplete\n */\n// TODO (AleksandrSl 08/12/2025): Add ICU validation for messages? The problem is that we don't know which will be rendered as a simple text\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { LingoConfig, MetadataSchema } from \"../types\";\nimport { logger } from \"../utils/logger\";\nimport { startTranslationServer, type TranslationServer, } from \"../translation-server\";\nimport { loadMetadata } from \"../metadata/manager\";\nimport { createCache, type TranslationCache, TranslationService, } from \"../translators\";\nimport { dictionaryFrom } from \"../translators/api\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\nexport interface BuildTranslationOptions {\n config: LingoConfig;\n publicOutputPath: string;\n metadataFilePath: string;\n}\n\nexport interface BuildTranslationResult {\n /**\n * Whether the build succeeded\n */\n success: boolean;\n\n /**\n * Error message if build failed\n */\n error?: string;\n\n /**\n * Translation statistics per locale\n */\n stats: Record<\n string,\n {\n total: number;\n translated: number;\n failed: number;\n }\n >;\n}\n\n/**\n * Process translations at build time\n *\n * @throws Error if validation or translation fails (causes build to fail)\n */\nexport async function processBuildTranslations(\n options: BuildTranslationOptions,\n): Promise<BuildTranslationResult> {\n const { config, publicOutputPath, metadataFilePath } = options;\n\n // Determine build mode (env var > options > config)\n const buildMode =\n (process.env.LINGO_BUILD_MODE as \"translate\" | \"cache-only\") ||\n config.buildMode;\n\n logger.info(`🌍 Build mode: ${buildMode}`);\n\n const metadata = await loadMetadata(metadataFilePath);\n\n if (!metadata || Object.keys(metadata.entries).length === 0) {\n logger.info(\"No translations to process (metadata is empty)\");\n return {\n success: true,\n stats: {},\n };\n }\n\n const totalEntries = Object.keys(metadata.entries).length;\n logger.info(`📊 Found ${totalEntries} translatable entries`);\n\n const cache = createCache(config);\n\n // Handle cache-only mode\n if (buildMode === \"cache-only\") {\n logger.info(\"🔍 Validating translation cache...\");\n await validateCache(config, metadata, cache);\n logger.info(\"✅ Cache validation passed\");\n\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n return {\n success: true,\n stats: buildCacheStats(config, metadata),\n };\n }\n\n // Handle translate mode\n logger.info(\"🔄 Generating translations...\");\n let translationServer: TranslationServer | undefined;\n\n try {\n translationServer = await startTranslationServer({\n translationService: new TranslationService(config, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n config,\n });\n\n // When pluralization is enabled, we need to generate the source locale file too\n // because pluralization modifies the sourceText\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n logger.info(\n `Processing translations for ${allLocales.length} locale(s)${needsSourceLocale ? \" (including source locale for pluralization)\" : \"\"}...`,\n );\n\n const stats: BuildTranslationResult[\"stats\"] = {};\n const errors: Array<{ locale: LocaleCode; error: string }> = [];\n\n // Translate all locales in parallel\n const localePromises = allLocales.map(async (locale) => {\n logger.info(`Translating to ${locale}...`);\n\n const result = await translationServer!.translateAll(locale);\n\n stats[locale] = {\n total: totalEntries,\n translated: Object.keys(result.translations).length,\n failed: result.errors.length,\n };\n\n if (result.errors.length > 0) {\n logger.warn(\n `⚠️ ${result.errors.length} translation error(s) for ${locale}`,\n );\n errors.push({\n locale,\n error: `${result.errors.length} translation(s) failed`,\n });\n } else {\n logger.info(`✅ ${locale} completed successfully`);\n }\n });\n\n await Promise.all(localePromises);\n\n // Fail build if any translations failed in translate mode\n if (errors.length > 0) {\n const errorMsg = formatTranslationErrors(errors);\n logger.error(errorMsg);\n process.exit(1);\n }\n\n // Copy cache to public directory if requested\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n logger.info(\"✅ Translation generation completed successfully\");\n\n return {\n success: true,\n stats,\n };\n } catch (error) {\n logger.error(\n \"❌ Translation generation failed:\\n\",\n error instanceof Error ? error.message : error,\n );\n process.exit(1);\n } finally {\n if (translationServer) {\n await translationServer.stop();\n logger.info(\"✅ Translation server stopped\");\n }\n }\n}\n\n/**\n * Validate that all required translations exist in cache\n * @throws Error if cache is incomplete or missing\n */\nasync function validateCache(\n config: LingoConfig,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n const allHashes = Object.keys(metadata.entries);\n const missingLocales: string[] = [];\n const incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }> = [];\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n try {\n const entries = await cache.get(locale);\n\n if (Object.keys(entries).length === 0) {\n missingLocales.push(locale);\n logger.debug(`Cache file not found or empty for ${locale}`);\n continue;\n }\n\n const missingHashes = allHashes.filter((hash) => !entries[hash]);\n\n if (missingHashes.length > 0) {\n incompleteLocales.push({\n locale,\n missing: missingHashes.length,\n total: allHashes.length,\n });\n\n // Log first few missing hashes for debugging\n logger.debug(\n `Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(\", \")}${\n missingHashes.length > 5 ? \"...\" : \"\"\n }`,\n );\n }\n } catch (error) {\n missingLocales.push(locale);\n logger.debug(`Failed to read cache for ${locale}:`, error);\n }\n }\n\n if (missingLocales.length > 0 || incompleteLocales.length > 0) {\n const errorMsg = formatCacheValidationError(\n missingLocales,\n incompleteLocales,\n );\n logger.error(errorMsg);\n process.exit(1);\n }\n}\n\nfunction buildCacheStats(\n config: LingoConfig,\n metadata: MetadataSchema,\n): BuildTranslationResult[\"stats\"] {\n const totalEntries = Object.keys(metadata.entries).length;\n const stats: BuildTranslationResult[\"stats\"] = {};\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n stats[locale] = {\n total: totalEntries,\n translated: totalEntries, // Assumed complete if validation passed\n failed: 0,\n };\n }\n\n return stats;\n}\n\nasync function copyStaticFiles(\n config: LingoConfig,\n publicOutputPath: string,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n logger.info(`📦 Generating static translation files in ${publicOutputPath}`);\n\n await fs.mkdir(publicOutputPath, { recursive: true });\n\n const usedHashes = new Set(Object.keys(metadata.entries));\n logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);\n\n // Include source locale if pluralization is enabled\n const needsSourceLocale = config.pluralization?.enabled !== false;\n const allLocales = needsSourceLocale\n ? [config.sourceLocale, ...config.targetLocales]\n : config.targetLocales;\n\n for (const locale of allLocales) {\n const publicFilePath = path.join(publicOutputPath, `${locale}.json`);\n\n try {\n const entries = await cache.get(locale, Array.from(usedHashes));\n const outputData = dictionaryFrom(locale, entries);\n\n await fs.writeFile(\n publicFilePath,\n JSON.stringify(outputData, null, 2),\n \"utf-8\",\n );\n\n logger.info(\n `✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`,\n );\n } catch (error) {\n logger.error(`❌ Failed to generate ${locale}.json:`, error);\n process.exit(1);\n }\n }\n}\n\nfunction formatCacheValidationError(\n missingLocales: string[],\n incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>,\n): string {\n let msg = \"❌ Cache validation failed in cache-only mode:\\n\\n\";\n\n if (missingLocales.length > 0) {\n msg += ` 📁 Missing cache files:\\n`;\n msg += missingLocales.map((locale) => ` - ${locale}.json`).join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n if (incompleteLocales.length > 0) {\n msg += ` 📊 Incomplete cache:\\n`;\n msg += incompleteLocales\n .map(\n (item) =>\n ` - ${item.locale}: ${item.missing}/${item.total} translations missing`,\n )\n .join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n msg += ` 💡 To fix:\\n`;\n msg += ` 1. Set LINGO_BUILD_MODE=translate to generate translations\\n`;\n msg += ` 2. Commit the generated .lingo/cache/*.json files\\n`;\n msg += ` 3. Ensure translation API keys are available if generating translations`;\n\n return msg;\n}\n\nfunction formatTranslationErrors(\n errors: Array<{ locale: LocaleCode; error: string }>,\n): string {\n let msg = \"❌ Translation generation failed:\\n\\n\";\n\n msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join(\"\\n\");\n\n msg += \"\\n\\n\";\n msg += ` 💡 Translation errors must be resolved in \"translate\" mode.\\n`;\n msg += ` Check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsDA,eAAsB,yBACpB,SACiC;CACjC,MAAM,EAAE,QAAQ,kBAAkB,qBAAqB;CAGvD,MAAM,YACH,QAAQ,IAAI,oBACb,OAAO;AAET,QAAO,KAAK,kBAAkB,YAAY;CAE1C,MAAM,WAAW,MAAM,aAAa,iBAAiB;AAErD,KAAI,CAAC,YAAY,OAAO,KAAK,SAAS,QAAQ,CAAC,WAAW,GAAG;AAC3D,SAAO,KAAK,iDAAiD;AAC7D,SAAO;GACL,SAAS;GACT,OAAO,EAAE;GACV;;CAGH,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,CAAC;AACnD,QAAO,KAAK,YAAY,aAAa,uBAAuB;CAE5D,MAAM,QAAQ,YAAY,OAAO;AAGjC,KAAI,cAAc,cAAc;AAC9B,SAAO,KAAK,qCAAqC;AACjD,QAAM,cAAc,QAAQ,UAAU,MAAM;AAC5C,SAAO,KAAK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IAAI,KAAK,QAAQ,GAAG,KAAK,MAAM,uBACvD,CACA,KAAK,KAAK;AACb,SAAO;;AAGT,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO;;AAGT,SAAS,wBACP,QACQ;CACR,IAAI,MAAM;AAEV,QAAO,OAAO,KAAK,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,QAAQ,CAAC,KAAK,KAAK;AAExE,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
package/build/plugin/next.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const require_logger = require('../utils/logger.cjs');
|
|
2
2
|
const require_config_factory = require('../utils/config-factory.cjs');
|
|
3
|
+
const require_translation_service = require('../translators/translation-service.cjs');
|
|
3
4
|
const require_manager = require('../metadata/manager.cjs');
|
|
4
5
|
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
5
6
|
const require_build_translator = require('./build-translator.cjs');
|
|
@@ -134,7 +135,7 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
134
135
|
require_logger.logger.debug(`Initializing Lingo.dev compiler. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
|
|
135
136
|
if (isDev && !process.env.LINGO_TRANSLATION_SERVER_URL) {
|
|
136
137
|
const translationServer = await require_translation_server.startOrGetTranslationServer({
|
|
137
|
-
|
|
138
|
+
translationService: new require_translation_service.TranslationService(lingoConfig, require_logger.logger),
|
|
138
139
|
onError: (err) => {
|
|
139
140
|
require_logger.logger.error("Translation server error:", err);
|
|
140
141
|
},
|
|
@@ -182,7 +183,6 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
182
183
|
projectDir
|
|
183
184
|
});
|
|
184
185
|
require_logger.logger.info("Running post-build translation generation...");
|
|
185
|
-
require_logger.logger.info(`Build mode: Using metadata file: ${metadataFilePath}`);
|
|
186
186
|
try {
|
|
187
187
|
await require_build_translator.processBuildTranslations({
|
|
188
188
|
config: lingoConfig,
|
|
@@ -190,7 +190,7 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
190
190
|
metadataFilePath
|
|
191
191
|
});
|
|
192
192
|
} catch (error) {
|
|
193
|
-
require_logger.logger.error("Translation generation failed:", error);
|
|
193
|
+
require_logger.logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
|
|
194
194
|
throw error;
|
|
195
195
|
}
|
|
196
196
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAgBY,sBAAA,GAAyB;iBAoLf,SAAA,aACR,sCACE,yBACb,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAgBY,sBAAA,GAAyB;iBAoLf,SAAA,aACR,sCACE,yBACb,QAAQ"}
|
package/build/plugin/next.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { __require } from "../_virtual/rolldown_runtime.mjs";
|
|
2
2
|
import { logger } from "../utils/logger.mjs";
|
|
3
3
|
import { createLingoConfig } from "../utils/config-factory.mjs";
|
|
4
|
+
import { TranslationService } from "../translators/translation-service.mjs";
|
|
4
5
|
import { cleanupExistingMetadata, getMetadataPath } from "../metadata/manager.mjs";
|
|
5
6
|
import { startOrGetTranslationServer } from "../translation-server/translation-server.mjs";
|
|
6
7
|
import { processBuildTranslations } from "./build-translator.mjs";
|
|
@@ -135,7 +136,7 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
135
136
|
logger.debug(`Initializing Lingo.dev compiler. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
|
|
136
137
|
if (isDev && !process.env.LINGO_TRANSLATION_SERVER_URL) {
|
|
137
138
|
const translationServer = await startOrGetTranslationServer({
|
|
138
|
-
|
|
139
|
+
translationService: new TranslationService(lingoConfig, logger),
|
|
139
140
|
onError: (err) => {
|
|
140
141
|
logger.error("Translation server error:", err);
|
|
141
142
|
},
|
|
@@ -183,7 +184,6 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
183
184
|
projectDir
|
|
184
185
|
});
|
|
185
186
|
logger.info("Running post-build translation generation...");
|
|
186
|
-
logger.info(`Build mode: Using metadata file: ${metadataFilePath}`);
|
|
187
187
|
try {
|
|
188
188
|
await processBuildTranslations({
|
|
189
189
|
config: lingoConfig,
|
|
@@ -191,7 +191,7 @@ async function withLingo(nextConfig = {}, lingoOptions) {
|
|
|
191
191
|
metadataFilePath
|
|
192
192
|
});
|
|
193
193
|
} catch (error) {
|
|
194
|
-
logger.error("Translation generation failed:", error);
|
|
194
|
+
logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
|
|
195
195
|
throw error;
|
|
196
196
|
}
|
|
197
197
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport { createLingoConfig } from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { LingoConfig, PartialLingoConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupExistingMetadata, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\n\nexport type LingoNextPluginOptions = PartialLingoConfig;\n\ntype RuleKey = \"compiler\" | \"devConfig\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n lingoConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n lingoConfig: LingoConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: lingoConfig.sourceRoot,\n lingoDir: lingoConfig.lingoDir,\n sourceLocale: lingoConfig.sourceLocale,\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@lingo.dev/compiler/next-compiler-loader\",\n options: {\n ...common,\n useDirective: lingoConfig.useDirective,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@lingo.dev/compiler/next-config-loader\",\n options: {\n ...common,\n dev: {\n translationServerUrl,\n ...lingoConfig.dev,\n },\n },\n };\n const localeServerLoader = {\n loader: \"@lingo.dev/compiler/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: lingoConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@lingo.dev/compiler/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: lingoConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: lingoConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n devConfig: translationServerUrl\n ? {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n }\n : {},\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack?.rules\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nexport async function withLingo(\n nextConfig: NextConfig = {},\n lingoOptions: LingoNextPluginOptions,\n): Promise<NextConfig> {\n const lingoConfig = createLingoConfig(lingoOptions);\n let metadataFilePath = getMetadataPath(lingoConfig);\n const isDev = lingoConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Lingo.dev compiler. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // TODO (AleksandrSl 12/12/2025): Add API keys validation too, so we can log it nicely.\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.LINGO_TRANSLATION_SERVER_URL) {\n const translationServer = await startOrGetTranslationServer({\n startPort: lingoConfig.dev.translationServerStartPort,\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(`Translation server started successfully on port: ${port}`);\n },\n config: lingoConfig,\n });\n process.env.LINGO_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n\n const translationServerUrl = process.env.LINGO_TRANSLATION_SERVER_URL;\n\n if (isMainRunner()) {\n // We need to cleaup the file only once, to avoid having extra translation introduced into the build, or old translation to pile up.\n cleanupExistingMetadata(metadataFilePath);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => {\n cleanupExistingMetadata(metadataFilePath);\n },\n });\n }\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ lingoConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n // TODO (AleksandrSl 08/12/2025): Describe what have to be done to support custom resolvers\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n logger.info(`Build mode: Using metadata file: ${metadataFilePath}`);\n\n try {\n await processBuildTranslations({\n config: lingoConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\"Translation generation failed:\", error);\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const lingoRules = Object.values(\n loaders({ lingoConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...lingoRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAS,QAAQ,EACf,aACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,YAAY;EACxB,UAAU,YAAY;EACt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Config: Partial<NextConfig>","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport { createLingoConfig } from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { LingoConfig, PartialLingoConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupExistingMetadata, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\n\nexport type LingoNextPluginOptions = PartialLingoConfig;\n\ntype RuleKey = \"compiler\" | \"devConfig\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n lingoConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n lingoConfig: LingoConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: lingoConfig.sourceRoot,\n lingoDir: lingoConfig.lingoDir,\n sourceLocale: lingoConfig.sourceLocale,\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@lingo.dev/compiler/next-compiler-loader\",\n options: {\n ...common,\n useDirective: lingoConfig.useDirective,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@lingo.dev/compiler/next-config-loader\",\n options: {\n ...common,\n dev: {\n translationServerUrl,\n ...lingoConfig.dev,\n },\n },\n };\n const localeServerLoader = {\n loader: \"@lingo.dev/compiler/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: lingoConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@lingo.dev/compiler/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: lingoConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: lingoConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n devConfig: translationServerUrl\n ? {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n }\n : {},\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack?.rules\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nexport async function withLingo(\n nextConfig: NextConfig = {},\n lingoOptions: LingoNextPluginOptions,\n): Promise<NextConfig> {\n const lingoConfig = createLingoConfig(lingoOptions);\n let metadataFilePath = getMetadataPath(lingoConfig);\n const isDev = lingoConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Lingo.dev compiler. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.LINGO_TRANSLATION_SERVER_URL) {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(lingoConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(`Translation server started successfully on port: ${port}`);\n },\n config: lingoConfig,\n });\n process.env.LINGO_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n\n const translationServerUrl = process.env.LINGO_TRANSLATION_SERVER_URL;\n\n if (isMainRunner()) {\n // We need to cleaup the file only once, to avoid having extra translation introduced into the build, or old translation to pile up.\n cleanupExistingMetadata(metadataFilePath);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => {\n cleanupExistingMetadata(metadataFilePath);\n },\n });\n }\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ lingoConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n // TODO (AleksandrSl 08/12/2025): Describe what have to be done to support custom resolvers\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n try {\n await processBuildTranslations({\n config: lingoConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const lingoRules = Object.values(\n loaders({ lingoConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...lingoRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,QAAQ,EACf,aACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,YAAY;EACxB,UAAU,YAAY;EACtB,cAAc,YAAY;EAC3B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,YAAY;GAC1B;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,KAAK;IACH;IACA,GAAG,YAAY;IAChB;GACF;EACF;CACD,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,YAAY;GAChC;EACF;CAED,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,YAAY;GAChC;EACF;AAED,QAAO;EACL,UAAU;GACR,WAAW;IACT,SAAS;IACT,QAAQ;KACN,WAAW,EACT,SAAS,YAAY,eAAe,eAAe,QACpD;KACD,SAAS,CAAC,eAAe;KAC1B;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,SAAS;IACT,KAAK,CAAC,eAAe;IACtB;GACF;EAED,WAAW,uBACP;GACE,WAAW;IACT,SAAS;IACT,QAAQ,EACN,SAAS,CAAC,aAAa,EACxB;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,KAAK,CAAC,aAAa;IACpB;GACF,GACD,EAAE;EAEN,cAAc;GACZ,WAAW;IACT,SAAS;IACT,QAAQ,EACN,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;CAIV,MAAMC,WACJ,QACA,YACG;EAEH,IAAI,iBAAiB;AACrB,MAAI,OAAO,WAAW,YAAY,WAChC,kBAAiB,WAAW,QAAQ,QAAQ,QAAQ;EAGtD,MAAM,aAAa,OAAO,OACxB,QAAQ;GAAE;GAAa;GAAkB;GAAsB,CAAC,CACjE,CACE,KAAK,UAAU,MAAM,QAAQ,CAC7B,OAAO,QAAQ;AAIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,WAAW;AAElD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_logger = require('../utils/logger.cjs');
|
|
3
3
|
const require_config_factory = require('../utils/config-factory.cjs');
|
|
4
|
+
const require_translation_service = require('../translators/translation-service.cjs');
|
|
4
5
|
const require_manager = require('../metadata/manager.cjs');
|
|
5
6
|
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
6
7
|
const require_build_translator = require('./build-translator.cjs');
|
|
@@ -54,7 +55,7 @@ const virtualModulesLoaders = Object.fromEntries(Object.values(virtualModules).m
|
|
|
54
55
|
const lingoUnplugin = (0, unplugin.createUnplugin)((options) => {
|
|
55
56
|
const config = require_config_factory.createLingoConfig(options);
|
|
56
57
|
const isDev = config.environment === "development";
|
|
57
|
-
|
|
58
|
+
config.dev.translationServerStartPort;
|
|
58
59
|
let webpackMode;
|
|
59
60
|
const getMetadataPath$1 = () => {
|
|
60
61
|
return require_manager.getMetadataPath(webpackMode ? {
|
|
@@ -64,7 +65,7 @@ const lingoUnplugin = (0, unplugin.createUnplugin)((options) => {
|
|
|
64
65
|
};
|
|
65
66
|
async function startServer() {
|
|
66
67
|
const server = await require_translation_server.startTranslationServer({
|
|
67
|
-
|
|
68
|
+
translationService: new require_translation_service.TranslationService(config, require_logger.logger),
|
|
68
69
|
onError: (err) => {
|
|
69
70
|
require_logger.logger.error("Translation server error:", err);
|
|
70
71
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unplugin.d.cts","names":[],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"unplugin.d.cts","names":[],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":[],"mappings":";;;;KA8BY,kBAAA,GAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unplugin.d.mts","names":[],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"unplugin.d.mts","names":[],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":[],"mappings":";;;;KA8BY,kBAAA,GAAqB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { logger } from "../utils/logger.mjs";
|
|
2
2
|
import { createLingoConfig } from "../utils/config-factory.mjs";
|
|
3
|
+
import { TranslationService } from "../translators/translation-service.mjs";
|
|
3
4
|
import { MetadataManager, cleanupExistingMetadata, getMetadataPath } from "../metadata/manager.mjs";
|
|
4
5
|
import { startTranslationServer } from "../translation-server/translation-server.mjs";
|
|
5
6
|
import { processBuildTranslations } from "./build-translator.mjs";
|
|
@@ -51,7 +52,7 @@ const virtualModulesLoaders = Object.fromEntries(Object.values(virtualModules).m
|
|
|
51
52
|
const lingoUnplugin = createUnplugin((options) => {
|
|
52
53
|
const config = createLingoConfig(options);
|
|
53
54
|
const isDev = config.environment === "development";
|
|
54
|
-
|
|
55
|
+
config.dev.translationServerStartPort;
|
|
55
56
|
let webpackMode;
|
|
56
57
|
const getMetadataPath$1 = () => {
|
|
57
58
|
return getMetadataPath(webpackMode ? {
|
|
@@ -61,7 +62,7 @@ const lingoUnplugin = createUnplugin((options) => {
|
|
|
61
62
|
};
|
|
62
63
|
async function startServer() {
|
|
63
64
|
const server = await startTranslationServer({
|
|
64
|
-
|
|
65
|
+
translationService: new TranslationService(config, logger),
|
|
65
66
|
onError: (err) => {
|
|
66
67
|
logger.error("Translation server error:", err);
|
|
67
68
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unplugin.mjs","names":["translationServer: TranslationServer","webpackMode: \"development\" | \"production\" | undefined","getMetadataPath","rawGetMetadataPath"],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":["import { createUnplugin } from \"unplugin\";\nimport { transformComponent } from \"./transform\";\nimport type {\n LingoConfig,\n LingoInternalFields,\n PartialLingoConfig,\n} from \"../types\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport {\n cleanupExistingMetadata,\n getMetadataPath as rawGetMetadataPath,\n MetadataManager,\n} from \"../metadata/manager\";\nimport { createLingoConfig } from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport {\n generateClientLocaleModule,\n generateConfigModule,\n generateServerLocaleModule,\n} from \"../virtual/code-generator\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nexport type LingoPluginOptions = PartialLingoConfig;\n\nlet translationServer: TranslationServer;\n\nconst PLUGIN_NAME = \"lingo-compiler\";\n\nfunction tryLocalOrReturnVirtual(\n config: LingoConfig,\n fileName: string,\n virtualName: string,\n) {\n const customPath = path.join(config.sourceRoot, config.lingoDir, fileName);\n if (fs.existsSync(customPath)) {\n return customPath;\n }\n return virtualName;\n}\n\n/**\n * Single source of truth for virtual modules\n * Each entry defines both resolver (import path → virtual ID) and loader (virtual ID → code)\n *\n * If customFileCheck is defined, the specified file will be first searched for, and if not found virtual module will be used.\n */\nconst virtualModules = {\n \"@lingo.dev/compiler/virtual/config\": {\n virtualId: \"\\0virtual:lingo-config\",\n loader: (config: LingoConfig) => generateConfigModule(config),\n customFileCheck: undefined,\n },\n \"@lingo.dev/compiler/virtual/locale/server\": {\n virtualId: \"\\0virtual:locale-resolver.server\" as const,\n loader: (config: LingoConfig) => generateServerLocaleModule(config),\n customFileCheck: \"locale-resolver.server.ts\" as const,\n },\n \"@lingo.dev/compiler/virtual/locale/client\": {\n virtualId: \"\\0virtual:locale-resolver.client\" as const,\n loader: (config: LingoConfig) => generateClientLocaleModule(config),\n customFileCheck: \"locale-resolver.client.ts\" as const,\n },\n} as const;\n\n// Derive resolver and loader maps from the single source\nconst virtualModulesResolvers = Object.fromEntries(\n Object.entries(virtualModules).map(([importPath, module]) => [\n importPath,\n (config: LingoConfig) =>\n module.customFileCheck\n ? tryLocalOrReturnVirtual(\n config,\n module.customFileCheck,\n module.virtualId,\n )\n : module.virtualId,\n ]),\n);\n\nconst virtualModulesLoaders = Object.fromEntries(\n Object.values(virtualModules).map((value) => [value.virtualId, value.loader]),\n);\n\n/**\n * Universal plugin for Lingo.dev compiler\n * Supports Vite, Webpack\n */\nexport const lingoUnplugin = createUnplugin<\n LingoPluginOptions & Partial<Pick<LingoConfig, LingoInternalFields>>\n>((options) => {\n const config = createLingoConfig(options);\n\n // Won't work for webpack most likely. Use mode there to set correct environment in configs.\n const isDev = config.environment === \"development\";\n const startPort = config.dev.translationServerStartPort;\n\n // For webpack: store the actual mode and use it to compute the correct metadata path\n let webpackMode: \"development\" | \"production\" | undefined;\n // Should be dynamic, because webpack only tells us the mode inside the plugin, not inside the config.\n const getMetadataPath = () => {\n return rawGetMetadataPath(\n webpackMode ? { ...config, environment: webpackMode } : config,\n );\n };\n\n async function startServer() {\n const server = await startTranslationServer({\n startPort,\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(`Translation server started successfully on port: ${port}`);\n },\n config,\n });\n // I don't like this quite a lot. But starting server inside the loader seems lame.\n config.dev.translationServerUrl = server.getUrl();\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.stop();\n },\n });\n return server;\n }\n\n return {\n name: PLUGIN_NAME,\n enforce: \"pre\", // Run before other plugins (especially before React plugin)\n\n vite: {\n // Vite handles deep merge\n config() {\n // Required for custom virtual like modules to be resolved; otherwise they are bundled with raw source code.\n return {\n optimizeDeps: {\n exclude: [\"@lingo.dev/compiler\"],\n },\n };\n },\n async buildStart() {\n const metadataFilePath = getMetadataPath();\n\n cleanupExistingMetadata(metadataFilePath);\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupExistingMetadata(metadataFilePath),\n });\n\n if (isDev && !translationServer) {\n translationServer = await startServer();\n }\n },\n\n async buildEnd() {\n const metadataFilePath = getMetadataPath();\n if (!isDev) {\n try {\n await processBuildTranslations({\n config,\n publicOutputPath: \"public/translations\",\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\"Build-time translation processing failed:\", error);\n }\n }\n },\n },\n\n webpack(compiler) {\n webpackMode =\n compiler.options.mode === \"development\" ? \"development\" : \"production\";\n const metadataFilePath = getMetadataPath();\n // Yes, this is dirty play, but webpack runs only for this plugin, and this way we save people from using wrong config\n config.environment = webpackMode;\n\n compiler.hooks.initialize.tap(PLUGIN_NAME, () => {\n cleanupExistingMetadata(metadataFilePath);\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupExistingMetadata(metadataFilePath),\n });\n });\n\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async () => {\n if (webpackMode === \"development\" && !translationServer) {\n translationServer = await startServer();\n }\n });\n\n compiler.hooks.additionalPass.tapPromise(PLUGIN_NAME, async () => {\n if (webpackMode === \"production\") {\n try {\n await processBuildTranslations({\n config,\n publicOutputPath: \"public/translations\",\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\"Build-time translation processing failed:\", error);\n throw error;\n }\n }\n });\n\n // Duplicates the cleanup process handlers does, but won't hurt since cleanup is idempotent.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {\n cleanupExistingMetadata(metadataFilePath);\n await translationServer?.stop();\n });\n },\n\n resolveId(id) {\n const handler = virtualModulesResolvers[id];\n if (handler) {\n return handler(config);\n }\n return null;\n },\n\n load: {\n filter: {\n // Without the filter webpack goes mad\n id: /virtual:/,\n },\n handler(id: string) {\n const handler = virtualModulesLoaders[id];\n if (handler) {\n return handler(config);\n }\n return null;\n },\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[tj]sx$/],\n exclude: /node_modules/,\n },\n // If useDirective is enabled, only process files with \"use i18n\"\n // This is more efficient than checking in the handler\n code: config.useDirective ? useI18nRegex : undefined,\n },\n async handler(code, id) {\n try {\n // Transform the component\n const result = transformComponent({\n code,\n filePath: id,\n config,\n });\n\n // If no transformation occurred, return original code\n if (!result.transformed) {\n logger.debug(`No transformation needed for ${id}`);\n return null;\n }\n const metadataManager = new MetadataManager(getMetadataPath());\n\n // Update metadata with new entries (thread-safe)\n if (result.newEntries && result.newEntries.length > 0) {\n await metadataManager.saveMetadataWithEntries(result.newEntries);\n\n logger.debug(\n `Found ${result.newEntries.length} translatable text(s) in ${id}`,\n );\n }\n\n logger.debug(`Returning transformed code for ${id}`);\n return {\n code: result.code,\n map: result.map,\n };\n } catch (error) {\n logger.error(`Transform error in ${id}:`, error);\n return null;\n }\n },\n },\n };\n});\n"],"mappings":";;;;;;;;;;;;;;AA+BA,IAAIA;AAEJ,MAAM,cAAc;AAEpB,SAAS,wBACP,QACA,UACA,aACA;CACA,MAAM,aAAa,KAAK,KAAK,OAAO,YAAY,OAAO,UAAU,SAAS;AAC1E,KAAI,GAAG,WAAW,WAAW,CAC3B,QAAO;AAET,QAAO;;;;;;;;AAST,MAAM,iBAAiB;CACrB,sCAAsC;EACpC,WAAW;EACX,SAAS,WAAwB,qBAAqB,OAAO;EAC7D,iBAAiB;EAClB;CACD,6CAA6C;EAC3C,WAAW;EACX,SAAS,WAAwB,2BAA2B,OAAO;EACnE,iBAAiB;EAClB;CACD,6CAA6C;EAC3C,WAAW;EACX,SAAS,WAAwB,2BAA2B,OAAO;EACnE,iBAAiB;EAClB;CACF;AAGD,MAAM,0BAA0B,OAAO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O;;KAET,MAAM,kBAAkB,IAAI,gBAAgBA,mBAAiB,CAAC;AAG9D,SAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,YAAM,gBAAgB,wBAAwB,OAAO,WAAW;AAEhE,aAAO,MACL,SAAS,OAAO,WAAW,OAAO,2BAA2B,KAC9D;;AAGH,YAAO,MAAM,kCAAkC,KAAK;AACpD,YAAO;MACL,MAAM,OAAO;MACb,KAAK,OAAO;MACb;aACM,OAAO;AACd,YAAO,MAAM,sBAAsB,GAAG,IAAI,MAAM;AAChD,YAAO;;;GAGZ;EACF;EACD"}
|
|
1
|
+
{"version":3,"file":"unplugin.mjs","names":["translationServer: TranslationServer","webpackMode: \"development\" | \"production\" | undefined","getMetadataPath","rawGetMetadataPath"],"sources":["../../src/plugin/unplugin.ts"],"sourcesContent":["import { createUnplugin } from \"unplugin\";\nimport { transformComponent } from \"./transform\";\nimport type {\n LingoConfig,\n LingoInternalFields,\n PartialLingoConfig,\n} from \"../types\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport {\n cleanupExistingMetadata,\n getMetadataPath as rawGetMetadataPath,\n MetadataManager,\n} from \"../metadata/manager\";\nimport { createLingoConfig } from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport {\n generateClientLocaleModule,\n generateConfigModule,\n generateServerLocaleModule,\n} from \"../virtual/code-generator\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { TranslationService } from \"../translators\";\n\nexport type LingoPluginOptions = PartialLingoConfig;\n\nlet translationServer: TranslationServer;\n\nconst PLUGIN_NAME = \"lingo-compiler\";\n\nfunction tryLocalOrReturnVirtual(\n config: LingoConfig,\n fileName: string,\n virtualName: string,\n) {\n const customPath = path.join(config.sourceRoot, config.lingoDir, fileName);\n if (fs.existsSync(customPath)) {\n return customPath;\n }\n return virtualName;\n}\n\n/**\n * Single source of truth for virtual modules\n * Each entry defines both resolver (import path → virtual ID) and loader (virtual ID → code)\n *\n * If customFileCheck is defined, the specified file will be first searched for, and if not found virtual module will be used.\n */\nconst virtualModules = {\n \"@lingo.dev/compiler/virtual/config\": {\n virtualId: \"\\0virtual:lingo-config\",\n loader: (config: LingoConfig) => generateConfigModule(config),\n customFileCheck: undefined,\n },\n \"@lingo.dev/compiler/virtual/locale/server\": {\n virtualId: \"\\0virtual:locale-resolver.server\" as const,\n loader: (config: LingoConfig) => generateServerLocaleModule(config),\n customFileCheck: \"locale-resolver.server.ts\" as const,\n },\n \"@lingo.dev/compiler/virtual/locale/client\": {\n virtualId: \"\\0virtual:locale-resolver.client\" as const,\n loader: (config: LingoConfig) => generateClientLocaleModule(config),\n customFileCheck: \"locale-resolver.client.ts\" as const,\n },\n} as const;\n\n// Derive resolver and loader maps from the single source\nconst virtualModulesResolvers = Object.fromEntries(\n Object.entries(virtualModules).map(([importPath, module]) => [\n importPath,\n (config: LingoConfig) =>\n module.customFileCheck\n ? tryLocalOrReturnVirtual(\n config,\n module.customFileCheck,\n module.virtualId,\n )\n : module.virtualId,\n ]),\n);\n\nconst virtualModulesLoaders = Object.fromEntries(\n Object.values(virtualModules).map((value) => [value.virtualId, value.loader]),\n);\n\n/**\n * Universal plugin for Lingo.dev compiler\n * Supports Vite, Webpack\n */\nexport const lingoUnplugin = createUnplugin<\n LingoPluginOptions & Partial<Pick<LingoConfig, LingoInternalFields>>\n>((options) => {\n const config = createLingoConfig(options);\n\n // Won't work for webpack most likely. Use mode there to set correct environment in configs.\n const isDev = config.environment === \"development\";\n const startPort = config.dev.translationServerStartPort;\n\n // For webpack: store the actual mode and use it to compute the correct metadata path\n let webpackMode: \"development\" | \"production\" | undefined;\n // Should be dynamic, because webpack only tells us the mode inside the plugin, not inside the config.\n const getMetadataPath = () => {\n return rawGetMetadataPath(\n webpackMode ? { ...config, environment: webpackMode } : config,\n );\n };\n\n async function startServer() {\n const server = await startTranslationServer({\n translationService: new TranslationService(config, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(`Translation server started successfully on port: ${port}`);\n },\n config,\n });\n // I don't like this quite a lot. But starting server inside the loader seems lame.\n config.dev.translationServerUrl = server.getUrl();\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.stop();\n },\n });\n return server;\n }\n\n return {\n name: PLUGIN_NAME,\n enforce: \"pre\", // Run before other plugins (especially before React plugin)\n\n vite: {\n // Vite handles deep merge\n config() {\n // Required for custom virtual like modules to be resolved; otherwise they are bundled with raw source code.\n return {\n optimizeDeps: {\n exclude: [\"@lingo.dev/compiler\"],\n },\n };\n },\n async buildStart() {\n const metadataFilePath = getMetadataPath();\n\n cleanupExistingMetadata(metadataFilePath);\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupExistingMetadata(metadataFilePath),\n });\n\n if (isDev && !translationServer) {\n translationServer = await startServer();\n }\n },\n\n async buildEnd() {\n const metadataFilePath = getMetadataPath();\n if (!isDev) {\n try {\n await processBuildTranslations({\n config,\n publicOutputPath: \"public/translations\",\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\"Build-time translation processing failed:\", error);\n }\n }\n },\n },\n\n webpack(compiler) {\n webpackMode =\n compiler.options.mode === \"development\" ? \"development\" : \"production\";\n const metadataFilePath = getMetadataPath();\n // Yes, this is dirty play, but webpack runs only for this plugin, and this way we save people from using wrong config\n config.environment = webpackMode;\n\n compiler.hooks.initialize.tap(PLUGIN_NAME, () => {\n cleanupExistingMetadata(metadataFilePath);\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupExistingMetadata(metadataFilePath),\n });\n });\n\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async () => {\n if (webpackMode === \"development\" && !translationServer) {\n translationServer = await startServer();\n }\n });\n\n compiler.hooks.additionalPass.tapPromise(PLUGIN_NAME, async () => {\n if (webpackMode === \"production\") {\n try {\n await processBuildTranslations({\n config,\n publicOutputPath: \"public/translations\",\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\"Build-time translation processing failed:\", error);\n throw error;\n }\n }\n });\n\n // Duplicates the cleanup process handlers does, but won't hurt since cleanup is idempotent.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {\n cleanupExistingMetadata(metadataFilePath);\n await translationServer?.stop();\n });\n },\n\n resolveId(id) {\n const handler = virtualModulesResolvers[id];\n if (handler) {\n return handler(config);\n }\n return null;\n },\n\n load: {\n filter: {\n // Without the filter webpack goes mad\n id: /virtual:/,\n },\n handler(id: string) {\n const handler = virtualModulesLoaders[id];\n if (handler) {\n return handler(config);\n }\n return null;\n },\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[tj]sx$/],\n exclude: /node_modules/,\n },\n // If useDirective is enabled, only process files with \"use i18n\"\n // This is more efficient than checking in the handler\n code: config.useDirective ? useI18nRegex : undefined,\n },\n async handler(code, id) {\n try {\n // Transform the component\n const result = transformComponent({\n code,\n filePath: id,\n config,\n });\n\n // If no transformation occurred, return original code\n if (!result.transformed) {\n logger.debug(`No transformation needed for ${id}`);\n return null;\n }\n const metadataManager = new MetadataManager(getMetadataPath());\n\n // Update metadata with new entries (thread-safe)\n if (result.newEntries && result.newEntries.length > 0) {\n await metadataManager.saveMetadataWithEntries(result.newEntries);\n\n logger.debug(\n `Found ${result.newEntries.length} translatable text(s) in ${id}`,\n );\n }\n\n logger.debug(`Returning transformed code for ${id}`);\n return {\n code: result.code,\n map: result.map,\n };\n } catch (error) {\n logger.error(`Transform error in ${id}:`, error);\n return null;\n }\n },\n },\n };\n});\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,IAAIA;AAEJ,MAAM,cAAc;AAEpB,SAAS,wBACP,QACA,UACA,aACA;CACA,MAAM,aAAa,KAAK,KAAK,OAAO,YAAY,OAAO,UAAU,SAAS;AAC1E,KAAI,GAAG,WAAW,WAAW,CAC3B,QAAO;AAET,QAAO;;;;;;;;A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