@lingo.dev/_compiler 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2649 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/_base.ts
9
+ var _generator = require('@babel/generator'); var _generator2 = _interopRequireDefault(_generator);
10
+ var _parser = require('@babel/parser'); var parser = _interopRequireWildcard(_parser);
11
+ function createCodeMutation(spec) {
12
+ return (payload) => {
13
+ const result = spec(payload);
14
+ return result;
15
+ };
16
+ }
17
+ function createPayload(input) {
18
+ const ast = parser.parse(input.code, {
19
+ sourceType: "module",
20
+ plugins: ["jsx", "typescript"]
21
+ });
22
+ return {
23
+ ...input,
24
+ ast
25
+ };
26
+ }
27
+ function createOutput(payload) {
28
+ const generationResult = _generator2.default.call(void 0, payload.ast, {}, payload.code);
29
+ return {
30
+ code: generationResult.code,
31
+ map: generationResult.map
32
+ };
33
+ }
34
+ function composeMutations(...mutations) {
35
+ return (input) => {
36
+ let result = input;
37
+ for (const mutate of mutations) {
38
+ const intermediateResult = mutate(result);
39
+ if (!intermediateResult) {
40
+ break;
41
+ } else {
42
+ result = intermediateResult;
43
+ }
44
+ }
45
+ return result;
46
+ };
47
+ }
48
+ var defaultParams = {
49
+ sourceRoot: "src",
50
+ lingoDir: "lingo",
51
+ sourceLocale: "en",
52
+ targetLocales: ["es"],
53
+ rsc: false,
54
+ useDirective: false,
55
+ debug: false,
56
+ models: {}
57
+ };
58
+
59
+ // src/_const.ts
60
+ var ModuleId = {
61
+ ReactClient: ["lingo.dev/react/client", "lingo.dev/react-client"],
62
+ ReactRSC: ["lingo.dev/react/rsc", "lingo.dev/react-rsc"],
63
+ ReactRouter: ["lingo.dev/react/react-router", "lingo.dev/react-router"]
64
+ };
65
+ var LCP_DICTIONARY_FILE_NAME = "dictionary.js";
66
+
67
+ // src/lib/lcp/cache.ts
68
+ var _fs = require('fs'); var fs = _interopRequireWildcard(_fs); var fs4 = _interopRequireWildcard(_fs);
69
+ var _path = require('path'); var path = _interopRequireWildcard(_path); var path5 = _interopRequireWildcard(_path);
70
+ var _prettier = require('prettier'); var prettier = _interopRequireWildcard(_prettier);
71
+ var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash);
72
+ var LCPCache = class {
73
+ // make sure the cache file exists, otherwise imports will fail
74
+ static ensureDictionaryFile(params) {
75
+ const cachePath = this._getCachePath(params);
76
+ if (!fs.existsSync(cachePath)) {
77
+ const dir = path.dirname(cachePath);
78
+ if (!fs.existsSync(dir)) {
79
+ fs.mkdirSync(dir, { recursive: true });
80
+ }
81
+ fs.writeFileSync(cachePath, "export default {};");
82
+ }
83
+ }
84
+ // read cache entries for given locale, validate entry hash from LCP schema
85
+ static readLocaleDictionary(locale, params) {
86
+ const cache = this._read(params);
87
+ const dictionary = this._extractLocaleDictionary(cache, locale, params.lcp);
88
+ return dictionary;
89
+ }
90
+ // write cache entries for given locale to existing cache file, use hash from LCP schema
91
+ static async writeLocaleDictionary(dictionary, params) {
92
+ const currentCache = this._read(params);
93
+ const newCache = this._mergeLocaleDictionary(
94
+ currentCache,
95
+ dictionary,
96
+ params.lcp
97
+ );
98
+ await this._write(newCache, params);
99
+ }
100
+ // merge dictionary with current cache, sort files, entries and locales to minimize diffs
101
+ static _mergeLocaleDictionary(currentCache, dictionary, lcp) {
102
+ const files = _lodash2.default.call(void 0, dictionary.files).mapValues((file, fileName) => ({
103
+ ...file,
104
+ entries: _lodash2.default.call(void 0, file.entries).mapValues((entry, entryName) => {
105
+ const cachedEntry = _nullishCoalesce(_lodash2.default.get(currentCache, ["files", fileName, "entries", entryName]), () => ( {}));
106
+ const hash = _lodash2.default.get(lcp, [
107
+ "files",
108
+ fileName,
109
+ "scopes",
110
+ entryName,
111
+ "hash"
112
+ ]);
113
+ const cachedEntryContent = cachedEntry.hash === hash ? cachedEntry.content : {};
114
+ const content = _lodash2.default.call(void 0, {
115
+ ...cachedEntryContent,
116
+ [dictionary.locale]: entry
117
+ }).toPairs().sortBy([0]).fromPairs().value();
118
+ return { content, hash };
119
+ }).toPairs().sortBy([0]).fromPairs().value()
120
+ })).toPairs().sortBy([0]).fromPairs().value();
121
+ const newCache = {
122
+ version: dictionary.version,
123
+ files
124
+ };
125
+ return newCache;
126
+ }
127
+ // extract dictionary from cache for given locale, validate entry hash from LCP schema
128
+ static _extractLocaleDictionary(cache, locale, lcp) {
129
+ const findCachedEntry = (hash) => {
130
+ const cachedEntry = _lodash2.default.call(void 0, cache.files).flatMap((file) => _lodash2.default.values(file.entries)).find((entry) => entry.hash === hash);
131
+ if (cachedEntry) {
132
+ return cachedEntry.content[locale];
133
+ }
134
+ return void 0;
135
+ };
136
+ const files = _lodash2.default.call(void 0, lcp.files).mapValues((file) => {
137
+ return {
138
+ entries: _lodash2.default.call(void 0, file.scopes).mapValues((entry) => {
139
+ return findCachedEntry(entry.hash);
140
+ }).pickBy((value) => value !== void 0).value()
141
+ };
142
+ }).pickBy((file) => !_lodash2.default.isEmpty(file.entries)).value();
143
+ const dictionary = {
144
+ version: cache.version,
145
+ locale,
146
+ files
147
+ };
148
+ return dictionary;
149
+ }
150
+ // format with prettier
151
+ static async _format(cachedContent, cachePath) {
152
+ try {
153
+ const config2 = await prettier.resolveConfig(cachePath);
154
+ const prettierOptions = {
155
+ ..._nullishCoalesce(config2, () => ( {})),
156
+ parser: _optionalChain([config2, 'optionalAccess', _12 => _12.parser]) ? config2.parser : "typescript"
157
+ };
158
+ return await prettier.format(cachedContent, prettierOptions);
159
+ } catch (error) {
160
+ }
161
+ return cachedContent;
162
+ }
163
+ // write cache to file as JSON
164
+ static async _write(dictionaryCache, params) {
165
+ const cachePath = this._getCachePath(params);
166
+ const cache = `export default ${JSON.stringify(dictionaryCache, null, 2)};`;
167
+ const formattedCache = await this._format(cache, cachePath);
168
+ fs.writeFileSync(cachePath, formattedCache);
169
+ }
170
+ // read cache from file as JSON
171
+ static _read(params) {
172
+ const cachePath = this._getCachePath(params);
173
+ if (!fs.existsSync(cachePath)) {
174
+ return {
175
+ version: 0.1,
176
+ files: {}
177
+ };
178
+ }
179
+ const jsObjectString = fs.readFileSync(cachePath, "utf8");
180
+ const cache = jsObjectString.replace(/^export default/, "").replace(/;\s*$/, "");
181
+ const obj = new Function(`return (${cache})`)();
182
+ return obj;
183
+ }
184
+ // get cache file path
185
+ static _getCachePath(params) {
186
+ return path.resolve(
187
+ process.cwd(),
188
+ params.sourceRoot,
189
+ params.lingoDir,
190
+ LCP_DICTIONARY_FILE_NAME
191
+ );
192
+ }
193
+ };
194
+
195
+ // src/utils/locales.ts
196
+ function getInvalidLocales(localeModels, sourceLocale, targetLocales) {
197
+ return targetLocales.filter((targetLocale) => {
198
+ const { provider, model } = getLocaleModel(
199
+ localeModels,
200
+ sourceLocale,
201
+ targetLocale
202
+ );
203
+ return provider === void 0 || model === void 0;
204
+ });
205
+ }
206
+ function getLocaleModel(localeModels, sourceLocale, targetLocale) {
207
+ const localeKeys = [
208
+ `${sourceLocale}:${targetLocale}`,
209
+ `*:${targetLocale}`,
210
+ `${sourceLocale}:*`,
211
+ "*:*"
212
+ ];
213
+ const modelKey = localeKeys.find((key) => localeModels.hasOwnProperty(key));
214
+ if (modelKey) {
215
+ const value = localeModels[modelKey];
216
+ const firstColonIndex = _optionalChain([value, 'optionalAccess', _13 => _13.indexOf, 'call', _14 => _14(":")]);
217
+ if (value && firstColonIndex !== -1 && firstColonIndex !== void 0) {
218
+ const provider2 = value.substring(0, firstColonIndex);
219
+ const model2 = value.substring(firstColonIndex + 1);
220
+ if (provider2 && model2) {
221
+ return { provider: provider2, model: model2 };
222
+ }
223
+ }
224
+ const [provider, model] = _optionalChain([value, 'optionalAccess', _15 => _15.split, 'call', _16 => _16(":")]) || [];
225
+ if (provider && model) {
226
+ return { provider, model };
227
+ }
228
+ }
229
+ return { provider: void 0, model: void 0 };
230
+ }
231
+
232
+ // src/utils/rc.ts
233
+ var _os = require('os'); var _os2 = _interopRequireDefault(_os);
234
+
235
+
236
+ var _ini = require('ini'); var _ini2 = _interopRequireDefault(_ini);
237
+ function getRc() {
238
+ const settingsFile = ".lingodotdevrc";
239
+ const homedir = _os2.default.homedir();
240
+ const settingsFilePath = path.default.join(homedir, settingsFile);
241
+ const content = fs.default.existsSync(settingsFilePath) ? fs.default.readFileSync(settingsFilePath, "utf-8") : "";
242
+ const data = _ini2.default.parse(content);
243
+ return data;
244
+ }
245
+
246
+ // src/utils/llm-api-key.ts
247
+
248
+ var _dotenv = require('dotenv'); var dotenv = _interopRequireWildcard(_dotenv);
249
+
250
+ function getKeyFromEnv(envVarName) {
251
+ if (process.env[envVarName]) {
252
+ return process.env[envVarName];
253
+ }
254
+ const result = dotenv.config({
255
+ path: [
256
+ path.default.resolve(process.cwd(), ".env"),
257
+ path.default.resolve(process.cwd(), ".env.local"),
258
+ path.default.resolve(process.cwd(), ".env.development")
259
+ ]
260
+ });
261
+ return _optionalChain([result, 'optionalAccess', _17 => _17.parsed, 'optionalAccess', _18 => _18[envVarName]]);
262
+ }
263
+ function getKeyFromRc(rcPath) {
264
+ const rc = getRc();
265
+ const result = _lodash2.default.get(rc, rcPath);
266
+ return typeof result === "string" ? result : void 0;
267
+ }
268
+ function getGroqKey() {
269
+ return getGroqKeyFromEnv() || getGroqKeyFromRc();
270
+ }
271
+ function getGroqKeyFromRc() {
272
+ return getKeyFromRc("llm.groqApiKey");
273
+ }
274
+ function getGroqKeyFromEnv() {
275
+ return getKeyFromEnv("GROQ_API_KEY");
276
+ }
277
+ function getLingoDotDevKeyFromEnv() {
278
+ return getKeyFromEnv("LINGODOTDEV_API_KEY");
279
+ }
280
+ function getLingoDotDevKeyFromRc() {
281
+ return getKeyFromRc("auth.apiKey");
282
+ }
283
+ function getLingoDotDevKey() {
284
+ return getLingoDotDevKeyFromEnv() || getLingoDotDevKeyFromRc();
285
+ }
286
+ function getGoogleKey() {
287
+ return getGoogleKeyFromEnv() || getGoogleKeyFromRc();
288
+ }
289
+ function getGoogleKeyFromRc() {
290
+ return getKeyFromRc("llm.googleApiKey");
291
+ }
292
+ function getGoogleKeyFromEnv() {
293
+ return getKeyFromEnv("GOOGLE_API_KEY");
294
+ }
295
+ function getOpenRouterKey() {
296
+ return getOpenRouterKeyFromEnv() || getOpenRouterKeyFromRc();
297
+ }
298
+ function getOpenRouterKeyFromRc() {
299
+ return getKeyFromRc("llm.openrouterApiKey");
300
+ }
301
+ function getOpenRouterKeyFromEnv() {
302
+ return getKeyFromEnv("OPENROUTER_API_KEY");
303
+ }
304
+
305
+ // src/utils/env.ts
306
+
307
+ function isRunningInCIOrDocker() {
308
+ return Boolean(process.env.CI) || fs.default.existsSync("/.dockerenv");
309
+ }
310
+
311
+ // src/lib/lcp/api/provider-details.ts
312
+ var providerDetails = {
313
+ groq: {
314
+ name: "Groq",
315
+ apiKeyEnvVar: "GROQ_API_KEY",
316
+ apiKeyConfigKey: "llm.groqApiKey",
317
+ getKeyLink: "https://groq.com",
318
+ docsLink: "https://console.groq.com/docs/errors"
319
+ },
320
+ google: {
321
+ name: "Google",
322
+ apiKeyEnvVar: "GOOGLE_API_KEY",
323
+ apiKeyConfigKey: "llm.googleApiKey",
324
+ getKeyLink: "https://ai.google.dev/",
325
+ docsLink: "https://ai.google.dev/gemini-api/docs/troubleshooting"
326
+ },
327
+ openrouter: {
328
+ name: "OpenRouter",
329
+ apiKeyEnvVar: "OPENROUTER_API_KEY",
330
+ apiKeyConfigKey: "llm.openrouterApiKey",
331
+ getKeyLink: "https://openrouter.ai",
332
+ docsLink: "https://openrouter.ai/docs"
333
+ },
334
+ ollama: {
335
+ name: "Ollama",
336
+ apiKeyEnvVar: void 0,
337
+ // Ollama doesn't require an API key
338
+ apiKeyConfigKey: void 0,
339
+ // Ollama doesn't require an API key
340
+ getKeyLink: "https://ollama.com/download",
341
+ docsLink: "https://github.com/ollama/ollama/tree/main/docs"
342
+ }
343
+ };
344
+
345
+ // src/_loader-utils.ts
346
+
347
+
348
+
349
+ // src/utils/index.ts
350
+ var _traverse = require('@babel/traverse'); var _traverse2 = _interopRequireDefault(_traverse);
351
+ var _types = require('@babel/types'); var t2 = _interopRequireWildcard(_types); var t = _interopRequireWildcard(_types); var t3 = _interopRequireWildcard(_types); var t5 = _interopRequireWildcard(_types); var t4 = _interopRequireWildcard(_types); var t8 = _interopRequireWildcard(_types); var t6 = _interopRequireWildcard(_types); var t7 = _interopRequireWildcard(_types); var t10 = _interopRequireWildcard(_types); var t9 = _interopRequireWildcard(_types); var t11 = _interopRequireWildcard(_types); var t12 = _interopRequireWildcard(_types); var t13 = _interopRequireWildcard(_types); var t14 = _interopRequireWildcard(_types); var t15 = _interopRequireWildcard(_types); var t17 = _interopRequireWildcard(_types); var t16 = _interopRequireWildcard(_types); var t21 = _interopRequireWildcard(_types); var t18 = _interopRequireWildcard(_types); var t19 = _interopRequireWildcard(_types); var t20 = _interopRequireWildcard(_types); var t22 = _interopRequireWildcard(_types); var t23 = _interopRequireWildcard(_types); var t24 = _interopRequireWildcard(_types);
352
+
353
+ // src/utils/jsx-attribute.ts
354
+
355
+
356
+ function getJsxAttributesMap(nodePath) {
357
+ const attributes = nodePath.node.openingElement.attributes;
358
+ return _lodash2.default.reduce(
359
+ attributes,
360
+ (result, attr) => {
361
+ if (attr.type !== "JSXAttribute" || attr.name.type !== "JSXIdentifier") {
362
+ return result;
363
+ }
364
+ const name = attr.name.name;
365
+ const value = extractAttributeValue(attr);
366
+ return { ...result, [name]: value };
367
+ },
368
+ {}
369
+ );
370
+ }
371
+ function getJsxAttributeValue(nodePath, attributeName) {
372
+ const attributes = nodePath.node.openingElement.attributes;
373
+ const attribute = _lodash2.default.find(
374
+ attributes,
375
+ (attr) => attr.type === "JSXAttribute" && attr.name.type === "JSXIdentifier" && attr.name.name === attributeName
376
+ );
377
+ if (!attribute) {
378
+ return void 0;
379
+ }
380
+ return extractAttributeValue(attribute);
381
+ }
382
+ function extractAttributeValue(attribute) {
383
+ if (!attribute.value) {
384
+ return true;
385
+ }
386
+ if (attribute.value.type === "StringLiteral") {
387
+ return attribute.value.value;
388
+ }
389
+ if (attribute.value.type === "JSXExpressionContainer") {
390
+ const expression = attribute.value.expression;
391
+ if (expression.type === "BooleanLiteral") {
392
+ return expression.value;
393
+ }
394
+ if (expression.type === "NumericLiteral") {
395
+ return expression.value;
396
+ }
397
+ if (expression.type === "StringLiteral") {
398
+ return expression.value;
399
+ }
400
+ }
401
+ return null;
402
+ }
403
+
404
+ // src/utils/index.ts
405
+ function getJsxRoots(node) {
406
+ const result = [];
407
+ _traverse2.default.call(void 0, node, {
408
+ JSXElement(path7) {
409
+ result.push(path7);
410
+ path7.skip();
411
+ }
412
+ });
413
+ return result;
414
+ }
415
+ function getOrCreateImport(ast, params) {
416
+ let importedName = params.exportedName;
417
+ let existingImport = findExistingImport(
418
+ ast,
419
+ params.exportedName,
420
+ params.moduleName
421
+ );
422
+ if (existingImport) {
423
+ return { importedName: existingImport };
424
+ }
425
+ importedName = generateUniqueImportName(ast, params.exportedName);
426
+ createImportDeclaration(
427
+ ast,
428
+ importedName,
429
+ params.exportedName,
430
+ params.moduleName
431
+ );
432
+ return { importedName };
433
+ }
434
+ function findExistingImport(ast, exportedName, moduleName) {
435
+ let result = null;
436
+ _traverse2.default.call(void 0, ast, {
437
+ ImportDeclaration(path7) {
438
+ if (!moduleName.includes(path7.node.source.value)) {
439
+ return;
440
+ }
441
+ for (const specifier of path7.node.specifiers) {
442
+ if (t2.isImportSpecifier(specifier) && (t2.isIdentifier(specifier.imported) && specifier.imported.name === exportedName || specifier.importKind === "value" && t2.isIdentifier(specifier.local) && specifier.local.name === exportedName)) {
443
+ result = specifier.local.name;
444
+ path7.stop();
445
+ return;
446
+ }
447
+ }
448
+ }
449
+ });
450
+ return result;
451
+ }
452
+ function generateUniqueImportName(ast, baseName) {
453
+ const usedNames = /* @__PURE__ */ new Set();
454
+ _traverse2.default.call(void 0, ast, {
455
+ Identifier(path7) {
456
+ usedNames.add(path7.node.name);
457
+ }
458
+ });
459
+ if (!usedNames.has(baseName)) {
460
+ return baseName;
461
+ }
462
+ let counter = 1;
463
+ let candidateName = `${baseName}${counter}`;
464
+ while (usedNames.has(candidateName)) {
465
+ counter++;
466
+ candidateName = `${baseName}${counter}`;
467
+ }
468
+ return candidateName;
469
+ }
470
+ function createImportDeclaration(ast, localName, exportedName, moduleName) {
471
+ _traverse2.default.call(void 0, ast, {
472
+ Program(path7) {
473
+ const importSpecifier2 = t2.importSpecifier(
474
+ t2.identifier(localName),
475
+ t2.identifier(exportedName)
476
+ );
477
+ const existingImport = path7.get("body").find(
478
+ (nodePath) => t2.isImportDeclaration(nodePath.node) && moduleName.includes(nodePath.node.source.value)
479
+ );
480
+ if (existingImport && t2.isImportDeclaration(existingImport.node)) {
481
+ existingImport.node.specifiers.push(importSpecifier2);
482
+ } else {
483
+ const importDeclaration2 = t2.importDeclaration(
484
+ [importSpecifier2],
485
+ t2.stringLiteral(moduleName[0])
486
+ );
487
+ const lastImportIndex = findLastImportIndex(path7);
488
+ path7.node.body.splice(lastImportIndex + 1, 0, importDeclaration2);
489
+ }
490
+ path7.stop();
491
+ }
492
+ });
493
+ }
494
+ function findLastImportIndex(programPath) {
495
+ const body = programPath.node.body;
496
+ for (let i = body.length - 1; i >= 0; i--) {
497
+ if (t2.isImportDeclaration(body[i])) {
498
+ return i;
499
+ }
500
+ }
501
+ return -1;
502
+ }
503
+ function _hasFileDirective(ast, directiveValue) {
504
+ let hasDirective = false;
505
+ _traverse2.default.call(void 0, ast, {
506
+ Directive(path7) {
507
+ if (path7.node.value.value === directiveValue) {
508
+ hasDirective = true;
509
+ path7.stop();
510
+ }
511
+ }
512
+ });
513
+ return hasDirective;
514
+ }
515
+ function hasI18nDirective(ast) {
516
+ return _hasFileDirective(ast, "use i18n");
517
+ }
518
+ function hasClientDirective(ast) {
519
+ return _hasFileDirective(ast, "use client");
520
+ }
521
+ function getModuleExecutionMode(ast, rscEnabled) {
522
+ if (rscEnabled) {
523
+ if (hasClientDirective(ast)) {
524
+ return "client";
525
+ } else {
526
+ return "server";
527
+ }
528
+ } else {
529
+ return "client";
530
+ }
531
+ }
532
+
533
+ // src/utils/invokations.ts
534
+
535
+
536
+ function findInvokations(ast, params) {
537
+ const result = [];
538
+ _traverse2.default.call(void 0, ast, {
539
+ ImportDeclaration(path7) {
540
+ if (!params.moduleName.includes(path7.node.source.value)) return;
541
+ const importNames = /* @__PURE__ */ new Map();
542
+ const specifiers = path7.node.specifiers;
543
+ specifiers.forEach((specifier) => {
544
+ if (t3.isImportSpecifier(specifier) && t3.isIdentifier(specifier.imported) && specifier.imported.name === params.functionName) {
545
+ importNames.set(specifier.local.name, true);
546
+ } else if (t3.isImportDefaultSpecifier(specifier) && params.functionName === "default") {
547
+ importNames.set(specifier.local.name, true);
548
+ } else if (t3.isImportNamespaceSpecifier(specifier)) {
549
+ importNames.set(specifier.local.name, "namespace");
550
+ }
551
+ });
552
+ collectCallExpressions(path7, importNames, result, params.functionName);
553
+ }
554
+ });
555
+ return result;
556
+ }
557
+ function collectCallExpressions(path7, importNames, result, functionName) {
558
+ const program = path7.findParent(
559
+ (p) => p.isProgram()
560
+ );
561
+ if (!program) return;
562
+ program.traverse({
563
+ CallExpression(callPath) {
564
+ const callee = callPath.node.callee;
565
+ if (t3.isIdentifier(callee) && importNames.has(callee.name)) {
566
+ result.push(callPath.node);
567
+ } else if (t3.isMemberExpression(callee) && t3.isIdentifier(callee.object) && importNames.get(callee.object.name) === "namespace" && t3.isIdentifier(callee.property) && callee.property.name === functionName) {
568
+ result.push(callPath.node);
569
+ }
570
+ }
571
+ });
572
+ }
573
+
574
+ // src/client-dictionary-loader.ts
575
+
576
+
577
+ // src/_utils.ts
578
+
579
+ var getDictionaryPath = (params) => {
580
+ const absolute = path.default.resolve(
581
+ params.sourceRoot,
582
+ params.lingoDir,
583
+ LCP_DICTIONARY_FILE_NAME
584
+ );
585
+ const rel = path.default.relative(params.relativeFilePath, absolute);
586
+ return rel.split(path.default.sep).join(path.default.posix.sep);
587
+ };
588
+
589
+ // src/utils/create-locale-import-map.ts
590
+
591
+ function createLocaleImportMap(allLocales, dictionaryPath) {
592
+ return t4.objectExpression(
593
+ allLocales.map(
594
+ (locale) => t4.objectProperty(
595
+ t4.stringLiteral(locale),
596
+ t4.arrowFunctionExpression(
597
+ [],
598
+ t4.callExpression(t4.identifier("import"), [
599
+ t4.stringLiteral(`${dictionaryPath}?locale=${locale}`)
600
+ ])
601
+ )
602
+ )
603
+ )
604
+ );
605
+ }
606
+
607
+ // src/client-dictionary-loader.ts
608
+ var clientDictionaryLoaderMutation = createCodeMutation((payload) => {
609
+ const invokations = findInvokations(payload.ast, {
610
+ moduleName: ModuleId.ReactClient,
611
+ functionName: "loadDictionary"
612
+ });
613
+ const allLocales = Array.from(
614
+ /* @__PURE__ */ new Set([payload.params.sourceLocale, ...payload.params.targetLocales])
615
+ );
616
+ for (const invokation of invokations) {
617
+ const internalDictionaryLoader = getOrCreateImport(payload.ast, {
618
+ moduleName: ModuleId.ReactClient,
619
+ exportedName: "loadDictionary_internal"
620
+ });
621
+ if (t5.isIdentifier(invokation.callee)) {
622
+ invokation.callee.name = internalDictionaryLoader.importedName;
623
+ }
624
+ const dictionaryPath = getDictionaryPath({
625
+ sourceRoot: payload.params.sourceRoot,
626
+ lingoDir: payload.params.lingoDir,
627
+ relativeFilePath: payload.relativeFilePath
628
+ });
629
+ const localeImportMap = createLocaleImportMap(allLocales, dictionaryPath);
630
+ invokation.arguments.push(localeImportMap);
631
+ }
632
+ return payload;
633
+ });
634
+
635
+ // src/i18n-directive.ts
636
+ var i18nDirectiveMutation = createCodeMutation((payload) => {
637
+ if (!payload.params.useDirective || hasI18nDirective(payload.ast)) {
638
+ return payload;
639
+ } else {
640
+ return null;
641
+ }
642
+ });
643
+ var i18n_directive_default = i18nDirectiveMutation;
644
+
645
+ // src/jsx-attribute-flag.ts
646
+
647
+
648
+ // src/utils/jsx-attribute-scope.ts
649
+
650
+
651
+ function collectJsxAttributeScopes(node) {
652
+ const result = [];
653
+ _traverse2.default.call(void 0, node, {
654
+ JSXElement(path7) {
655
+ if (!hasJsxAttributeScopeAttribute(path7)) return;
656
+ const localizableAttributes = getJsxAttributeScopeAttribute(path7);
657
+ if (!localizableAttributes) return;
658
+ result.push([path7, localizableAttributes]);
659
+ }
660
+ });
661
+ return result;
662
+ }
663
+ function getJsxAttributeScopes(node) {
664
+ const result = [];
665
+ const LOCALIZABLE_ATTRIBUTES = [
666
+ "title",
667
+ "aria-label",
668
+ "aria-description",
669
+ "alt",
670
+ "label",
671
+ "description",
672
+ "placeholder",
673
+ "content",
674
+ "subtitle"
675
+ ];
676
+ _traverse2.default.call(void 0, node, {
677
+ JSXElement(path7) {
678
+ const openingElement = path7.node.openingElement;
679
+ const elementName = openingElement.name;
680
+ if (!t6.isJSXIdentifier(elementName) || !elementName.name) {
681
+ return;
682
+ }
683
+ const hasAttributeScope = openingElement.attributes.find(
684
+ (attr) => t6.isJSXAttribute(attr) && attr.name.name === "data-jsx-attribute-scope"
685
+ );
686
+ if (hasAttributeScope) {
687
+ return;
688
+ }
689
+ const localizableAttrs = openingElement.attributes.filter(
690
+ (attr) => {
691
+ if (!t6.isJSXAttribute(attr) || !t6.isStringLiteral(attr.value)) {
692
+ return false;
693
+ }
694
+ const name = attr.name.name;
695
+ return typeof name === "string" && LOCALIZABLE_ATTRIBUTES.includes(name);
696
+ }
697
+ ).map((attr) => attr.name.name);
698
+ if (localizableAttrs.length > 0) {
699
+ result.push([path7, localizableAttrs]);
700
+ }
701
+ }
702
+ });
703
+ return result;
704
+ }
705
+ function hasJsxAttributeScopeAttribute(path7) {
706
+ return !!getJsxAttributeScopeAttribute(path7);
707
+ }
708
+ function getJsxAttributeScopeAttribute(path7) {
709
+ const attribute = path7.node.openingElement.attributes.find(
710
+ (attr) => attr.type === "JSXAttribute" && attr.name.name === "data-jsx-attribute-scope"
711
+ );
712
+ if (!attribute || !t6.isJSXAttribute(attribute)) {
713
+ return void 0;
714
+ }
715
+ if (t6.isJSXExpressionContainer(attribute.value) && t6.isArrayExpression(attribute.value.expression)) {
716
+ const arrayExpr = attribute.value.expression;
717
+ return arrayExpr.elements.filter((el) => t6.isStringLiteral(el)).map((el) => el.value);
718
+ }
719
+ if (t6.isStringLiteral(attribute.value)) {
720
+ return [attribute.value.value];
721
+ }
722
+ return void 0;
723
+ }
724
+
725
+ // src/utils/ast-key.ts
726
+
727
+
728
+ function getAstKey(nodePath) {
729
+ const keyChunks = [];
730
+ let current = nodePath;
731
+ while (current) {
732
+ keyChunks.push(current.key);
733
+ current = current.parentPath;
734
+ if (t7.isProgram(_optionalChain([current, 'optionalAccess', _19 => _19.node]))) {
735
+ break;
736
+ }
737
+ }
738
+ const result = keyChunks.reverse().join("/");
739
+ return result;
740
+ }
741
+
742
+ // src/jsx-attribute-flag.ts
743
+ var jsxAttributeFlagMutation = createCodeMutation(
744
+ (payload) => {
745
+ const jsxScopes = getJsxAttributeScopes(payload.ast);
746
+ for (const [jsxScope, attributes] of jsxScopes) {
747
+ const scopeKey = getAstKey(jsxScope);
748
+ jsxScope.node.openingElement.attributes.push(
749
+ t8.jsxAttribute(
750
+ t8.jsxIdentifier("data-jsx-attribute-scope"),
751
+ t8.jsxExpressionContainer(
752
+ t8.arrayExpression(
753
+ attributes.map(
754
+ (attr) => t8.stringLiteral(`${attr}:${scopeKey}-${attr}`)
755
+ )
756
+ )
757
+ )
758
+ )
759
+ );
760
+ }
761
+ return {
762
+ ...payload
763
+ };
764
+ }
765
+ );
766
+ var jsx_attribute_flag_default = jsxAttributeFlagMutation;
767
+
768
+ // src/jsx-attribute-scope-inject.ts
769
+
770
+
771
+ // src/utils/jsx-element.ts
772
+
773
+ function getJsxElementName(nodePath) {
774
+ const openingElement = nodePath.node.openingElement;
775
+ if (t9.isJSXIdentifier(openingElement.name)) {
776
+ return openingElement.name.name;
777
+ }
778
+ return null;
779
+ }
780
+ function getNestedJsxElements(nodePath) {
781
+ const nestedElements = [];
782
+ nodePath.traverse({
783
+ JSXElement(path7) {
784
+ if (path7.node !== nodePath.node) {
785
+ nestedElements.push(path7.node);
786
+ }
787
+ }
788
+ });
789
+ const arrayOfElements = nestedElements.map((element, index) => {
790
+ const param = t9.identifier("children");
791
+ const clonedElement = t9.cloneNode(element);
792
+ clonedElement.children = [t9.jsxExpressionContainer(param)];
793
+ return t9.arrowFunctionExpression(
794
+ [t9.objectPattern([t9.objectProperty(param, param, false, true)])],
795
+ clonedElement
796
+ );
797
+ });
798
+ const result = t9.arrayExpression(arrayOfElements);
799
+ return result;
800
+ }
801
+
802
+ // src/jsx-attribute-scope-inject.ts
803
+ var lingoJsxAttributeScopeInjectMutation = createCodeMutation(
804
+ (payload) => {
805
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
806
+ const jsxAttributeScopes = collectJsxAttributeScopes(payload.ast);
807
+ for (const [jsxScope, attributes] of jsxAttributeScopes) {
808
+ const packagePath = mode === "client" ? ModuleId.ReactClient : ModuleId.ReactRSC;
809
+ const lingoComponentImport = getOrCreateImport(payload.ast, {
810
+ moduleName: packagePath,
811
+ exportedName: "LingoAttributeComponent"
812
+ });
813
+ const originalJsxElementName = getJsxElementName(jsxScope);
814
+ if (!originalJsxElementName) {
815
+ continue;
816
+ }
817
+ jsxScope.node.openingElement.name = t10.jsxIdentifier(
818
+ lingoComponentImport.importedName
819
+ );
820
+ if (jsxScope.node.closingElement) {
821
+ jsxScope.node.closingElement.name = t10.jsxIdentifier(
822
+ lingoComponentImport.importedName
823
+ );
824
+ }
825
+ const as = /^[A-Z]/.test(originalJsxElementName) ? t10.jsxExpressionContainer(t10.identifier(originalJsxElementName)) : t10.stringLiteral(originalJsxElementName);
826
+ jsxScope.node.openingElement.attributes.push(
827
+ t10.jsxAttribute(t10.jsxIdentifier("$attrAs"), as)
828
+ );
829
+ jsxScope.node.openingElement.attributes.push(
830
+ t10.jsxAttribute(
831
+ t10.jsxIdentifier("$fileKey"),
832
+ t10.stringLiteral(payload.relativeFilePath)
833
+ )
834
+ );
835
+ jsxScope.node.openingElement.attributes.push(
836
+ t10.jsxAttribute(
837
+ t10.jsxIdentifier("$attributes"),
838
+ t10.jsxExpressionContainer(
839
+ t10.objectExpression(
840
+ attributes.map((attributeDefinition) => {
841
+ const [attribute, key = ""] = attributeDefinition.split(":");
842
+ return t10.objectProperty(
843
+ t10.stringLiteral(attribute),
844
+ t10.stringLiteral(key)
845
+ );
846
+ })
847
+ )
848
+ )
849
+ )
850
+ );
851
+ if (mode === "server") {
852
+ const loadDictionaryImport = getOrCreateImport(payload.ast, {
853
+ exportedName: "loadDictionary",
854
+ moduleName: ModuleId.ReactRSC
855
+ });
856
+ jsxScope.node.openingElement.attributes.push(
857
+ t10.jsxAttribute(
858
+ t10.jsxIdentifier("$loadDictionary"),
859
+ t10.jsxExpressionContainer(
860
+ t10.arrowFunctionExpression(
861
+ [t10.identifier("locale")],
862
+ t10.callExpression(
863
+ t10.identifier(loadDictionaryImport.importedName),
864
+ [t10.identifier("locale")]
865
+ )
866
+ )
867
+ )
868
+ )
869
+ );
870
+ }
871
+ }
872
+ return payload;
873
+ }
874
+ );
875
+
876
+ // src/lib/lcp/index.ts
877
+
878
+
879
+
880
+ var _dedent = require('dedent'); var _dedent2 = _interopRequireDefault(_dedent);
881
+ var LCP_FILE_NAME = "meta.json";
882
+ var LCP = class _LCP {
883
+ constructor(filePath, data = {
884
+ version: 0.1
885
+ }) {
886
+ this.filePath = filePath;
887
+ this.data = data;
888
+ }
889
+ static ensureFile(params) {
890
+ const filePath = path5.resolve(
891
+ process.cwd(),
892
+ params.sourceRoot,
893
+ params.lingoDir,
894
+ LCP_FILE_NAME
895
+ );
896
+ if (!fs4.existsSync(filePath)) {
897
+ const dir = path5.dirname(filePath);
898
+ if (!fs4.existsSync(dir)) {
899
+ fs4.mkdirSync(dir, { recursive: true });
900
+ }
901
+ fs4.writeFileSync(filePath, "{}");
902
+ console.log(_dedent2.default`
903
+ \n
904
+ ⚠️ Lingo.dev Compiler detected missing meta.json file in lingo directory.
905
+ Please restart the build / watch command to regenerate all Lingo.dev Compiler files.
906
+ `);
907
+ try {
908
+ fs4.rmdirSync(path5.resolve(process.cwd(), ".next"), {
909
+ recursive: true
910
+ });
911
+ } catch (error) {
912
+ }
913
+ process.exit(1);
914
+ }
915
+ }
916
+ static getInstance(params) {
917
+ const filePath = path5.resolve(
918
+ process.cwd(),
919
+ params.sourceRoot,
920
+ params.lingoDir,
921
+ LCP_FILE_NAME
922
+ );
923
+ if (fs4.existsSync(filePath)) {
924
+ return new _LCP(filePath, JSON.parse(fs4.readFileSync(filePath, "utf8")));
925
+ }
926
+ return new _LCP(filePath);
927
+ }
928
+ // wait until LCP file stops updating
929
+ // this ensures all files were transformed before loading / translating dictionaries
930
+ static async ready(params) {
931
+ if (params.isDev) {
932
+ _LCP.ensureFile(params);
933
+ }
934
+ const filePath = path5.resolve(
935
+ process.cwd(),
936
+ params.sourceRoot,
937
+ params.lingoDir,
938
+ LCP_FILE_NAME
939
+ );
940
+ if (fs4.existsSync(filePath)) {
941
+ const stats = fs4.statSync(filePath);
942
+ if (Date.now() - stats.mtimeMs > 1500) {
943
+ return;
944
+ }
945
+ }
946
+ return new Promise((resolve3) => {
947
+ setTimeout(() => {
948
+ _LCP.ready(params).then(resolve3);
949
+ }, 750);
950
+ });
951
+ }
952
+ resetScope(fileKey, scopeKey) {
953
+ if (!_lodash2.default.isObject(
954
+ _lodash2.default.get(this.data, ["files", fileKey])
955
+ )) {
956
+ _lodash2.default.set(this.data, ["files", fileKey], {});
957
+ }
958
+ _lodash2.default.set(
959
+ this.data,
960
+ [
961
+ "files",
962
+ fileKey,
963
+ "scopes",
964
+ scopeKey
965
+ ],
966
+ {}
967
+ );
968
+ return this;
969
+ }
970
+ setScopeType(fileKey, scopeKey, type) {
971
+ return this._setScopeField(fileKey, scopeKey, "type", type);
972
+ }
973
+ setScopeContext(fileKey, scopeKey, context) {
974
+ return this._setScopeField(fileKey, scopeKey, "context", context);
975
+ }
976
+ setScopeHash(fileKey, scopeKey, hash) {
977
+ return this._setScopeField(fileKey, scopeKey, "hash", hash);
978
+ }
979
+ setScopeSkip(fileKey, scopeKey, skip) {
980
+ return this._setScopeField(fileKey, scopeKey, "skip", skip);
981
+ }
982
+ setScopeOverrides(fileKey, scopeKey, overrides) {
983
+ return this._setScopeField(fileKey, scopeKey, "overrides", overrides);
984
+ }
985
+ setScopeContent(fileKey, scopeKey, content) {
986
+ return this._setScopeField(fileKey, scopeKey, "content", content);
987
+ }
988
+ toJSON() {
989
+ const files = _lodash2.default.call(void 0, _optionalChain([this, 'access', _20 => _20.data, 'optionalAccess', _21 => _21.files])).mapValues((file, fileName) => {
990
+ return {
991
+ ...file,
992
+ scopes: _lodash2.default.call(void 0, _optionalChain([file, 'optionalAccess', _22 => _22.scopes])).toPairs().sortBy([0]).fromPairs().value()
993
+ };
994
+ }).toPairs().sortBy([0]).fromPairs().value();
995
+ return { ...this.data, files };
996
+ }
997
+ toString() {
998
+ return JSON.stringify(this.toJSON(), null, 2);
999
+ }
1000
+ save() {
1001
+ const hasChanges = !fs4.existsSync(this.filePath) || fs4.readFileSync(this.filePath, "utf8") !== this.toString();
1002
+ if (hasChanges) {
1003
+ const dir = path5.dirname(this.filePath);
1004
+ if (!fs4.existsSync(dir)) {
1005
+ fs4.mkdirSync(dir, { recursive: true });
1006
+ }
1007
+ fs4.writeFileSync(this.filePath, this.toString());
1008
+ this._triggerLCPReload();
1009
+ }
1010
+ }
1011
+ _triggerLCPReload() {
1012
+ const dir = path5.dirname(this.filePath);
1013
+ const filePath = path5.resolve(dir, LCP_DICTIONARY_FILE_NAME);
1014
+ if (fs4.existsSync(filePath)) {
1015
+ try {
1016
+ const now = Math.floor(Date.now() / 1e3);
1017
+ fs4.utimesSync(filePath, now, now);
1018
+ } catch (error) {
1019
+ if (_optionalChain([error, 'optionalAccess', _23 => _23.code]) === "EINVAL") {
1020
+ console.warn(
1021
+ _dedent2.default`
1022
+ ⚠️ Lingo: Auto-reload disabled - system blocks Node.js timestamp updates.
1023
+ 💡 Fix: Adjust security settings to allow Node.js file modifications.
1024
+ ⚡ Workaround: Manually refresh browser after translation changes.
1025
+ 💬 Need help? Join our Discord: https://lingo.dev/go/discord.
1026
+ `
1027
+ );
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1032
+ _setScopeField(fileKey, scopeKey, field, value) {
1033
+ _lodash2.default.set(
1034
+ this.data,
1035
+ [
1036
+ "files",
1037
+ fileKey,
1038
+ "scopes",
1039
+ scopeKey,
1040
+ field
1041
+ ],
1042
+ value
1043
+ );
1044
+ return this;
1045
+ }
1046
+ };
1047
+
1048
+ // src/utils/hash.ts
1049
+ var _objecthash = require('object-hash');
1050
+ function getJsxElementHash(nodePath) {
1051
+ if (!nodePath.node) {
1052
+ return "";
1053
+ }
1054
+ const content = nodePath.node.children.map((child) => child.value).join("");
1055
+ const result = _objecthash.MD5.call(void 0, content);
1056
+ return result;
1057
+ }
1058
+ function getJsxAttributeValueHash(attributeValue) {
1059
+ if (!attributeValue) {
1060
+ return "";
1061
+ }
1062
+ const result = _objecthash.MD5.call(void 0, attributeValue);
1063
+ return result;
1064
+ }
1065
+
1066
+ // src/jsx-attribute-scopes-export.ts
1067
+
1068
+ function jsxAttributeScopesExportMutation(payload) {
1069
+ const attributeScopes = collectJsxAttributeScopes(payload.ast);
1070
+ if (_lodash2.default.isEmpty(attributeScopes)) {
1071
+ return payload;
1072
+ }
1073
+ const lcp = LCP.getInstance({
1074
+ sourceRoot: payload.params.sourceRoot,
1075
+ lingoDir: payload.params.lingoDir
1076
+ });
1077
+ for (const [scope, attributes] of attributeScopes) {
1078
+ for (const attributeDefinition of attributes) {
1079
+ const [attribute, scopeKey] = attributeDefinition.split(":");
1080
+ lcp.resetScope(payload.relativeFilePath, scopeKey);
1081
+ const attributeValue = getJsxAttributeValue(scope, attribute);
1082
+ if (!attributeValue) {
1083
+ continue;
1084
+ }
1085
+ lcp.setScopeType(payload.relativeFilePath, scopeKey, "attribute");
1086
+ const hash = getJsxAttributeValueHash(String(attributeValue));
1087
+ lcp.setScopeHash(payload.relativeFilePath, scopeKey, hash);
1088
+ lcp.setScopeContext(payload.relativeFilePath, scopeKey, "");
1089
+ lcp.setScopeSkip(payload.relativeFilePath, scopeKey, false);
1090
+ lcp.setScopeOverrides(payload.relativeFilePath, scopeKey, {});
1091
+ lcp.setScopeContent(
1092
+ payload.relativeFilePath,
1093
+ scopeKey,
1094
+ String(attributeValue)
1095
+ );
1096
+ }
1097
+ }
1098
+ lcp.save();
1099
+ return payload;
1100
+ }
1101
+
1102
+ // src/jsx-fragment.ts
1103
+
1104
+
1105
+ function jsxFragmentMutation(payload) {
1106
+ const { ast } = payload;
1107
+ let foundFragments = false;
1108
+ let fragmentImportName = null;
1109
+ _traverse2.default.call(void 0, ast, {
1110
+ ImportDeclaration(path7) {
1111
+ if (path7.node.source.value !== "react") return;
1112
+ for (const specifier of path7.node.specifiers) {
1113
+ if (t11.isImportSpecifier(specifier) && t11.isIdentifier(specifier.imported) && specifier.imported.name === "Fragment") {
1114
+ fragmentImportName = specifier.local.name;
1115
+ path7.stop();
1116
+ }
1117
+ }
1118
+ }
1119
+ });
1120
+ _traverse2.default.call(void 0, ast, {
1121
+ JSXFragment(path7) {
1122
+ foundFragments = true;
1123
+ if (!fragmentImportName) {
1124
+ const result = getOrCreateImport(ast, {
1125
+ exportedName: "Fragment",
1126
+ moduleName: ["react"]
1127
+ });
1128
+ fragmentImportName = result.importedName;
1129
+ }
1130
+ const fragmentElement = t11.jsxElement(
1131
+ t11.jsxOpeningElement(t11.jsxIdentifier(fragmentImportName), [], false),
1132
+ t11.jsxClosingElement(t11.jsxIdentifier(fragmentImportName)),
1133
+ path7.node.children,
1134
+ false
1135
+ );
1136
+ path7.replaceWith(fragmentElement);
1137
+ }
1138
+ });
1139
+ return payload;
1140
+ }
1141
+
1142
+ // src/jsx-html-lang.ts
1143
+
1144
+
1145
+ var jsxHtmlLangMutation = createCodeMutation((payload) => {
1146
+ _traverse2.default.call(void 0, payload.ast, {
1147
+ JSXElement: (path7) => {
1148
+ if (_optionalChain([getJsxElementName, 'call', _24 => _24(path7), 'optionalAccess', _25 => _25.toLowerCase, 'call', _26 => _26()]) === "html") {
1149
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
1150
+ const packagePath = mode === "client" ? ModuleId.ReactClient : ModuleId.ReactRSC;
1151
+ const lingoHtmlComponentImport = getOrCreateImport(payload.ast, {
1152
+ moduleName: packagePath,
1153
+ exportedName: "LingoHtmlComponent"
1154
+ });
1155
+ path7.node.openingElement.name = t12.jsxIdentifier(
1156
+ lingoHtmlComponentImport.importedName
1157
+ );
1158
+ if (path7.node.closingElement) {
1159
+ path7.node.closingElement.name = t12.jsxIdentifier(
1160
+ lingoHtmlComponentImport.importedName
1161
+ );
1162
+ }
1163
+ path7.skip();
1164
+ }
1165
+ }
1166
+ });
1167
+ return payload;
1168
+ });
1169
+
1170
+ // src/jsx-provider.ts
1171
+
1172
+
1173
+ var jsxProviderMutation = createCodeMutation((payload) => {
1174
+ _traverse2.default.call(void 0, payload.ast, {
1175
+ JSXElement: (path7) => {
1176
+ if (_optionalChain([getJsxElementName, 'call', _27 => _27(path7), 'optionalAccess', _28 => _28.toLowerCase, 'call', _29 => _29()]) === "html") {
1177
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
1178
+ if (mode === "client") {
1179
+ return;
1180
+ }
1181
+ const lingoProviderImport = getOrCreateImport(payload.ast, {
1182
+ moduleName: ModuleId.ReactRSC,
1183
+ exportedName: "LingoProvider"
1184
+ });
1185
+ const loadDictionaryImport = getOrCreateImport(payload.ast, {
1186
+ moduleName: ModuleId.ReactRSC,
1187
+ exportedName: "loadDictionary"
1188
+ });
1189
+ const loadDictionaryArrow = t13.arrowFunctionExpression(
1190
+ [t13.identifier("locale")],
1191
+ t13.callExpression(t13.identifier(loadDictionaryImport.importedName), [
1192
+ t13.identifier("locale")
1193
+ ])
1194
+ );
1195
+ const providerProps = [
1196
+ t13.jsxAttribute(
1197
+ t13.jsxIdentifier("loadDictionary"),
1198
+ t13.jsxExpressionContainer(loadDictionaryArrow)
1199
+ )
1200
+ ];
1201
+ const provider = t13.jsxElement(
1202
+ t13.jsxOpeningElement(
1203
+ t13.jsxIdentifier(lingoProviderImport.importedName),
1204
+ providerProps,
1205
+ false
1206
+ ),
1207
+ t13.jsxClosingElement(
1208
+ t13.jsxIdentifier(lingoProviderImport.importedName)
1209
+ ),
1210
+ [path7.node],
1211
+ false
1212
+ );
1213
+ path7.replaceWith(provider);
1214
+ path7.skip();
1215
+ }
1216
+ }
1217
+ });
1218
+ return payload;
1219
+ });
1220
+ var jsx_provider_default = jsxProviderMutation;
1221
+
1222
+ // src/jsx-remove-attributes.ts
1223
+
1224
+
1225
+ var jsxRemoveAttributesMutation = createCodeMutation(
1226
+ (payload) => {
1227
+ const ATTRIBUTES_TO_REMOVE = [
1228
+ "data-jsx-root",
1229
+ "data-jsx-scope",
1230
+ "data-jsx-attribute-scope"
1231
+ ];
1232
+ _traverse2.default.call(void 0, payload.ast, {
1233
+ JSXElement(path7) {
1234
+ const openingElement = path7.node.openingElement;
1235
+ openingElement.attributes = openingElement.attributes.filter((attr) => {
1236
+ const removeAttr = t14.isJSXAttribute(attr) && t14.isJSXIdentifier(attr.name) && ATTRIBUTES_TO_REMOVE.includes(attr.name.name);
1237
+ return !removeAttr;
1238
+ });
1239
+ }
1240
+ });
1241
+ return {
1242
+ ...payload
1243
+ };
1244
+ }
1245
+ );
1246
+
1247
+ // src/jsx-root-flag.ts
1248
+
1249
+ var jsxRootFlagMutation = createCodeMutation((payload) => {
1250
+ const jsxRoots = getJsxRoots(payload.ast);
1251
+ for (const jsxElementPath of jsxRoots) {
1252
+ jsxElementPath.node.openingElement.attributes.push(
1253
+ t15.jsxAttribute(t15.jsxIdentifier("data-jsx-root"), null)
1254
+ );
1255
+ }
1256
+ return {
1257
+ ...payload
1258
+ };
1259
+ });
1260
+ var jsx_root_flag_default = jsxRootFlagMutation;
1261
+
1262
+ // src/jsx-scope-flag.ts
1263
+
1264
+
1265
+ // src/utils/jsx-scope.ts
1266
+
1267
+
1268
+ function collectJsxScopes(ast) {
1269
+ const jsxScopes = [];
1270
+ _traverse2.default.call(void 0, ast, {
1271
+ JSXElement: (path7) => {
1272
+ if (!hasJsxScopeAttribute(path7)) return;
1273
+ path7.skip();
1274
+ jsxScopes.push(path7);
1275
+ }
1276
+ });
1277
+ return jsxScopes;
1278
+ }
1279
+ function getJsxScopes(node) {
1280
+ const result = [];
1281
+ _traverse2.default.call(void 0, node, {
1282
+ JSXElement(path7) {
1283
+ if (getJsxElementName(path7) === "LingoProvider") {
1284
+ return;
1285
+ }
1286
+ const hasNonEmptyTextSiblings = path7.getAllPrevSiblings().concat(path7.getAllNextSiblings()).some(
1287
+ (sibling) => t16.isJSXText(sibling.node) && _optionalChain([sibling, 'access', _30 => _30.node, 'access', _31 => _31.value, 'optionalAccess', _32 => _32.trim, 'call', _33 => _33()]) !== ""
1288
+ );
1289
+ if (hasNonEmptyTextSiblings) {
1290
+ return;
1291
+ }
1292
+ const hasNonEmptyTextChild = path7.get("children").some(
1293
+ (child) => t16.isJSXText(child.node) && _optionalChain([child, 'access', _34 => _34.node, 'access', _35 => _35.value, 'optionalAccess', _36 => _36.trim, 'call', _37 => _37()]) !== ""
1294
+ );
1295
+ if (hasNonEmptyTextChild) {
1296
+ result.push(path7);
1297
+ path7.skip();
1298
+ }
1299
+ }
1300
+ });
1301
+ return result;
1302
+ }
1303
+ function hasJsxScopeAttribute(path7) {
1304
+ return !!getJsxScopeAttribute(path7);
1305
+ }
1306
+ function getJsxScopeAttribute(path7) {
1307
+ const attribute = path7.node.openingElement.attributes.find(
1308
+ (attr) => attr.type === "JSXAttribute" && attr.name.name === "data-jsx-scope"
1309
+ );
1310
+ return attribute && t16.isJSXAttribute(attribute) && t16.isStringLiteral(attribute.value) ? attribute.value.value : void 0;
1311
+ }
1312
+
1313
+ // src/jsx-scope-flag.ts
1314
+ var jsxScopeFlagMutation = createCodeMutation((payload) => {
1315
+ const jsxScopes = getJsxScopes(payload.ast);
1316
+ for (const jsxScope of jsxScopes) {
1317
+ jsxScope.node.openingElement.attributes.push(
1318
+ t17.jsxAttribute(
1319
+ t17.jsxIdentifier("data-jsx-scope"),
1320
+ t17.stringLiteral(getAstKey(jsxScope))
1321
+ )
1322
+ );
1323
+ }
1324
+ return {
1325
+ ...payload
1326
+ };
1327
+ });
1328
+ var jsx_scope_flag_default = jsxScopeFlagMutation;
1329
+
1330
+ // src/jsx-scope-inject.ts
1331
+
1332
+
1333
+ // src/utils/jsx-variables.ts
1334
+
1335
+ var getJsxVariables = (nodePath) => {
1336
+ const variables = /* @__PURE__ */ new Set();
1337
+ nodePath.traverse({
1338
+ JSXOpeningElement(path7) {
1339
+ path7.skip();
1340
+ },
1341
+ JSXExpressionContainer(path7) {
1342
+ if (t18.isIdentifier(path7.node.expression)) {
1343
+ variables.add(path7.node.expression.name);
1344
+ } else if (t18.isMemberExpression(path7.node.expression)) {
1345
+ let current = path7.node.expression;
1346
+ const parts = [];
1347
+ while (t18.isMemberExpression(current)) {
1348
+ if (t18.isIdentifier(current.property)) {
1349
+ if (current.computed) {
1350
+ parts.unshift(`[${current.property.name}]`);
1351
+ } else {
1352
+ parts.unshift(current.property.name);
1353
+ }
1354
+ }
1355
+ current = current.object;
1356
+ }
1357
+ if (t18.isIdentifier(current)) {
1358
+ parts.unshift(current.name);
1359
+ variables.add(parts.join(".").replaceAll(".[", "["));
1360
+ }
1361
+ }
1362
+ path7.skip();
1363
+ }
1364
+ });
1365
+ const properties = Array.from(variables).map(
1366
+ (name) => t18.objectProperty(t18.stringLiteral(name), t18.identifier(name))
1367
+ );
1368
+ const result = t18.objectExpression(properties);
1369
+ return result;
1370
+ };
1371
+
1372
+ // src/utils/jsx-functions.ts
1373
+
1374
+ var getJsxFunctions = (nodePath) => {
1375
+ const functions = /* @__PURE__ */ new Map();
1376
+ let fnCounter = 0;
1377
+ nodePath.traverse({
1378
+ JSXOpeningElement(path7) {
1379
+ path7.skip();
1380
+ },
1381
+ JSXExpressionContainer(path7) {
1382
+ if (t19.isCallExpression(path7.node.expression)) {
1383
+ let key = "";
1384
+ if (t19.isIdentifier(path7.node.expression.callee)) {
1385
+ key = `${path7.node.expression.callee.name}`;
1386
+ } else if (t19.isMemberExpression(path7.node.expression.callee)) {
1387
+ let firstCallee = path7.node.expression.callee;
1388
+ while (t19.isMemberExpression(firstCallee) && t19.isCallExpression(firstCallee.object)) {
1389
+ firstCallee = firstCallee.object.callee;
1390
+ }
1391
+ let current = firstCallee;
1392
+ const parts = [];
1393
+ while (t19.isMemberExpression(current)) {
1394
+ if (t19.isIdentifier(current.property)) {
1395
+ parts.unshift(current.property.name);
1396
+ }
1397
+ current = current.object;
1398
+ }
1399
+ if (t19.isIdentifier(current)) {
1400
+ parts.unshift(current.name);
1401
+ }
1402
+ if (t19.isMemberExpression(firstCallee) && t19.isNewExpression(firstCallee.object) && t19.isIdentifier(firstCallee.object.callee)) {
1403
+ parts.unshift(firstCallee.object.callee.name);
1404
+ }
1405
+ key = parts.join(".");
1406
+ }
1407
+ const existing = _nullishCoalesce(functions.get(key), () => ( []));
1408
+ functions.set(key, [...existing, path7.node.expression]);
1409
+ fnCounter++;
1410
+ }
1411
+ path7.skip();
1412
+ }
1413
+ });
1414
+ const properties = Array.from(functions.entries()).map(
1415
+ ([name, callExpr]) => t19.objectProperty(t19.stringLiteral(name), t19.arrayExpression(callExpr))
1416
+ );
1417
+ return t19.objectExpression(properties);
1418
+ };
1419
+
1420
+ // src/utils/jsx-expressions.ts
1421
+
1422
+ var getJsxExpressions = (nodePath) => {
1423
+ const expressions = [];
1424
+ nodePath.traverse({
1425
+ JSXOpeningElement(path7) {
1426
+ path7.skip();
1427
+ },
1428
+ JSXExpressionContainer(path7) {
1429
+ const expr = path7.node.expression;
1430
+ if (!t20.isJSXEmptyExpression(expr) && !t20.isIdentifier(expr) && !t20.isMemberExpression(expr) && !t20.isCallExpression(expr) && !(t20.isStringLiteral(expr) && expr.value === " ")) {
1431
+ expressions.push(expr);
1432
+ }
1433
+ path7.skip();
1434
+ }
1435
+ });
1436
+ return t20.arrayExpression(expressions);
1437
+ };
1438
+
1439
+ // src/jsx-scope-inject.ts
1440
+ var lingoJsxScopeInjectMutation = createCodeMutation((payload) => {
1441
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
1442
+ const jsxScopes = collectJsxScopes(payload.ast);
1443
+ for (const jsxScope of jsxScopes) {
1444
+ const skip = getJsxAttributeValue(jsxScope, "data-lingo-skip");
1445
+ if (skip) {
1446
+ continue;
1447
+ }
1448
+ const packagePath = mode === "client" ? ModuleId.ReactClient : ModuleId.ReactRSC;
1449
+ const lingoComponentImport = getOrCreateImport(payload.ast, {
1450
+ moduleName: packagePath,
1451
+ exportedName: "LingoComponent"
1452
+ });
1453
+ const originalJsxElementName = getJsxElementName(jsxScope);
1454
+ if (!originalJsxElementName) {
1455
+ continue;
1456
+ }
1457
+ const originalAttributes = jsxScope.node.openingElement.attributes.slice();
1458
+ const as = /^[A-Z]/.test(originalJsxElementName) ? t21.jsxExpressionContainer(t21.identifier(originalJsxElementName)) : t21.stringLiteral(originalJsxElementName);
1459
+ originalAttributes.push(t21.jsxAttribute(t21.jsxIdentifier("$as"), as));
1460
+ originalAttributes.push(
1461
+ t21.jsxAttribute(
1462
+ t21.jsxIdentifier("$fileKey"),
1463
+ t21.stringLiteral(payload.relativeFilePath)
1464
+ )
1465
+ );
1466
+ originalAttributes.push(
1467
+ t21.jsxAttribute(
1468
+ t21.jsxIdentifier("$entryKey"),
1469
+ t21.stringLiteral(getJsxScopeAttribute(jsxScope))
1470
+ )
1471
+ );
1472
+ const $variables = getJsxVariables(jsxScope);
1473
+ if ($variables.properties.length > 0) {
1474
+ originalAttributes.push(
1475
+ t21.jsxAttribute(
1476
+ t21.jsxIdentifier("$variables"),
1477
+ t21.jsxExpressionContainer($variables)
1478
+ )
1479
+ );
1480
+ }
1481
+ const $elements = getNestedJsxElements(jsxScope);
1482
+ if ($elements.elements.length > 0) {
1483
+ originalAttributes.push(
1484
+ t21.jsxAttribute(
1485
+ t21.jsxIdentifier("$elements"),
1486
+ t21.jsxExpressionContainer($elements)
1487
+ )
1488
+ );
1489
+ }
1490
+ const $functions = getJsxFunctions(jsxScope);
1491
+ if ($functions.properties.length > 0) {
1492
+ originalAttributes.push(
1493
+ t21.jsxAttribute(
1494
+ t21.jsxIdentifier("$functions"),
1495
+ t21.jsxExpressionContainer($functions)
1496
+ )
1497
+ );
1498
+ }
1499
+ const $expressions = getJsxExpressions(jsxScope);
1500
+ if ($expressions.elements.length > 0) {
1501
+ originalAttributes.push(
1502
+ t21.jsxAttribute(
1503
+ t21.jsxIdentifier("$expressions"),
1504
+ t21.jsxExpressionContainer($expressions)
1505
+ )
1506
+ );
1507
+ }
1508
+ if (mode === "server") {
1509
+ const loadDictionaryImport = getOrCreateImport(payload.ast, {
1510
+ exportedName: "loadDictionary",
1511
+ moduleName: ModuleId.ReactRSC
1512
+ });
1513
+ originalAttributes.push(
1514
+ t21.jsxAttribute(
1515
+ t21.jsxIdentifier("$loadDictionary"),
1516
+ t21.jsxExpressionContainer(
1517
+ t21.arrowFunctionExpression(
1518
+ [t21.identifier("locale")],
1519
+ t21.callExpression(
1520
+ t21.identifier(loadDictionaryImport.importedName),
1521
+ [t21.identifier("locale")]
1522
+ )
1523
+ )
1524
+ )
1525
+ )
1526
+ );
1527
+ }
1528
+ const newNode = t21.jsxElement(
1529
+ t21.jsxOpeningElement(
1530
+ t21.jsxIdentifier(lingoComponentImport.importedName),
1531
+ originalAttributes,
1532
+ true
1533
+ // selfClosing
1534
+ ),
1535
+ null,
1536
+ // no closing element
1537
+ [],
1538
+ // no children
1539
+ true
1540
+ // selfClosing
1541
+ );
1542
+ jsxScope.replaceWith(newNode);
1543
+ }
1544
+ return payload;
1545
+ });
1546
+
1547
+ // src/jsx-scopes-export.ts
1548
+
1549
+
1550
+ // src/utils/jsx-content.ts
1551
+
1552
+
1553
+ var WHITESPACE_PLACEHOLDER = "[lingo-whitespace-placeholder]";
1554
+ function extractJsxContent(nodePath, replaceWhitespacePlaceholders = true) {
1555
+ const chunks = [];
1556
+ nodePath.traverse({
1557
+ JSXElement(path7) {
1558
+ if (path7.parent === nodePath.node) {
1559
+ const content = extractJsxContent(path7, false);
1560
+ const name = getJsxElementName(path7);
1561
+ chunks.push(`<element:${name}>${content}</element:${name}>`);
1562
+ path7.skip();
1563
+ }
1564
+ },
1565
+ JSXText(path7) {
1566
+ chunks.push(path7.node.value);
1567
+ },
1568
+ JSXExpressionContainer(path7) {
1569
+ if (path7.parent !== nodePath.node) {
1570
+ return;
1571
+ }
1572
+ const expr = path7.node.expression;
1573
+ if (t22.isCallExpression(expr)) {
1574
+ let key = "";
1575
+ if (t22.isIdentifier(expr.callee)) {
1576
+ key = `${expr.callee.name}`;
1577
+ } else if (t22.isMemberExpression(expr.callee)) {
1578
+ let firstCallee = expr.callee;
1579
+ while (t22.isMemberExpression(firstCallee) && t22.isCallExpression(firstCallee.object)) {
1580
+ firstCallee = firstCallee.object.callee;
1581
+ }
1582
+ let current = firstCallee;
1583
+ const parts = [];
1584
+ while (t22.isMemberExpression(current)) {
1585
+ if (t22.isIdentifier(current.property)) {
1586
+ parts.unshift(current.property.name);
1587
+ }
1588
+ current = current.object;
1589
+ }
1590
+ if (t22.isIdentifier(current)) {
1591
+ parts.unshift(current.name);
1592
+ }
1593
+ if (t22.isMemberExpression(firstCallee) && t22.isNewExpression(firstCallee.object) && t22.isIdentifier(firstCallee.object.callee)) {
1594
+ parts.unshift(firstCallee.object.callee.name);
1595
+ }
1596
+ key = parts.join(".");
1597
+ }
1598
+ chunks.push(`<function:${key}/>`);
1599
+ } else if (t22.isIdentifier(expr)) {
1600
+ chunks.push(`{${expr.name}}`);
1601
+ } else if (t22.isMemberExpression(expr)) {
1602
+ let current = expr;
1603
+ const parts = [];
1604
+ while (t22.isMemberExpression(current)) {
1605
+ if (t22.isIdentifier(current.property)) {
1606
+ if (current.computed) {
1607
+ parts.unshift(`[${current.property.name}]`);
1608
+ } else {
1609
+ parts.unshift(current.property.name);
1610
+ }
1611
+ }
1612
+ current = current.object;
1613
+ }
1614
+ if (t22.isIdentifier(current)) {
1615
+ parts.unshift(current.name);
1616
+ chunks.push(`{${parts.join(".").replaceAll(".[", "[")}}`);
1617
+ }
1618
+ } else if (isWhitespace(path7)) {
1619
+ chunks.push(WHITESPACE_PLACEHOLDER);
1620
+ } else if (isExpression2(path7)) {
1621
+ chunks.push("<expression/>");
1622
+ }
1623
+ path7.skip();
1624
+ }
1625
+ });
1626
+ const result = chunks.join("");
1627
+ const normalized = normalizeJsxWhitespace(result);
1628
+ if (replaceWhitespacePlaceholders) {
1629
+ return normalized.replaceAll(WHITESPACE_PLACEHOLDER, " ");
1630
+ }
1631
+ return normalized;
1632
+ }
1633
+ var compilerProps = ["data-jsx-attribute-scope", "data-jsx-scope"];
1634
+ function isExpression2(nodePath) {
1635
+ const isCompilerExpression = !_lodash2.default.isArray(nodePath.container) && t22.isJSXAttribute(nodePath.container) && t22.isJSXIdentifier(nodePath.container.name) && compilerProps.includes(nodePath.container.name.name);
1636
+ return !isCompilerExpression && !t22.isJSXEmptyExpression(nodePath.node.expression);
1637
+ }
1638
+ function isWhitespace(nodePath) {
1639
+ const expr = nodePath.node.expression;
1640
+ return t22.isStringLiteral(expr) && expr.value === " ";
1641
+ }
1642
+ function normalizeJsxWhitespace(input) {
1643
+ const lines = input.split("\n");
1644
+ let result = "";
1645
+ for (let i = 0; i < lines.length; i++) {
1646
+ const line = lines[i].trim();
1647
+ if (line === "") continue;
1648
+ if (i > 0 && (line.startsWith("<element:") || line.startsWith("<function:") || line.startsWith("{") || line.startsWith("<expression/>"))) {
1649
+ result += line;
1650
+ } else {
1651
+ if (result && !result.endsWith(" ")) result += " ";
1652
+ result += line;
1653
+ }
1654
+ }
1655
+ result = result.replace(/\s+/g, " ");
1656
+ return result.trim();
1657
+ }
1658
+
1659
+ // src/jsx-scopes-export.ts
1660
+ function jsxScopesExportMutation(payload) {
1661
+ const scopes = collectJsxScopes(payload.ast);
1662
+ if (_lodash2.default.isEmpty(scopes)) {
1663
+ return payload;
1664
+ }
1665
+ const lcp = LCP.getInstance({
1666
+ sourceRoot: payload.params.sourceRoot,
1667
+ lingoDir: payload.params.lingoDir
1668
+ });
1669
+ for (const scope of scopes) {
1670
+ const scopeKey = getAstKey(scope);
1671
+ lcp.resetScope(payload.relativeFilePath, scopeKey);
1672
+ lcp.setScopeType(payload.relativeFilePath, scopeKey, "element");
1673
+ const hash = getJsxElementHash(scope);
1674
+ lcp.setScopeHash(payload.relativeFilePath, scopeKey, hash);
1675
+ const context = getJsxAttributeValue(scope, "data-lingo-context");
1676
+ lcp.setScopeContext(
1677
+ payload.relativeFilePath,
1678
+ scopeKey,
1679
+ String(context || "")
1680
+ );
1681
+ const skip = getJsxAttributeValue(scope, "data-lingo-skip");
1682
+ lcp.setScopeSkip(
1683
+ payload.relativeFilePath,
1684
+ scopeKey,
1685
+ Boolean(skip || false)
1686
+ );
1687
+ const attributesMap = getJsxAttributesMap(scope);
1688
+ const overrides = _lodash2.default.chain(attributesMap).entries().filter(
1689
+ ([attributeKey]) => attributeKey.startsWith("data-lingo-override-")
1690
+ ).map(([k, v]) => [k.split("data-lingo-override-")[1], v]).filter(([k]) => !!k).filter(([, v]) => !!v).fromPairs().value();
1691
+ lcp.setScopeOverrides(payload.relativeFilePath, scopeKey, overrides);
1692
+ const content = extractJsxContent(scope);
1693
+ lcp.setScopeContent(payload.relativeFilePath, scopeKey, content);
1694
+ }
1695
+ lcp.save();
1696
+ return payload;
1697
+ }
1698
+
1699
+ // src/lib/lcp/server.ts
1700
+
1701
+
1702
+ // src/lib/lcp/api/index.ts
1703
+ var _groq = require('@ai-sdk/groq');
1704
+ var _google = require('@ai-sdk/google');
1705
+ var _aisdkprovider = require('@openrouter/ai-sdk-provider');
1706
+ var _ollamaaiprovider = require('ollama-ai-provider');
1707
+ var _ai = require('ai');
1708
+ var __sdk = require('@lingo.dev/_sdk');
1709
+
1710
+
1711
+ // src/lib/lcp/api/prompt.ts
1712
+ var prompt_default = (args) => {
1713
+ return getUserSystemPrompt(args) || getBuiltInSystemPrompt(args);
1714
+ };
1715
+ function getUserSystemPrompt(args) {
1716
+ const userPrompt = _optionalChain([args, 'access', _38 => _38.prompt, 'optionalAccess', _39 => _39.trim, 'call', _40 => _40(), 'optionalAccess', _41 => _41.replace, 'call', _42 => _42("{SOURCE_LOCALE}", args.sourceLocale), 'optionalAccess', _43 => _43.replace, 'call', _44 => _44("{TARGET_LOCALE}", args.targetLocale)]);
1717
+ if (userPrompt) {
1718
+ console.log("\u2728 Compiler is using user-defined prompt.");
1719
+ return userPrompt;
1720
+ }
1721
+ return void 0;
1722
+ }
1723
+ function getBuiltInSystemPrompt(args) {
1724
+ return `
1725
+ # Identity
1726
+
1727
+ You are an advanced AI localization engine. You do state-of-the-art localization for software products.
1728
+ Your task is to localize pieces of data from one locale to another locale.
1729
+ You always consider context, cultural nuances of source and target locales, and specific localization requirements.
1730
+ You replicate the meaning, intent, style, tone, and purpose of the original data.
1731
+
1732
+ ## Setup
1733
+
1734
+ Source language (locale code): ${args.sourceLocale}
1735
+ Target language (locale code): ${args.targetLocale}
1736
+
1737
+ ## Guidelines
1738
+
1739
+ Follow these guidelines for translation:
1740
+
1741
+ 1. Analyze the source text to understand its overall context and purpose
1742
+ 2. Translate the meaning and intent rather than word-for-word translation
1743
+ 3. Rephrase and restructure sentences to sound natural and fluent in the target language
1744
+ 4. Adapt idiomatic expressions and cultural references for the target audience
1745
+ 5. Maintain the style and tone of the source text
1746
+ 6. You must produce valid UTF-8 encoded output
1747
+ 7. YOU MUST ONLY PRODUCE VALID XML.
1748
+
1749
+ ## Special Instructions
1750
+
1751
+ Do not localize any of these technical elements:
1752
+ - Variables like {variable}, {variable.key}, {data[type]}
1753
+ - Expressions like <expression/>
1754
+ - Functions like <function:value/>, <function:getDisplayName/>
1755
+ - Elements like <element:strong>, </element:strong>, <element:LuPlus>, </element:LuPlus>, <element:LuSparkles>, </element:LuSparkles>
1756
+
1757
+ Remember, you are a context-aware multilingual assistant helping international companies.
1758
+ Your goal is to perform state-of-the-art localization for software products and content.
1759
+ `;
1760
+ }
1761
+
1762
+ // src/lib/lcp/api/xml2obj.ts
1763
+ var _fastxmlparser = require('fast-xml-parser');
1764
+
1765
+ var TAG_OBJECT = "object";
1766
+ var TAG_ARRAY = "array";
1767
+ var TAG_VALUE = "value";
1768
+ function _toGenericNode(value, key) {
1769
+ if (_lodash2.default.isArray(value)) {
1770
+ const children = _lodash2.default.map(value, (item) => _toGenericNode(item));
1771
+ return {
1772
+ [TAG_ARRAY]: {
1773
+ ...key ? { key } : {},
1774
+ ..._groupChildren(children)
1775
+ }
1776
+ };
1777
+ }
1778
+ if (_lodash2.default.isPlainObject(value)) {
1779
+ const children = _lodash2.default.map(
1780
+ Object.entries(value),
1781
+ ([k, v]) => _toGenericNode(v, k)
1782
+ );
1783
+ return {
1784
+ [TAG_OBJECT]: {
1785
+ ...key ? { key } : {},
1786
+ ..._groupChildren(children)
1787
+ }
1788
+ };
1789
+ }
1790
+ return {
1791
+ [TAG_VALUE]: {
1792
+ ...key ? { key } : {},
1793
+ "#text": _nullishCoalesce(value, () => ( ""))
1794
+ }
1795
+ };
1796
+ }
1797
+ function _groupChildren(nodes) {
1798
+ return _lodash2.default.call(void 0, nodes).groupBy((node) => Object.keys(node)[0]).mapValues((arr) => _lodash2.default.map(arr, (n) => n[Object.keys(n)[0]])).value();
1799
+ }
1800
+ function _fromGenericNode(tag, data) {
1801
+ if (tag === TAG_VALUE) {
1802
+ if (_lodash2.default.isPlainObject(data)) {
1803
+ return _lodash2.default.get(data, "#text", "");
1804
+ }
1805
+ return _nullishCoalesce(data, () => ( ""));
1806
+ }
1807
+ if (tag === TAG_ARRAY) {
1808
+ const result = [];
1809
+ _lodash2.default.forEach([TAG_VALUE, TAG_OBJECT, TAG_ARRAY], (childTag) => {
1810
+ const childNodes = _lodash2.default.castArray(_lodash2.default.get(data, childTag, []));
1811
+ _lodash2.default.forEach(childNodes, (child) => {
1812
+ result.push(_fromGenericNode(childTag, child));
1813
+ });
1814
+ });
1815
+ return result;
1816
+ }
1817
+ const obj = {};
1818
+ _lodash2.default.forEach([TAG_VALUE, TAG_OBJECT, TAG_ARRAY], (childTag) => {
1819
+ const childNodes = _lodash2.default.castArray(_lodash2.default.get(data, childTag, []));
1820
+ _lodash2.default.forEach(childNodes, (child) => {
1821
+ const key = _lodash2.default.get(child, "key", "");
1822
+ obj[key] = _fromGenericNode(childTag, child);
1823
+ });
1824
+ });
1825
+ return obj;
1826
+ }
1827
+ function obj2xml(obj) {
1828
+ const rootNode = _toGenericNode(obj)[TAG_OBJECT];
1829
+ const builder = new (0, _fastxmlparser.XMLBuilder)({
1830
+ ignoreAttributes: false,
1831
+ attributeNamePrefix: "",
1832
+ format: true,
1833
+ suppressEmptyNode: true
1834
+ });
1835
+ return builder.build({ [TAG_OBJECT]: rootNode });
1836
+ }
1837
+ function xml2obj(xml) {
1838
+ const parser2 = new (0, _fastxmlparser.XMLParser)({
1839
+ ignoreAttributes: false,
1840
+ attributeNamePrefix: "",
1841
+ parseTagValue: true,
1842
+ parseAttributeValue: false,
1843
+ processEntities: true,
1844
+ isArray: (name) => [TAG_VALUE, TAG_ARRAY, TAG_OBJECT].includes(name)
1845
+ });
1846
+ const parsed = parser2.parse(xml);
1847
+ const withoutDeclaration = _lodash2.default.omit(parsed, "?xml");
1848
+ const rootTag = Object.keys(withoutDeclaration)[0];
1849
+ const rootNode = _lodash2.default.castArray(withoutDeclaration[rootTag])[0];
1850
+ return _fromGenericNode(rootTag, rootNode);
1851
+ }
1852
+
1853
+ // src/lib/lcp/api/shots.ts
1854
+ var shots_default = [
1855
+ // Shot #1
1856
+ [
1857
+ {
1858
+ version: 0.1,
1859
+ locale: "en",
1860
+ files: {
1861
+ "demo-app/my-custom-header.tsx": {
1862
+ entries: {
1863
+ "1z2x3c4v": "Dashboard",
1864
+ "5t6y7u8i": "Settings",
1865
+ "9o0p1q2r": "Logout"
1866
+ }
1867
+ },
1868
+ "demo-app/my-custom-footer.tsx": {
1869
+ entries: {
1870
+ "9k0l1m2n": "\xA9 2025 Lingo.dev. All rights reserved."
1871
+ }
1872
+ }
1873
+ }
1874
+ },
1875
+ {
1876
+ version: 0.1,
1877
+ locale: "es",
1878
+ files: {
1879
+ "demo-app/my-custom-header.tsx": {
1880
+ entries: {
1881
+ "1z2x3c4v": "Panel de control",
1882
+ "5t6y7u8i": "Configuraci\xF3n",
1883
+ "9o0p1q2r": "Cerrar sesi\xF3n"
1884
+ }
1885
+ },
1886
+ "demo-app/my-custom-footer.tsx": {
1887
+ entries: {
1888
+ "9k0l1m2n": "\xA9 2025 Lingo.dev. Todos los derechos reservados."
1889
+ }
1890
+ }
1891
+ }
1892
+ }
1893
+ ]
1894
+ // More shots here...
1895
+ ];
1896
+
1897
+ // src/lib/lcp/api/index.ts
1898
+
1899
+ var LCPAPI = class {
1900
+ static async translate(models, sourceDictionary, sourceLocale, targetLocale) {
1901
+ const timeLabel = `LCPAPI.translate: ${targetLocale}`;
1902
+ console.time(timeLabel);
1903
+ const chunks = this._chunkDictionary(sourceDictionary);
1904
+ const translatedChunks = [];
1905
+ for (const chunk of chunks) {
1906
+ const translatedChunk = await this._translateChunk(
1907
+ models,
1908
+ chunk,
1909
+ sourceLocale,
1910
+ targetLocale
1911
+ );
1912
+ translatedChunks.push(translatedChunk);
1913
+ }
1914
+ const result = this._mergeDictionaries(translatedChunks);
1915
+ console.timeEnd(timeLabel);
1916
+ return result;
1917
+ }
1918
+ static _chunkDictionary(dictionary) {
1919
+ const MAX_ENTRIES_PER_CHUNK = 100;
1920
+ const { files, ...rest } = dictionary;
1921
+ const chunks = [];
1922
+ let currentChunk = {
1923
+ ...rest,
1924
+ files: {}
1925
+ };
1926
+ let currentEntryCount = 0;
1927
+ Object.entries(files).forEach(([fileName, file]) => {
1928
+ const entries = file.entries;
1929
+ const entryPairs = Object.entries(entries);
1930
+ let currentIndex = 0;
1931
+ while (currentIndex < entryPairs.length) {
1932
+ const remainingSpace = MAX_ENTRIES_PER_CHUNK - currentEntryCount;
1933
+ const entriesToAdd = entryPairs.slice(
1934
+ currentIndex,
1935
+ currentIndex + remainingSpace
1936
+ );
1937
+ if (entriesToAdd.length > 0) {
1938
+ currentChunk.files[fileName] = currentChunk.files[fileName] || {
1939
+ entries: {}
1940
+ };
1941
+ currentChunk.files[fileName].entries = {
1942
+ ...currentChunk.files[fileName].entries,
1943
+ ...Object.fromEntries(entriesToAdd)
1944
+ };
1945
+ currentEntryCount += entriesToAdd.length;
1946
+ }
1947
+ currentIndex += entriesToAdd.length;
1948
+ if (currentEntryCount >= MAX_ENTRIES_PER_CHUNK || currentIndex < entryPairs.length && currentEntryCount + (entryPairs.length - currentIndex) > MAX_ENTRIES_PER_CHUNK) {
1949
+ chunks.push(currentChunk);
1950
+ currentChunk = { ...rest, files: {} };
1951
+ currentEntryCount = 0;
1952
+ }
1953
+ }
1954
+ });
1955
+ if (currentEntryCount > 0) {
1956
+ chunks.push(currentChunk);
1957
+ }
1958
+ return chunks;
1959
+ }
1960
+ static _mergeDictionaries(dictionaries) {
1961
+ const fileNames = _lodash2.default.uniq(
1962
+ _lodash2.default.flatMap(dictionaries, (dict) => Object.keys(dict.files))
1963
+ );
1964
+ const files = _lodash2.default.call(void 0, fileNames).map((fileName) => {
1965
+ const entries = dictionaries.reduce((entries2, dict) => {
1966
+ const file = dict.files[fileName];
1967
+ if (file) {
1968
+ entries2 = _lodash2.default.merge(entries2, file.entries);
1969
+ }
1970
+ return entries2;
1971
+ }, {});
1972
+ return [fileName, { entries }];
1973
+ }).fromPairs().value();
1974
+ const dictionary = {
1975
+ version: dictionaries[0].version,
1976
+ locale: dictionaries[0].locale,
1977
+ files
1978
+ };
1979
+ return dictionary;
1980
+ }
1981
+ static _createLingoDotDevEngine() {
1982
+ if (isRunningInCIOrDocker()) {
1983
+ const apiKeyFromEnv = getLingoDotDevKeyFromEnv();
1984
+ if (!apiKeyFromEnv) {
1985
+ this._failMissingLLMKeyCi("lingo.dev");
1986
+ }
1987
+ }
1988
+ const apiKey = getLingoDotDevKey();
1989
+ if (!apiKey) {
1990
+ throw new Error(
1991
+ "\u26A0\uFE0F Lingo.dev API key not found. Please set LINGODOTDEV_API_KEY environment variable or configure it user-wide."
1992
+ );
1993
+ }
1994
+ console.log(`Creating Lingo.dev client`);
1995
+ return new (0, __sdk.LingoDotDevEngine)({
1996
+ apiKey
1997
+ });
1998
+ }
1999
+ static async _translateChunk(models, sourceDictionary, sourceLocale, targetLocale) {
2000
+ if (models === "lingo.dev") {
2001
+ try {
2002
+ const lingoDotDevEngine = this._createLingoDotDevEngine();
2003
+ console.log(
2004
+ `\u2728 Using Lingo.dev Engine to localize from "${sourceLocale}" to "${targetLocale}"`
2005
+ );
2006
+ const result = await lingoDotDevEngine.localizeObject(
2007
+ sourceDictionary,
2008
+ {
2009
+ sourceLocale,
2010
+ targetLocale
2011
+ }
2012
+ );
2013
+ return result;
2014
+ } catch (error) {
2015
+ this._failLLMFailureLocal(
2016
+ "lingo.dev",
2017
+ targetLocale,
2018
+ error instanceof Error ? error.message : "Unknown error"
2019
+ );
2020
+ throw error;
2021
+ }
2022
+ } else {
2023
+ const { provider, model } = getLocaleModel(
2024
+ models,
2025
+ sourceLocale,
2026
+ targetLocale
2027
+ );
2028
+ if (!provider || !model) {
2029
+ throw new Error(
2030
+ _dedent2.default`
2031
+ 🚫 Lingo.dev Localization Engine Not Configured!
2032
+
2033
+ The "models" parameter is missing or incomplete in your Lingo.dev configuration.
2034
+
2035
+ 👉 To fix this, set the "models" parameter to either:
2036
+ • "lingo.dev" (for the default engine)
2037
+ • a map of locale-to-model, e.g. { "models": { "en:es": "openai:gpt-3.5-turbo" } }
2038
+
2039
+ Example:
2040
+ {
2041
+ // ...
2042
+ "models": "lingo.dev"
2043
+ }
2044
+
2045
+ For more details, see: https://lingo.dev/compiler
2046
+ To get help, join our Discord: https://lingo.dev/go/discord
2047
+ `
2048
+ );
2049
+ }
2050
+ try {
2051
+ const aiModel = this._createAiModel(provider, model, targetLocale);
2052
+ console.log(
2053
+ `\u2139\uFE0F Using raw LLM API ("${provider}":"${model}") to translate from "${sourceLocale}" to "${targetLocale}"`
2054
+ );
2055
+ const response = await _ai.generateText.call(void 0, {
2056
+ model: aiModel,
2057
+ messages: [
2058
+ {
2059
+ role: "system",
2060
+ content: prompt_default({ sourceLocale, targetLocale })
2061
+ },
2062
+ ...shots_default.flatMap((shotsTuple) => [
2063
+ {
2064
+ role: "user",
2065
+ content: obj2xml(shotsTuple[0])
2066
+ },
2067
+ {
2068
+ role: "assistant",
2069
+ content: obj2xml(shotsTuple[1])
2070
+ }
2071
+ ]),
2072
+ {
2073
+ role: "user",
2074
+ content: obj2xml(sourceDictionary)
2075
+ }
2076
+ ]
2077
+ });
2078
+ console.log("Response text received for", targetLocale);
2079
+ let responseText = response.text;
2080
+ responseText = responseText.substring(
2081
+ responseText.indexOf("<"),
2082
+ responseText.lastIndexOf(">") + 1
2083
+ );
2084
+ return xml2obj(responseText);
2085
+ } catch (error) {
2086
+ this._failLLMFailureLocal(
2087
+ provider,
2088
+ targetLocale,
2089
+ error instanceof Error ? error.message : "Unknown error"
2090
+ );
2091
+ throw error;
2092
+ }
2093
+ }
2094
+ }
2095
+ /**
2096
+ * Instantiates an AI model based on provider and model ID.
2097
+ * Includes CI/CD API key checks.
2098
+ * @param providerId The ID of the AI provider (e.g., "groq", "google").
2099
+ * @param modelId The ID of the specific model (e.g., "llama3-8b-8192", "gemini-2.0-flash").
2100
+ * @param targetLocale The target locale being translated to (for logging/error messages).
2101
+ * @returns An instantiated AI LanguageModel.
2102
+ * @throws Error if the provider is not supported or API key is missing in CI/CD.
2103
+ */
2104
+ static _createAiModel(providerId, modelId, targetLocale) {
2105
+ switch (providerId) {
2106
+ case "groq": {
2107
+ if (isRunningInCIOrDocker()) {
2108
+ const groqFromEnv = getGroqKeyFromEnv();
2109
+ if (!groqFromEnv) {
2110
+ this._failMissingLLMKeyCi(providerId);
2111
+ }
2112
+ }
2113
+ const groqKey = getGroqKey();
2114
+ if (!groqKey) {
2115
+ throw new Error(
2116
+ "\u26A0\uFE0F GROQ API key not found. Please set GROQ_API_KEY environment variable or configure it user-wide."
2117
+ );
2118
+ }
2119
+ console.log(
2120
+ `Creating Groq client for ${targetLocale} using model ${modelId}`
2121
+ );
2122
+ return _groq.createGroq.call(void 0, { apiKey: groqKey })(modelId);
2123
+ }
2124
+ case "google": {
2125
+ if (isRunningInCIOrDocker()) {
2126
+ const googleFromEnv = getGoogleKeyFromEnv();
2127
+ if (!googleFromEnv) {
2128
+ this._failMissingLLMKeyCi(providerId);
2129
+ }
2130
+ }
2131
+ const googleKey = getGoogleKey();
2132
+ if (!googleKey) {
2133
+ throw new Error(
2134
+ "\u26A0\uFE0F Google API key not found. Please set GOOGLE_API_KEY environment variable or configure it user-wide."
2135
+ );
2136
+ }
2137
+ console.log(
2138
+ `Creating Google Generative AI client for ${targetLocale} using model ${modelId}`
2139
+ );
2140
+ return _google.createGoogleGenerativeAI.call(void 0, { apiKey: googleKey })(modelId);
2141
+ }
2142
+ case "openrouter": {
2143
+ if (isRunningInCIOrDocker()) {
2144
+ const openRouterFromEnv = getOpenRouterKeyFromEnv();
2145
+ if (!openRouterFromEnv) {
2146
+ this._failMissingLLMKeyCi(providerId);
2147
+ }
2148
+ }
2149
+ const openRouterKey = getOpenRouterKey();
2150
+ if (!openRouterKey) {
2151
+ throw new Error(
2152
+ "\u26A0\uFE0F OpenRouter API key not found. Please set OPENROUTER_API_KEY environment variable or configure it user-wide."
2153
+ );
2154
+ }
2155
+ console.log(
2156
+ `Creating OpenRouter client for ${targetLocale} using model ${modelId}`
2157
+ );
2158
+ return _aisdkprovider.createOpenRouter.call(void 0, {
2159
+ apiKey: openRouterKey
2160
+ })(modelId);
2161
+ }
2162
+ case "ollama": {
2163
+ console.log(
2164
+ `Creating Ollama client for ${targetLocale} using model ${modelId} at default Ollama address`
2165
+ );
2166
+ return _ollamaaiprovider.createOllama.call(void 0, )(modelId);
2167
+ }
2168
+ default: {
2169
+ throw new Error(
2170
+ `\u26A0\uFE0F Provider "${providerId}" for locale "${targetLocale}" is not supported. Only "groq" and "google" providers are supported at the moment.`
2171
+ );
2172
+ }
2173
+ }
2174
+ }
2175
+ /**
2176
+ * Show an actionable error message and exit the process when the compiler
2177
+ * is running in CI/CD without a required LLM API key.
2178
+ * The message explains why this situation is unusual and how to fix it.
2179
+ * @param providerId The ID of the LLM provider whose key is missing.
2180
+ */
2181
+ static _failMissingLLMKeyCi(providerId) {
2182
+ let details = providerDetails[providerId];
2183
+ if (!details) {
2184
+ console.error(
2185
+ `Internal Error: Missing details for provider "${providerId}" when reporting missing key in CI/CD. You might be using an unsupported provider.`
2186
+ );
2187
+ process.exit(1);
2188
+ }
2189
+ console.log(
2190
+ _dedent2.default`
2191
+ \n
2192
+ 💡 You're using Lingo.dev Localization Compiler, and it detected unlocalized components in your app.
2193
+
2194
+ The compiler needs a ${details.name} API key to translate missing strings, but ${details.apiKeyEnvVar} is not set in the environment.
2195
+
2196
+ This is unexpected: typically you run a full build locally, commit the generated translation files, and push them to CI/CD.
2197
+
2198
+ However, If you want CI/CD to translate the new strings, provide the key with:
2199
+ • Session-wide: export ${details.apiKeyEnvVar}=<your-api-key>
2200
+ • Project-wide / CI: add ${details.apiKeyEnvVar}=<your-api-key> to your pipeline environment variables
2201
+
2202
+ ⭐️ Also:
2203
+ 1. If you don't yet have a ${details.name} API key, get one for free at ${details.getKeyLink}
2204
+ 2. If you want to use a different LLM, update your configuration. Refer to documentation for help: https://lingo.dev/compiler
2205
+ 3. If the model you want to use isn't supported yet, raise an issue in our open-source repo: https://lingo.dev/go/gh
2206
+
2207
+
2208
+ `
2209
+ );
2210
+ process.exit(1);
2211
+ }
2212
+ /**
2213
+ * Show an actionable error message and exit the process when an LLM API call
2214
+ * fails during local compilation.
2215
+ * @param providerId The ID of the LLM provider that failed.
2216
+ * @param targetLocale The target locale being translated to.
2217
+ * @param errorMessage The error message received from the API.
2218
+ */
2219
+ static _failLLMFailureLocal(providerId, targetLocale, errorMessage) {
2220
+ const details = providerDetails[providerId];
2221
+ if (!details) {
2222
+ console.error(
2223
+ `Internal Error: Missing details for provider "${providerId}" when reporting local failure.`
2224
+ );
2225
+ console.error(`Original Error: ${errorMessage}`);
2226
+ process.exit(1);
2227
+ }
2228
+ const isInvalidApiKey = errorMessage.match("Invalid API Key");
2229
+ if (isInvalidApiKey) {
2230
+ console.log(_dedent2.default`
2231
+ \n
2232
+ ⚠️ Lingo.dev Compiler requires a valid ${details.name} API key to translate your application.
2233
+
2234
+ It looks like you set ${details.name} API key but it is not valid. Please check your API key and try again.
2235
+
2236
+ Error details from ${details.name} API: ${errorMessage}
2237
+
2238
+ 👉 You can set the API key in one of the following ways:
2239
+ 1. User-wide: Run npx lingo.dev@latest config set ${details.apiKeyConfigKey} <your-api-key>
2240
+ 2. Project-wide: Add ${details.apiKeyEnvVar}=<your-api-key> to .env file in every project that uses Lingo.dev Localization Compiler
2241
+ 3 Session-wide: Run export ${details.apiKeyEnvVar}=<your-api-key> in your terminal before running the compiler to set the API key for the current session
2242
+
2243
+ ⭐️ Also:
2244
+ 1. If you don't yet have a ${details.name} API key, get one for free at ${details.getKeyLink}
2245
+ 2. If you want to use a different LLM, raise an issue in our open-source repo: https://lingo.dev/go/gh
2246
+ 3. If you have questions, feature requests, or would like to contribute, join our Discord: https://lingo.dev/go/discord
2247
+
2248
+
2249
+ `);
2250
+ } else {
2251
+ console.log(
2252
+ _dedent2.default`
2253
+ \n
2254
+ ⚠️ Lingo.dev Compiler tried to translate your application to "${targetLocale}" locale via ${details.name} but it failed.
2255
+
2256
+ Error details from ${details.name} API: ${errorMessage}
2257
+
2258
+ This error comes from the ${details.name} API, please check their documentation for more details: ${details.docsLink}
2259
+
2260
+ ⭐️ Also:
2261
+ 1. Did you set ${details.apiKeyEnvVar ? `${details.apiKeyEnvVar}` : "the provider API key"} environment variable correctly ${!details.apiKeyEnvVar ? "(if required)" : ""}?
2262
+ 2. Did you reach any limits of your ${details.name} account?
2263
+ 3. If you have questions, feature requests, or would like to contribute, join our Discord: https://lingo.dev/go/discord
2264
+
2265
+
2266
+ `
2267
+ );
2268
+ }
2269
+ process.exit(1);
2270
+ }
2271
+ };
2272
+
2273
+ // src/lib/lcp/server.ts
2274
+ var LCPServer = (_class = class {
2275
+ static __initStatic() {this.inFlightPromise = null}
2276
+ static async loadDictionaries(params) {
2277
+ if (this.inFlightPromise) {
2278
+ return this.inFlightPromise;
2279
+ }
2280
+ this.inFlightPromise = (async () => {
2281
+ try {
2282
+ const targetLocales = _lodash2.default.uniq([
2283
+ ...params.targetLocales,
2284
+ params.sourceLocale
2285
+ ]);
2286
+ const dictionaries = await Promise.all(
2287
+ targetLocales.map(
2288
+ (targetLocale) => this.loadDictionaryForLocale({ ...params, targetLocale })
2289
+ )
2290
+ );
2291
+ const result = _lodash2.default.fromPairs(
2292
+ targetLocales.map((targetLocale, index) => [
2293
+ targetLocale,
2294
+ dictionaries[index]
2295
+ ])
2296
+ );
2297
+ return result;
2298
+ } finally {
2299
+ this.inFlightPromise = null;
2300
+ }
2301
+ })();
2302
+ return this.inFlightPromise;
2303
+ }
2304
+ static async loadDictionaryForLocale(params) {
2305
+ const sourceDictionary = this._extractSourceDictionary(
2306
+ params.lcp,
2307
+ params.sourceLocale,
2308
+ params.targetLocale
2309
+ );
2310
+ const cacheParams = {
2311
+ lcp: params.lcp,
2312
+ sourceLocale: params.sourceLocale,
2313
+ lingoDir: params.lingoDir,
2314
+ sourceRoot: params.sourceRoot
2315
+ };
2316
+ if (this._countDictionaryEntries(sourceDictionary) === 0) {
2317
+ console.log(
2318
+ "Source dictionary is empty, returning empty dictionary for target locale"
2319
+ );
2320
+ return { ...sourceDictionary, locale: params.targetLocale };
2321
+ }
2322
+ const cache = LCPCache.readLocaleDictionary(
2323
+ params.targetLocale,
2324
+ cacheParams
2325
+ );
2326
+ const uncachedSourceDictionary = this._getDictionaryDiff(
2327
+ sourceDictionary,
2328
+ cache
2329
+ );
2330
+ let targetDictionary;
2331
+ let newTranslations;
2332
+ if (this._countDictionaryEntries(uncachedSourceDictionary) === 0) {
2333
+ targetDictionary = cache;
2334
+ } else if (params.targetLocale === params.sourceLocale) {
2335
+ console.log(
2336
+ "\u2139\uFE0F Lingo.dev returns source dictionary - source and target locales are the same"
2337
+ );
2338
+ await LCPCache.writeLocaleDictionary(sourceDictionary, cacheParams);
2339
+ return sourceDictionary;
2340
+ } else {
2341
+ newTranslations = await LCPAPI.translate(
2342
+ params.models,
2343
+ uncachedSourceDictionary,
2344
+ params.sourceLocale,
2345
+ params.targetLocale
2346
+ );
2347
+ targetDictionary = this._mergeDictionaries(newTranslations, cache);
2348
+ targetDictionary = {
2349
+ ...targetDictionary,
2350
+ locale: params.targetLocale
2351
+ };
2352
+ await LCPCache.writeLocaleDictionary(targetDictionary, cacheParams);
2353
+ }
2354
+ const targetDictionaryWithFallback = this._mergeDictionaries(
2355
+ targetDictionary,
2356
+ sourceDictionary,
2357
+ true
2358
+ );
2359
+ const result = this._addOverridesToDictionary(
2360
+ targetDictionaryWithFallback,
2361
+ params.lcp,
2362
+ params.targetLocale
2363
+ );
2364
+ if (newTranslations) {
2365
+ console.log(
2366
+ `\u2139\uFE0F Lingo.dev dictionary for ${params.targetLocale}:
2367
+ - %d entries
2368
+ - %d cached
2369
+ - %d uncached
2370
+ - %d translated
2371
+ - %d overrides`,
2372
+ this._countDictionaryEntries(result),
2373
+ this._countDictionaryEntries(cache),
2374
+ this._countDictionaryEntries(uncachedSourceDictionary),
2375
+ newTranslations ? this._countDictionaryEntries(newTranslations) : 0,
2376
+ this._countDictionaryEntries(result) - this._countDictionaryEntries(targetDictionary)
2377
+ );
2378
+ }
2379
+ return result;
2380
+ }
2381
+ static _extractSourceDictionary(lcp, sourceLocale, targetLocale) {
2382
+ const dictionary = {
2383
+ version: 0.1,
2384
+ locale: sourceLocale,
2385
+ files: {}
2386
+ };
2387
+ for (const [fileKey, fileData] of Object.entries(lcp.files || {})) {
2388
+ for (const [scopeKey, scopeData] of Object.entries(
2389
+ fileData.scopes || {}
2390
+ )) {
2391
+ if (scopeData.skip) {
2392
+ continue;
2393
+ }
2394
+ if (this._getScopeLocaleOverride(scopeData, targetLocale)) {
2395
+ continue;
2396
+ }
2397
+ _lodash2.default.set(
2398
+ dictionary,
2399
+ [
2400
+ "files",
2401
+ fileKey,
2402
+ "entries",
2403
+ scopeKey
2404
+ ],
2405
+ scopeData.content
2406
+ );
2407
+ }
2408
+ }
2409
+ return dictionary;
2410
+ }
2411
+ static _addOverridesToDictionary(dictionary, lcp, targetLocale) {
2412
+ for (const [fileKey, fileData] of Object.entries(lcp.files || {})) {
2413
+ for (const [scopeKey, scopeData] of Object.entries(
2414
+ fileData.scopes || {}
2415
+ )) {
2416
+ const override = this._getScopeLocaleOverride(scopeData, targetLocale);
2417
+ if (!override) {
2418
+ continue;
2419
+ }
2420
+ _lodash2.default.set(
2421
+ dictionary,
2422
+ [
2423
+ "files",
2424
+ fileKey,
2425
+ "entries",
2426
+ scopeKey
2427
+ ],
2428
+ override
2429
+ );
2430
+ }
2431
+ }
2432
+ return dictionary;
2433
+ }
2434
+ static _getScopeLocaleOverride(scopeData, locale) {
2435
+ return _nullishCoalesce(_lodash2.default.get(scopeData.overrides, locale), () => ( null));
2436
+ }
2437
+ static _getDictionaryDiff(sourceDictionary, targetDictionary) {
2438
+ if (this._countDictionaryEntries(targetDictionary) === 0) {
2439
+ return sourceDictionary;
2440
+ }
2441
+ const files = _lodash2.default.call(void 0, sourceDictionary.files).mapValues((file, fileName) => ({
2442
+ ...file,
2443
+ entries: _lodash2.default.call(void 0, file.entries).mapValues((entry, entryName) => {
2444
+ const targetEntry = _lodash2.default.get(targetDictionary.files, [
2445
+ fileName,
2446
+ "entries",
2447
+ entryName
2448
+ ]);
2449
+ if (targetEntry !== void 0) {
2450
+ return void 0;
2451
+ }
2452
+ return entry;
2453
+ }).pickBy((value) => value !== void 0).value()
2454
+ })).pickBy((value) => Object.keys(value.entries).length > 0).value();
2455
+ const dictionary = {
2456
+ version: sourceDictionary.version,
2457
+ locale: sourceDictionary.locale,
2458
+ files
2459
+ };
2460
+ return dictionary;
2461
+ }
2462
+ static _mergeDictionaries(sourceDictionary, targetDictionary, removeEmptyEntries = false) {
2463
+ const fileNames = _lodash2.default.uniq([
2464
+ ...Object.keys(sourceDictionary.files),
2465
+ ...Object.keys(targetDictionary.files)
2466
+ ]);
2467
+ const files = _lodash2.default.call(void 0, fileNames).map((fileName) => {
2468
+ const sourceFile = _lodash2.default.get(sourceDictionary.files, fileName);
2469
+ const targetFile = _lodash2.default.get(targetDictionary.files, fileName);
2470
+ const entries = removeEmptyEntries ? _lodash2.default.pickBy(
2471
+ _optionalChain([sourceFile, 'optionalAccess', _45 => _45.entries]) || {},
2472
+ (value) => _optionalChain([String, 'call', _46 => _46(value || ""), 'optionalAccess', _47 => _47.trim, 'optionalCall', _48 => _48(), 'optionalAccess', _49 => _49.length]) > 0
2473
+ ) : _optionalChain([sourceFile, 'optionalAccess', _50 => _50.entries]) || {};
2474
+ return [
2475
+ fileName,
2476
+ {
2477
+ ...targetFile,
2478
+ entries: _lodash2.default.merge({}, _optionalChain([targetFile, 'optionalAccess', _51 => _51.entries]) || {}, entries)
2479
+ }
2480
+ ];
2481
+ }).fromPairs().value();
2482
+ const dictionary = {
2483
+ version: sourceDictionary.version,
2484
+ locale: sourceDictionary.locale,
2485
+ files
2486
+ };
2487
+ return dictionary;
2488
+ }
2489
+ static _countDictionaryEntries(dict) {
2490
+ return Object.values(dict.files).reduce(
2491
+ (sum, file) => sum + Object.keys(file.entries).length,
2492
+ 0
2493
+ );
2494
+ }
2495
+ }, _class.__initStatic(), _class);
2496
+
2497
+ // src/react-router-dictionary-loader.ts
2498
+
2499
+ var reactRouterDictionaryLoaderMutation = createCodeMutation(
2500
+ (payload) => {
2501
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
2502
+ if (mode === "server") {
2503
+ return payload;
2504
+ }
2505
+ const invokations = findInvokations(payload.ast, {
2506
+ moduleName: ModuleId.ReactRouter,
2507
+ functionName: "loadDictionary"
2508
+ });
2509
+ const allLocales = Array.from(
2510
+ /* @__PURE__ */ new Set([payload.params.sourceLocale, ...payload.params.targetLocales])
2511
+ );
2512
+ for (const invokation of invokations) {
2513
+ const internalDictionaryLoader = getOrCreateImport(payload.ast, {
2514
+ moduleName: ModuleId.ReactRouter,
2515
+ exportedName: "loadDictionary_internal"
2516
+ });
2517
+ if (t23.isIdentifier(invokation.callee)) {
2518
+ invokation.callee.name = internalDictionaryLoader.importedName;
2519
+ }
2520
+ const dictionaryPath = getDictionaryPath({
2521
+ sourceRoot: payload.params.sourceRoot,
2522
+ lingoDir: payload.params.lingoDir,
2523
+ relativeFilePath: payload.relativeFilePath
2524
+ });
2525
+ const localeImportMap = createLocaleImportMap(allLocales, dictionaryPath);
2526
+ invokation.arguments.push(localeImportMap);
2527
+ }
2528
+ return payload;
2529
+ }
2530
+ );
2531
+
2532
+ // src/rsc-dictionary-loader.ts
2533
+
2534
+ var rscDictionaryLoaderMutation = createCodeMutation((payload) => {
2535
+ const mode = getModuleExecutionMode(payload.ast, payload.params.rsc);
2536
+ if (mode === "client") {
2537
+ return payload;
2538
+ }
2539
+ const invokations = findInvokations(payload.ast, {
2540
+ moduleName: ModuleId.ReactRSC,
2541
+ functionName: "loadDictionary"
2542
+ });
2543
+ const allLocales = Array.from(
2544
+ /* @__PURE__ */ new Set([payload.params.sourceLocale, ...payload.params.targetLocales])
2545
+ );
2546
+ for (const invokation of invokations) {
2547
+ const internalDictionaryLoader = getOrCreateImport(payload.ast, {
2548
+ moduleName: ModuleId.ReactRSC,
2549
+ exportedName: "loadDictionary_internal"
2550
+ });
2551
+ if (t24.isIdentifier(invokation.callee)) {
2552
+ invokation.callee.name = internalDictionaryLoader.importedName;
2553
+ }
2554
+ const dictionaryPath = getDictionaryPath({
2555
+ sourceRoot: payload.params.sourceRoot,
2556
+ lingoDir: payload.params.lingoDir,
2557
+ relativeFilePath: payload.relativeFilePath
2558
+ });
2559
+ const localeImportMap = createLocaleImportMap(allLocales, dictionaryPath);
2560
+ invokation.arguments.push(localeImportMap);
2561
+ }
2562
+ return payload;
2563
+ });
2564
+
2565
+ // src/utils/module-params.ts
2566
+ function parseParametrizedModuleId(rawId) {
2567
+ const moduleUri = new URL(rawId, "module://");
2568
+ return {
2569
+ id: moduleUri.pathname.replace(/^\//, ""),
2570
+ params: Object.fromEntries(moduleUri.searchParams.entries())
2571
+ };
2572
+ }
2573
+
2574
+ // src/_loader-utils.ts
2575
+ async function loadDictionary(options) {
2576
+ const { resourcePath, resourceQuery = "", params, sourceRoot, lingoDir, isDev } = options;
2577
+ const fullResourcePath = `${resourcePath}${resourceQuery}`;
2578
+ if (!resourcePath.endsWith(LCP_DICTIONARY_FILE_NAME)) {
2579
+ return null;
2580
+ }
2581
+ const moduleInfo = parseParametrizedModuleId(fullResourcePath);
2582
+ const locale = moduleInfo.params.locale;
2583
+ if (!locale) {
2584
+ return null;
2585
+ }
2586
+ const lcpParams = {
2587
+ sourceRoot,
2588
+ lingoDir,
2589
+ isDev
2590
+ };
2591
+ await LCP.ready(lcpParams);
2592
+ const lcp = LCP.getInstance(lcpParams);
2593
+ const dictionaries = await LCPServer.loadDictionaries({
2594
+ ...params,
2595
+ lcp: lcp.data
2596
+ });
2597
+ const dictionary = dictionaries[locale];
2598
+ if (!dictionary) {
2599
+ throw new Error(
2600
+ `Lingo.dev: Dictionary for locale "${locale}" could not be generated.`
2601
+ );
2602
+ }
2603
+ return dictionary;
2604
+ }
2605
+ function transformComponent(options) {
2606
+ const { code, params, resourcePath, sourceRoot } = options;
2607
+ return _lodash2.default.chain({
2608
+ code,
2609
+ params,
2610
+ relativeFilePath: path.default.relative(path.default.resolve(process.cwd(), sourceRoot), resourcePath).split(path.default.sep).join("/")
2611
+ // Always normalize for consistent dictionaries
2612
+ }).thru(createPayload).thru(
2613
+ composeMutations(
2614
+ i18n_directive_default,
2615
+ jsxFragmentMutation,
2616
+ jsx_attribute_flag_default,
2617
+ jsx_provider_default,
2618
+ jsxHtmlLangMutation,
2619
+ jsx_root_flag_default,
2620
+ jsx_scope_flag_default,
2621
+ jsxAttributeScopesExportMutation,
2622
+ jsxScopesExportMutation,
2623
+ lingoJsxAttributeScopeInjectMutation,
2624
+ lingoJsxScopeInjectMutation,
2625
+ rscDictionaryLoaderMutation,
2626
+ reactRouterDictionaryLoaderMutation,
2627
+ jsxRemoveAttributesMutation,
2628
+ clientDictionaryLoaderMutation
2629
+ )
2630
+ ).thru(createOutput).value();
2631
+ }
2632
+
2633
+
2634
+
2635
+
2636
+
2637
+
2638
+
2639
+
2640
+
2641
+
2642
+
2643
+
2644
+
2645
+
2646
+
2647
+
2648
+
2649
+ exports.__require = __require; exports.defaultParams = defaultParams; exports.LCP_DICTIONARY_FILE_NAME = LCP_DICTIONARY_FILE_NAME; exports.LCPCache = LCPCache; exports.getInvalidLocales = getInvalidLocales; exports.getGroqKeyFromRc = getGroqKeyFromRc; exports.getGroqKeyFromEnv = getGroqKeyFromEnv; exports.getLingoDotDevKeyFromEnv = getLingoDotDevKeyFromEnv; exports.getLingoDotDevKeyFromRc = getLingoDotDevKeyFromRc; exports.getGoogleKeyFromRc = getGoogleKeyFromRc; exports.getGoogleKeyFromEnv = getGoogleKeyFromEnv; exports.isRunningInCIOrDocker = isRunningInCIOrDocker; exports.providerDetails = providerDetails; exports.loadDictionary = loadDictionary; exports.transformComponent = transformComponent;