@djangocfg/llm 2.1.164

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.
Files changed (45) hide show
  1. package/README.md +181 -0
  2. package/dist/index.cjs +1164 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +164 -0
  5. package/dist/index.d.ts +164 -0
  6. package/dist/index.mjs +1128 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/providers/index.cjs +317 -0
  9. package/dist/providers/index.cjs.map +1 -0
  10. package/dist/providers/index.d.cts +30 -0
  11. package/dist/providers/index.d.ts +30 -0
  12. package/dist/providers/index.mjs +304 -0
  13. package/dist/providers/index.mjs.map +1 -0
  14. package/dist/sdkrouter-D8GMBmTi.d.ts +171 -0
  15. package/dist/sdkrouter-hlQlVd0v.d.cts +171 -0
  16. package/dist/text-utils-DoYqMIr6.d.ts +289 -0
  17. package/dist/text-utils-VXWN-8Oq.d.cts +289 -0
  18. package/dist/translator/index.cjs +794 -0
  19. package/dist/translator/index.cjs.map +1 -0
  20. package/dist/translator/index.d.cts +24 -0
  21. package/dist/translator/index.d.ts +24 -0
  22. package/dist/translator/index.mjs +769 -0
  23. package/dist/translator/index.mjs.map +1 -0
  24. package/dist/types-D6lazgm1.d.cts +59 -0
  25. package/dist/types-D6lazgm1.d.ts +59 -0
  26. package/package.json +82 -0
  27. package/src/client.ts +119 -0
  28. package/src/index.ts +70 -0
  29. package/src/providers/anthropic.ts +98 -0
  30. package/src/providers/base.ts +90 -0
  31. package/src/providers/index.ts +15 -0
  32. package/src/providers/openai.ts +73 -0
  33. package/src/providers/sdkrouter.ts +279 -0
  34. package/src/translator/cache.ts +237 -0
  35. package/src/translator/index.ts +55 -0
  36. package/src/translator/json-translator.ts +408 -0
  37. package/src/translator/prompts.ts +90 -0
  38. package/src/translator/text-utils.ts +148 -0
  39. package/src/translator/types.ts +112 -0
  40. package/src/translator/validator.ts +181 -0
  41. package/src/types.ts +85 -0
  42. package/src/utils/env.ts +67 -0
  43. package/src/utils/index.ts +2 -0
  44. package/src/utils/json.ts +44 -0
  45. package/src/utils/schema.ts +153 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,1164 @@
1
+ 'use strict';
2
+
3
+ var OpenAI = require('openai');
4
+ var crypto = require('crypto');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
9
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
14
+
15
+ // src/translator/text-utils.ts
16
+ function isTechnicalContent(text) {
17
+ const trimmed = text.trim();
18
+ if (!trimmed) return true;
19
+ if (/^(https?:\/\/|\/\/|www\.)/i.test(trimmed)) return true;
20
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) return true;
21
+ if (/^\/[a-zA-Z]/.test(trimmed)) return true;
22
+ if (/\.(js|ts|tsx|jsx|json|css|scss|html|md|py|go|rs)$/i.test(trimmed)) return true;
23
+ if (/^[\d.,]+%?$/.test(trimmed)) return true;
24
+ if (/^[A-Z][A-Z0-9_]*$/.test(trimmed)) return true;
25
+ if (/^(\{[^}]+\}|\{\{[^}]+\}\}|%[sd]|\$\d+)$/.test(trimmed)) return true;
26
+ if (/^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/.test(trimmed)) return true;
27
+ return false;
28
+ }
29
+ function containsCJK(text) {
30
+ return /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(text);
31
+ }
32
+ function containsCyrillic(text) {
33
+ return /[\u0400-\u04ff]/.test(text);
34
+ }
35
+ function containsArabic(text) {
36
+ return /[\u0600-\u06ff]/.test(text);
37
+ }
38
+ function detectScript(text) {
39
+ if (containsCJK(text)) return "cjk";
40
+ if (containsCyrillic(text)) return "cyrillic";
41
+ if (containsArabic(text)) return "arabic";
42
+ if (/[a-zA-Z]/.test(text)) return "latin";
43
+ return "unknown";
44
+ }
45
+ function extractPlaceholders(text) {
46
+ const patterns = [
47
+ /\{[^}]+\}/g,
48
+ // {name}
49
+ /\{\{[^}]+\}\}/g,
50
+ // {{name}}
51
+ /%[sd]/g,
52
+ // %s, %d
53
+ /\$\d+/g
54
+ // $1, $2
55
+ ];
56
+ const placeholders = [];
57
+ for (const pattern of patterns) {
58
+ const matches = text.match(pattern);
59
+ if (matches) {
60
+ placeholders.push(...matches);
61
+ }
62
+ }
63
+ return [...new Set(placeholders)];
64
+ }
65
+
66
+ // src/translator/validator.ts
67
+ function validateJsonKeys(original, translated, path = "") {
68
+ const errors = [];
69
+ if (typeof original !== typeof translated) {
70
+ errors.push(`Type mismatch at ${path || "root"}: expected ${typeof original}, got ${typeof translated}`);
71
+ return { valid: false, errors };
72
+ }
73
+ if (original === null || translated === null) {
74
+ if (original !== translated) {
75
+ errors.push(`Null mismatch at ${path || "root"}`);
76
+ }
77
+ return { valid: errors.length === 0, errors };
78
+ }
79
+ if (Array.isArray(original)) {
80
+ if (!Array.isArray(translated)) {
81
+ errors.push(`Expected array at ${path || "root"}`);
82
+ return { valid: false, errors };
83
+ }
84
+ if (original.length !== translated.length) {
85
+ errors.push(
86
+ `Array length mismatch at ${path || "root"}: expected ${original.length}, got ${translated.length}`
87
+ );
88
+ }
89
+ const minLen = Math.min(original.length, translated.length);
90
+ for (let i = 0; i < minLen; i++) {
91
+ const result = validateJsonKeys(
92
+ original[i],
93
+ translated[i],
94
+ `${path}[${i}]`
95
+ );
96
+ errors.push(...result.errors);
97
+ }
98
+ return { valid: errors.length === 0, errors };
99
+ }
100
+ if (typeof original === "object") {
101
+ if (typeof translated !== "object" || Array.isArray(translated)) {
102
+ errors.push(`Expected object at ${path || "root"}`);
103
+ return { valid: false, errors };
104
+ }
105
+ const origKeys = Object.keys(original);
106
+ const transKeys = Object.keys(translated);
107
+ for (const key of origKeys) {
108
+ if (!transKeys.includes(key)) {
109
+ errors.push(`Missing key: ${path ? `${path}.${key}` : key}`);
110
+ }
111
+ }
112
+ for (const key of transKeys) {
113
+ if (!origKeys.includes(key)) {
114
+ errors.push(
115
+ `Unexpected key: ${path ? `${path}.${key}` : key} (key was translated?)`
116
+ );
117
+ }
118
+ }
119
+ for (const key of origKeys) {
120
+ if (transKeys.includes(key)) {
121
+ const result = validateJsonKeys(
122
+ original[key],
123
+ translated[key],
124
+ path ? `${path}.${key}` : key
125
+ );
126
+ errors.push(...result.errors);
127
+ }
128
+ }
129
+ return { valid: errors.length === 0, errors };
130
+ }
131
+ return { valid: true, errors: [] };
132
+ }
133
+ function validatePlaceholders(original, translated, path = "") {
134
+ const errors = [];
135
+ if (typeof original === "string" && typeof translated === "string") {
136
+ const origPlaceholders = extractPlaceholders(original);
137
+ const transPlaceholders = extractPlaceholders(translated);
138
+ for (const placeholder of origPlaceholders) {
139
+ if (!transPlaceholders.includes(placeholder)) {
140
+ errors.push(
141
+ `Missing placeholder "${placeholder}" at ${path || "root"}`
142
+ );
143
+ }
144
+ }
145
+ for (const placeholder of transPlaceholders) {
146
+ if (!origPlaceholders.includes(placeholder)) {
147
+ errors.push(
148
+ `Extra placeholder "${placeholder}" at ${path || "root"}`
149
+ );
150
+ }
151
+ }
152
+ } else if (Array.isArray(original) && Array.isArray(translated)) {
153
+ const minLen = Math.min(original.length, translated.length);
154
+ for (let i = 0; i < minLen; i++) {
155
+ const result = validatePlaceholders(
156
+ original[i],
157
+ translated[i],
158
+ `${path}[${i}]`
159
+ );
160
+ errors.push(...result.errors);
161
+ }
162
+ } else if (typeof original === "object" && original !== null && typeof translated === "object" && translated !== null) {
163
+ for (const key of Object.keys(original)) {
164
+ if (key in translated) {
165
+ const result = validatePlaceholders(
166
+ original[key],
167
+ translated[key],
168
+ path ? `${path}.${key}` : key
169
+ );
170
+ errors.push(...result.errors);
171
+ }
172
+ }
173
+ }
174
+ return { valid: errors.length === 0, errors };
175
+ }
176
+ function validateTranslation(original, translated) {
177
+ const keyResult = validateJsonKeys(original, translated);
178
+ const placeholderResult = validatePlaceholders(original, translated);
179
+ return {
180
+ valid: keyResult.valid && placeholderResult.valid,
181
+ errors: [...keyResult.errors, ...placeholderResult.errors]
182
+ };
183
+ }
184
+
185
+ // src/utils/json.ts
186
+ function extractJson(text) {
187
+ let jsonStr = text.trim();
188
+ if (jsonStr.startsWith("```json")) {
189
+ jsonStr = jsonStr.slice(7);
190
+ } else if (jsonStr.startsWith("```")) {
191
+ jsonStr = jsonStr.slice(3);
192
+ }
193
+ if (jsonStr.endsWith("```")) {
194
+ jsonStr = jsonStr.slice(0, -3);
195
+ }
196
+ jsonStr = jsonStr.trim();
197
+ const jsonStart = jsonStr.search(/[\[{]/);
198
+ const jsonEndBracket = jsonStr.lastIndexOf("]");
199
+ const jsonEndBrace = jsonStr.lastIndexOf("}");
200
+ const jsonEnd = Math.max(jsonEndBracket, jsonEndBrace);
201
+ if (jsonStart !== -1 && jsonEnd !== -1) {
202
+ jsonStr = jsonStr.slice(jsonStart, jsonEnd + 1);
203
+ }
204
+ try {
205
+ return JSON.parse(jsonStr);
206
+ } catch (error) {
207
+ throw new Error(
208
+ `Failed to parse JSON from LLM response: ${error instanceof Error ? error.message : "Unknown error"}
209
+
210
+ Response:
211
+ ${text}`
212
+ );
213
+ }
214
+ }
215
+
216
+ // src/providers/base.ts
217
+ var BaseLLMProvider = class {
218
+ constructor(config) {
219
+ __publicField(this, "config");
220
+ this.config = {
221
+ model: config.model ?? "gpt-4o-mini",
222
+ temperature: config.temperature ?? 0.1,
223
+ maxTokens: config.maxTokens ?? 4096,
224
+ ...config
225
+ };
226
+ }
227
+ /**
228
+ * Send single chat message
229
+ */
230
+ async chat(prompt, options) {
231
+ const messages = [];
232
+ if (options?.system) {
233
+ messages.push({ role: "system", content: options.system });
234
+ }
235
+ messages.push({ role: "user", content: prompt });
236
+ return this.chatMessages(messages, options);
237
+ }
238
+ /**
239
+ * Get JSON response
240
+ */
241
+ async json(prompt, options) {
242
+ const systemPrompt = `${options?.system ?? ""}
243
+
244
+ Respond with valid JSON only. No markdown, no explanations.`.trim();
245
+ const response = await this.chat(prompt, {
246
+ ...options,
247
+ system: systemPrompt,
248
+ temperature: options?.temperature ?? 0
249
+ });
250
+ return extractJson(response.content);
251
+ }
252
+ /**
253
+ * Get JSON response with schema hint
254
+ */
255
+ async jsonSchema(prompt, schema, options) {
256
+ const systemPrompt = `${options?.system ?? ""}
257
+
258
+ Respond with valid JSON matching this schema:
259
+ ${schema}
260
+
261
+ No markdown, no explanations.`.trim();
262
+ const response = await this.chat(prompt, {
263
+ ...options,
264
+ system: systemPrompt,
265
+ temperature: options?.temperature ?? 0
266
+ });
267
+ return extractJson(response.content);
268
+ }
269
+ };
270
+
271
+ // src/providers/openai.ts
272
+ var OpenAIProvider = class extends BaseLLMProvider {
273
+ constructor(config) {
274
+ super({
275
+ model: config.model ?? "gpt-4o-mini",
276
+ ...config
277
+ });
278
+ __publicField(this, "provider", "openai");
279
+ __publicField(this, "client");
280
+ if (!config.apiKey) {
281
+ throw new Error("OpenAI API key is required");
282
+ }
283
+ this.client = new OpenAI__default.default({
284
+ apiKey: config.apiKey,
285
+ baseURL: config.baseUrl
286
+ });
287
+ }
288
+ async chatMessages(messages, options) {
289
+ const model = options?.model ?? this.config.model;
290
+ const temperature = options?.temperature ?? this.config.temperature;
291
+ const maxTokens = options?.maxTokens ?? this.config.maxTokens;
292
+ const allMessages = options?.system ? [{ role: "system", content: options.system }, ...messages] : messages;
293
+ const response = await this.client.chat.completions.create({
294
+ model,
295
+ messages: allMessages.map((m) => ({
296
+ role: m.role,
297
+ content: m.content
298
+ })),
299
+ temperature,
300
+ max_tokens: maxTokens
301
+ });
302
+ const choice = response.choices[0];
303
+ return {
304
+ content: choice.message.content ?? "",
305
+ model: response.model,
306
+ usage: response.usage ? {
307
+ promptTokens: response.usage.prompt_tokens,
308
+ completionTokens: response.usage.completion_tokens,
309
+ totalTokens: response.usage.total_tokens
310
+ } : void 0,
311
+ finishReason: choice.finish_reason ?? void 0
312
+ };
313
+ }
314
+ };
315
+ var AnthropicProvider = class extends BaseLLMProvider {
316
+ constructor(config) {
317
+ super({
318
+ model: config.model ?? "claude-3-5-haiku-latest",
319
+ ...config
320
+ });
321
+ __publicField(this, "provider", "anthropic");
322
+ __publicField(this, "client");
323
+ if (!config.apiKey) {
324
+ throw new Error("Anthropic API key is required");
325
+ }
326
+ this.client = new OpenAI__default.default({
327
+ apiKey: config.apiKey,
328
+ baseURL: config.baseUrl ?? "https://api.anthropic.com/v1",
329
+ defaultHeaders: {
330
+ "anthropic-version": "2023-06-01",
331
+ "x-api-key": config.apiKey
332
+ }
333
+ });
334
+ }
335
+ async chatMessages(messages, options) {
336
+ const model = options?.model ?? this.config.model;
337
+ const temperature = options?.temperature ?? this.config.temperature;
338
+ const maxTokens = options?.maxTokens ?? this.config.maxTokens;
339
+ const systemMessage = options?.system ? options.system : messages.find((m) => m.role === "system")?.content;
340
+ const userMessages = messages.filter((m) => m.role !== "system");
341
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
342
+ method: "POST",
343
+ headers: {
344
+ "Content-Type": "application/json",
345
+ "x-api-key": this.config.apiKey,
346
+ "anthropic-version": "2023-06-01"
347
+ },
348
+ body: JSON.stringify({
349
+ model,
350
+ max_tokens: maxTokens,
351
+ temperature,
352
+ system: systemMessage,
353
+ messages: userMessages.map((m) => ({
354
+ role: m.role,
355
+ content: m.content
356
+ }))
357
+ })
358
+ });
359
+ if (!response.ok) {
360
+ const error = await response.text();
361
+ throw new Error(`Anthropic API error: ${response.status} ${error}`);
362
+ }
363
+ const data = await response.json();
364
+ return {
365
+ content: data.content?.[0]?.text ?? "",
366
+ model: data.model,
367
+ usage: data.usage ? {
368
+ promptTokens: data.usage.input_tokens,
369
+ completionTokens: data.usage.output_tokens,
370
+ totalTokens: data.usage.input_tokens + data.usage.output_tokens
371
+ } : void 0,
372
+ finishReason: data.stop_reason ?? void 0
373
+ };
374
+ }
375
+ };
376
+ var SDKROUTER_BASE_URL = "https://llm.sdkrouter.com/v1";
377
+ function buildModelAlias(tier, options) {
378
+ const parts = [tier];
379
+ if (options) {
380
+ if (options.vision) parts.push("vision");
381
+ if (options.tools) parts.push("tools");
382
+ if (options.agents) parts.push("agents");
383
+ if (options.json) parts.push("json");
384
+ if (options.streaming) parts.push("streaming");
385
+ if (options.long) parts.push("long");
386
+ if (options.image) parts.push("image");
387
+ if (options.code) parts.push("code");
388
+ if (options.reasoning) parts.push("reasoning");
389
+ if (options.creative) parts.push("creative");
390
+ if (options.chat) parts.push("chat");
391
+ if (options.analysis) parts.push("analysis");
392
+ }
393
+ return "@" + parts.join("+");
394
+ }
395
+ var Model = {
396
+ /** Cheapest available model */
397
+ cheap: (options) => buildModelAlias("cheap", options),
398
+ /** Budget-friendly with decent quality */
399
+ budget: (options) => buildModelAlias("budget", options),
400
+ /** Standard tier */
401
+ standard: (options) => buildModelAlias("standard", options),
402
+ /** Best quality/price ratio (recommended) */
403
+ balanced: (options) => buildModelAlias("balanced", options),
404
+ /** Highest quality model */
405
+ smart: (options) => buildModelAlias("smart", options),
406
+ /** Lowest latency model */
407
+ fast: (options) => buildModelAlias("fast", options),
408
+ /** Top-tier premium model */
409
+ premium: (options) => buildModelAlias("premium", options),
410
+ /**
411
+ * Build alias from raw strings (escape hatch)
412
+ *
413
+ * @example Model.alias('cheap', 'vision', 'code') // '@cheap+vision+code'
414
+ */
415
+ alias: (tier, ...modifiers) => "@" + [tier, ...modifiers].join("+")
416
+ };
417
+ var ModelPresets = {
418
+ /** Translation: cheap + json mode */
419
+ translation: Model.cheap({ json: true }),
420
+ /** Code generation: balanced + code */
421
+ code: Model.balanced({ code: true }),
422
+ /** Code with tools: balanced + code + tools */
423
+ codeWithTools: Model.balanced({ code: true, tools: true }),
424
+ /** Vision: balanced + vision */
425
+ vision: Model.balanced({ vision: true }),
426
+ /** Reasoning: smart + reasoning */
427
+ reasoning: Model.smart({ reasoning: true }),
428
+ /** Creative writing: balanced + creative */
429
+ creative: Model.balanced({ creative: true }),
430
+ /** Fast chat: fast + chat */
431
+ fastChat: Model.fast({ chat: true }),
432
+ /** Analysis: balanced + analysis */
433
+ analysis: Model.balanced({ analysis: true }),
434
+ /** Agents: smart + agents + tools */
435
+ agents: Model.smart({ agents: true, tools: true })
436
+ };
437
+ var SDKRouterProvider = class extends BaseLLMProvider {
438
+ constructor(config) {
439
+ const model = config.model ?? (config.tier ? buildModelAlias(config.tier, config.modelOptions) : "@balanced");
440
+ super({
441
+ model,
442
+ ...config
443
+ });
444
+ __publicField(this, "provider", "sdkrouter");
445
+ __publicField(this, "client");
446
+ if (!config.apiKey) {
447
+ throw new Error("SDKRouter API key is required (SDKROUTER_API_KEY)");
448
+ }
449
+ this.client = new OpenAI__default.default({
450
+ apiKey: config.apiKey,
451
+ baseURL: config.baseUrl ?? SDKROUTER_BASE_URL
452
+ });
453
+ }
454
+ async chatMessages(messages, options) {
455
+ const model = options?.model ?? this.config.model;
456
+ const temperature = options?.temperature ?? this.config.temperature;
457
+ const maxTokens = options?.maxTokens ?? this.config.maxTokens;
458
+ const allMessages = options?.system ? [{ role: "system", content: options.system }, ...messages] : messages;
459
+ const response = await this.client.chat.completions.create({
460
+ model,
461
+ messages: allMessages.map((m) => ({
462
+ role: m.role,
463
+ content: m.content
464
+ })),
465
+ temperature,
466
+ max_tokens: maxTokens
467
+ });
468
+ const choice = response.choices[0];
469
+ return {
470
+ content: choice.message.content ?? "",
471
+ model: response.model,
472
+ usage: response.usage ? {
473
+ promptTokens: response.usage.prompt_tokens,
474
+ completionTokens: response.usage.completion_tokens,
475
+ totalTokens: response.usage.total_tokens
476
+ } : void 0,
477
+ finishReason: choice.finish_reason ?? void 0
478
+ };
479
+ }
480
+ };
481
+
482
+ // src/utils/env.ts
483
+ function getApiKey(provider) {
484
+ if (provider === "sdkrouter") {
485
+ return process.env.SDKROUTER_API_KEY;
486
+ }
487
+ if (provider === "openai") {
488
+ return process.env.OPENAI_API_KEY;
489
+ }
490
+ if (provider === "anthropic") {
491
+ return process.env.ANTHROPIC_API_KEY;
492
+ }
493
+ return process.env.SDKROUTER_API_KEY || process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY;
494
+ }
495
+ function detectProvider() {
496
+ const explicit = process.env.LLM_PROVIDER?.toLowerCase();
497
+ if (explicit === "sdkrouter" || explicit === "openai" || explicit === "anthropic") {
498
+ return explicit;
499
+ }
500
+ if (process.env.SDKROUTER_API_KEY) {
501
+ return "sdkrouter";
502
+ }
503
+ if (process.env.OPENAI_API_KEY) {
504
+ return "openai";
505
+ }
506
+ if (process.env.ANTHROPIC_API_KEY) {
507
+ return "anthropic";
508
+ }
509
+ return void 0;
510
+ }
511
+ function getDefaultModel(provider) {
512
+ if (provider === "sdkrouter") {
513
+ return process.env.SDKROUTER_MODEL || "@balanced";
514
+ }
515
+ if (provider === "openai") {
516
+ return process.env.OPENAI_MODEL || "gpt-4o-mini";
517
+ }
518
+ if (provider === "anthropic") {
519
+ return process.env.ANTHROPIC_MODEL || "claude-3-5-haiku-latest";
520
+ }
521
+ return "@balanced";
522
+ }
523
+
524
+ // src/client.ts
525
+ var LLMError = class extends Error {
526
+ constructor(message) {
527
+ super(message);
528
+ this.name = "LLMError";
529
+ }
530
+ };
531
+ function createLLMClient(config) {
532
+ const provider = config?.provider ?? detectProvider();
533
+ if (!provider) {
534
+ throw new LLMError(
535
+ "No LLM provider configured. Set SDKROUTER_API_KEY, OPENAI_API_KEY, or ANTHROPIC_API_KEY environment variable."
536
+ );
537
+ }
538
+ const apiKey = config?.apiKey ?? getApiKey(provider);
539
+ if (!apiKey) {
540
+ const envVar = provider === "sdkrouter" ? "SDKROUTER_API_KEY" : provider === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
541
+ throw new LLMError(
542
+ `No API key found for ${provider}. Set ${envVar} environment variable.`
543
+ );
544
+ }
545
+ const model = config?.model ?? getDefaultModel(provider);
546
+ const fullConfig = {
547
+ ...config,
548
+ provider,
549
+ apiKey,
550
+ model
551
+ };
552
+ if (provider === "sdkrouter") {
553
+ return new SDKRouterProvider(fullConfig);
554
+ }
555
+ if (provider === "openai") {
556
+ return new OpenAIProvider(fullConfig);
557
+ }
558
+ if (provider === "anthropic") {
559
+ return new AnthropicProvider(fullConfig);
560
+ }
561
+ throw new LLMError(`Unknown provider: ${provider}`);
562
+ }
563
+ function createSDKRouterClient(config) {
564
+ return createLLMClient({ ...config, provider: "sdkrouter" });
565
+ }
566
+ function createOpenAIClient(config) {
567
+ return createLLMClient({ ...config, provider: "openai" });
568
+ }
569
+ function createAnthropicClient(config) {
570
+ return createLLMClient({ ...config, provider: "anthropic" });
571
+ }
572
+ function isLLMConfigured() {
573
+ return detectProvider() !== void 0;
574
+ }
575
+ function getConfiguredProvider() {
576
+ return detectProvider();
577
+ }
578
+
579
+ // src/translator/types.ts
580
+ var LANGUAGE_NAMES = {
581
+ en: "English",
582
+ ru: "Russian",
583
+ ko: "Korean",
584
+ ja: "Japanese",
585
+ zh: "Chinese",
586
+ de: "German",
587
+ fr: "French",
588
+ es: "Spanish",
589
+ it: "Italian",
590
+ pt: "Portuguese",
591
+ "pt-BR": "Brazilian Portuguese",
592
+ ar: "Arabic",
593
+ nl: "Dutch",
594
+ tr: "Turkish",
595
+ pl: "Polish",
596
+ sv: "Swedish",
597
+ no: "Norwegian",
598
+ da: "Danish",
599
+ uk: "Ukrainian",
600
+ hi: "Hindi"
601
+ };
602
+
603
+ // src/translator/prompts.ts
604
+ function getLanguageName(code) {
605
+ return LANGUAGE_NAMES[code] ?? code;
606
+ }
607
+ function buildJsonTranslationPrompt(json, sourceLanguage, targetLanguage) {
608
+ const sourceName = getLanguageName(sourceLanguage);
609
+ const targetName = getLanguageName(targetLanguage);
610
+ return `Translate all string VALUES in this JSON from ${sourceName} to ${targetName}.
611
+
612
+ Rules:
613
+ - Translate ALL string values to ${targetName}
614
+ - Keep JSON keys unchanged (English)
615
+ - Skip: URLs, emails, numbers, "SKIP"
616
+ - Keep placeholders: {name}, {{var}}, %s
617
+
618
+ ${json}
619
+
620
+ Return ONLY the JSON with all values translated to ${targetName}:`;
621
+ }
622
+ var TranslationCache = class {
623
+ constructor(maxMemorySize = 1e3, storage) {
624
+ this.maxMemorySize = maxMemorySize;
625
+ this.storage = storage;
626
+ __publicField(this, "memoryCache", /* @__PURE__ */ new Map());
627
+ __publicField(this, "cacheOrder", []);
628
+ __publicField(this, "hits", 0);
629
+ __publicField(this, "misses", 0);
630
+ }
631
+ /**
632
+ * Generate hash for text
633
+ */
634
+ getTextHash(text) {
635
+ return crypto__default.default.createHash("md5").update(text).digest("hex");
636
+ }
637
+ /**
638
+ * Get storage key for language pair
639
+ */
640
+ getStorageKey(sourceLang, targetLang) {
641
+ return `translator:${sourceLang}-${targetLang}`;
642
+ }
643
+ /**
644
+ * Load from persistent storage
645
+ */
646
+ loadFromStorage(sourceLang, targetLang) {
647
+ if (!this.storage) return {};
648
+ try {
649
+ const key = this.getStorageKey(sourceLang, targetLang);
650
+ const data = this.storage.getItem(key);
651
+ return data ? JSON.parse(data) : {};
652
+ } catch {
653
+ return {};
654
+ }
655
+ }
656
+ /**
657
+ * Save to persistent storage
658
+ */
659
+ saveToStorage(sourceLang, targetLang, cache) {
660
+ if (!this.storage) return;
661
+ try {
662
+ const key = this.getStorageKey(sourceLang, targetLang);
663
+ this.storage.setItem(key, JSON.stringify(cache));
664
+ } catch {
665
+ }
666
+ }
667
+ /**
668
+ * Evict oldest entries if memory is full
669
+ */
670
+ evictIfNeeded() {
671
+ while (this.memoryCache.size >= this.maxMemorySize && this.cacheOrder.length > 0) {
672
+ const oldestKey = this.cacheOrder.shift();
673
+ this.memoryCache.delete(oldestKey);
674
+ }
675
+ }
676
+ /**
677
+ * Get translation from cache
678
+ */
679
+ get(text, sourceLang, targetLang) {
680
+ const textHash = this.getTextHash(text);
681
+ const cacheKey = `${sourceLang}-${targetLang}:${textHash}`;
682
+ if (this.memoryCache.has(cacheKey)) {
683
+ this.hits++;
684
+ return this.memoryCache.get(cacheKey);
685
+ }
686
+ const fileCache = this.loadFromStorage(sourceLang, targetLang);
687
+ if (textHash in fileCache) {
688
+ const translation = fileCache[textHash];
689
+ this.evictIfNeeded();
690
+ this.memoryCache.set(cacheKey, translation);
691
+ this.cacheOrder.push(cacheKey);
692
+ this.hits++;
693
+ return translation;
694
+ }
695
+ this.misses++;
696
+ return void 0;
697
+ }
698
+ /**
699
+ * Store translation in cache
700
+ */
701
+ set(text, sourceLang, targetLang, translation) {
702
+ const textHash = this.getTextHash(text);
703
+ const cacheKey = `${sourceLang}-${targetLang}:${textHash}`;
704
+ this.evictIfNeeded();
705
+ this.memoryCache.set(cacheKey, translation);
706
+ if (!this.cacheOrder.includes(cacheKey)) {
707
+ this.cacheOrder.push(cacheKey);
708
+ }
709
+ const fileCache = this.loadFromStorage(sourceLang, targetLang);
710
+ fileCache[textHash] = translation;
711
+ this.saveToStorage(sourceLang, targetLang, fileCache);
712
+ }
713
+ /**
714
+ * Get multiple translations at once
715
+ */
716
+ getMany(texts, sourceLang, targetLang) {
717
+ const cached = /* @__PURE__ */ new Map();
718
+ const uncached = [];
719
+ for (const text of texts) {
720
+ const translation = this.get(text, sourceLang, targetLang);
721
+ if (translation !== void 0) {
722
+ cached.set(text, translation);
723
+ } else {
724
+ uncached.push(text);
725
+ }
726
+ }
727
+ return { cached, uncached };
728
+ }
729
+ /**
730
+ * Store multiple translations at once
731
+ */
732
+ setMany(translations, sourceLang, targetLang) {
733
+ for (const [text, translation] of translations) {
734
+ this.set(text, sourceLang, targetLang, translation);
735
+ }
736
+ }
737
+ /**
738
+ * Clear cache
739
+ */
740
+ clear(sourceLang, targetLang) {
741
+ if (sourceLang && targetLang) {
742
+ const prefix = `${sourceLang}-${targetLang}:`;
743
+ for (const key of [...this.memoryCache.keys()]) {
744
+ if (key.startsWith(prefix)) {
745
+ this.memoryCache.delete(key);
746
+ const idx = this.cacheOrder.indexOf(key);
747
+ if (idx !== -1) this.cacheOrder.splice(idx, 1);
748
+ }
749
+ }
750
+ if (this.storage) {
751
+ this.storage.removeItem(this.getStorageKey(sourceLang, targetLang));
752
+ }
753
+ } else {
754
+ this.memoryCache.clear();
755
+ this.cacheOrder = [];
756
+ this.hits = 0;
757
+ this.misses = 0;
758
+ }
759
+ }
760
+ /**
761
+ * Get cache statistics
762
+ */
763
+ getStats() {
764
+ const languagePairs = [];
765
+ const pairCounts = /* @__PURE__ */ new Map();
766
+ for (const key of this.memoryCache.keys()) {
767
+ const pair = key.split(":")[0];
768
+ pairCounts.set(pair, (pairCounts.get(pair) || 0) + 1);
769
+ }
770
+ for (const [pair, count] of pairCounts) {
771
+ languagePairs.push({ pair, translations: count });
772
+ }
773
+ return {
774
+ memorySize: this.memoryCache.size,
775
+ hits: this.hits,
776
+ misses: this.misses,
777
+ languagePairs
778
+ };
779
+ }
780
+ };
781
+ function createCache(maxMemorySize, storage) {
782
+ return new TranslationCache(maxMemorySize, storage);
783
+ }
784
+
785
+ // src/translator/json-translator.ts
786
+ var DEFAULT_TRANSLATION_MODEL = "openai/gpt-4o-mini";
787
+ var JsonTranslator = class {
788
+ constructor(client, cache, defaultModel) {
789
+ this.client = client;
790
+ __publicField(this, "cache");
791
+ __publicField(this, "defaultModel");
792
+ this.cache = cache ?? createCache();
793
+ this.defaultModel = defaultModel ?? DEFAULT_TRANSLATION_MODEL;
794
+ }
795
+ /**
796
+ * Detect language from text
797
+ */
798
+ detectLanguage(text) {
799
+ const script = detectScript(text);
800
+ switch (script) {
801
+ case "cjk":
802
+ return "zh";
803
+ case "cyrillic":
804
+ return "ru";
805
+ case "arabic":
806
+ return "ar";
807
+ default:
808
+ return "en";
809
+ }
810
+ }
811
+ /**
812
+ * Check if text needs translation
813
+ */
814
+ needsTranslation(text, sourceLang, targetLang) {
815
+ if (!text || !text.trim()) return false;
816
+ if (isTechnicalContent(text)) return false;
817
+ if (sourceLang === targetLang) return false;
818
+ return true;
819
+ }
820
+ /**
821
+ * Translate single text
822
+ */
823
+ async translateText(text, targetLanguage, options) {
824
+ if (!text || !text.trim()) return text;
825
+ const sourceLang = options?.sourceLanguage ?? "auto";
826
+ const actualSource = sourceLang === "auto" ? this.detectLanguage(text) : sourceLang;
827
+ if (!this.needsTranslation(text, actualSource, targetLanguage)) {
828
+ return text;
829
+ }
830
+ const cached = this.cache.get(text, actualSource, targetLanguage);
831
+ if (cached) return cached;
832
+ const response = await this.client.chat(
833
+ `Translate this text to ${targetLanguage}. Return ONLY the translation:
834
+
835
+ ${text}`,
836
+ {
837
+ ...options,
838
+ model: options?.model ?? this.defaultModel,
839
+ temperature: 0
840
+ }
841
+ );
842
+ const translated = response.content.trim();
843
+ this.cache.set(text, actualSource, targetLanguage, translated);
844
+ return translated;
845
+ }
846
+ /**
847
+ * Translate JSON object with smart text-level caching
848
+ *
849
+ * @example
850
+ * ```ts
851
+ * const translator = new JsonTranslator(llm)
852
+ * const result = await translator.translate(
853
+ * { title: 'Hello', items: ['World', 'Earth'] },
854
+ * 'ru'
855
+ * )
856
+ * // { data: { title: 'Привет', items: ['Мир', 'Земля'] }, valid: true, ... }
857
+ * ```
858
+ */
859
+ async translate(data, targetLanguage, options) {
860
+ const sourceLang = options?.sourceLanguage ?? "auto";
861
+ const translatableTexts = this.extractTranslatableTexts(data, sourceLang, targetLanguage);
862
+ if (translatableTexts.size === 0) {
863
+ return {
864
+ data,
865
+ valid: true,
866
+ errors: [],
867
+ retries: 0,
868
+ sourceLanguage: sourceLang,
869
+ targetLanguage
870
+ };
871
+ }
872
+ let actualSource = sourceLang;
873
+ if (sourceLang === "auto") {
874
+ const firstText = [...translatableTexts][0];
875
+ actualSource = this.detectLanguage(firstText);
876
+ }
877
+ const { cached, uncached } = this.cache.getMany(
878
+ [...translatableTexts],
879
+ actualSource,
880
+ targetLanguage
881
+ );
882
+ if (uncached.length === 0) {
883
+ return {
884
+ data: this.applyTranslations(data, cached),
885
+ valid: true,
886
+ errors: [],
887
+ retries: 0,
888
+ sourceLanguage: actualSource,
889
+ targetLanguage
890
+ };
891
+ }
892
+ const partialJson = this.createPartialJson(data, new Set(uncached));
893
+ const jsonStr = JSON.stringify(partialJson, null, 2);
894
+ try {
895
+ const prompt = buildJsonTranslationPrompt(jsonStr, actualSource, targetLanguage);
896
+ const response = await this.client.chat(prompt, {
897
+ ...options,
898
+ model: options?.model ?? this.defaultModel,
899
+ temperature: 0
900
+ });
901
+ const translatedPartial = extractJson(response.content);
902
+ const newTranslations = this.extractTranslationsByComparison(
903
+ partialJson,
904
+ translatedPartial,
905
+ uncached
906
+ );
907
+ this.cache.setMany(newTranslations, actualSource, targetLanguage);
908
+ const allTranslations = new Map([...cached, ...newTranslations]);
909
+ return {
910
+ data: this.applyTranslations(data, allTranslations),
911
+ valid: true,
912
+ errors: [],
913
+ retries: 0,
914
+ sourceLanguage: actualSource,
915
+ targetLanguage
916
+ };
917
+ } catch (error) {
918
+ const errorMsg = error instanceof Error ? error.message : String(error);
919
+ console.error("Translation failed:", errorMsg);
920
+ return {
921
+ data: cached.size > 0 ? this.applyTranslations(data, cached) : data,
922
+ valid: false,
923
+ errors: [errorMsg],
924
+ retries: 0,
925
+ sourceLanguage: actualSource,
926
+ targetLanguage
927
+ };
928
+ }
929
+ }
930
+ /**
931
+ * Translate to multiple languages in parallel
932
+ */
933
+ async translateToMany(data, targetLanguages, options) {
934
+ const results = /* @__PURE__ */ new Map();
935
+ const promises = targetLanguages.map(async (lang) => {
936
+ const result = await this.translate(data, lang, options);
937
+ return { lang, result };
938
+ });
939
+ const settled = await Promise.all(promises);
940
+ for (const { lang, result } of settled) {
941
+ results.set(lang, result);
942
+ }
943
+ return results;
944
+ }
945
+ /**
946
+ * Extract all translatable texts from object
947
+ */
948
+ extractTranslatableTexts(obj, sourceLang, targetLang) {
949
+ const texts = /* @__PURE__ */ new Set();
950
+ const extract = (item) => {
951
+ if (typeof item === "string") {
952
+ if (this.needsTranslation(item, sourceLang, targetLang)) {
953
+ texts.add(item);
954
+ }
955
+ } else if (Array.isArray(item)) {
956
+ for (const i of item) extract(i);
957
+ } else if (item !== null && typeof item === "object") {
958
+ for (const v of Object.values(item)) extract(v);
959
+ }
960
+ };
961
+ extract(obj);
962
+ return texts;
963
+ }
964
+ /**
965
+ * Apply translations to object
966
+ */
967
+ applyTranslations(obj, translations) {
968
+ const apply = (item) => {
969
+ if (typeof item === "string") {
970
+ return translations.get(item) ?? item;
971
+ } else if (Array.isArray(item)) {
972
+ return item.map(apply);
973
+ } else if (item !== null && typeof item === "object") {
974
+ const result = {};
975
+ for (const [k, v] of Object.entries(item)) {
976
+ result[k] = apply(v);
977
+ }
978
+ return result;
979
+ }
980
+ return item;
981
+ };
982
+ return apply(obj);
983
+ }
984
+ /**
985
+ * Create partial JSON with only texts that need translation
986
+ */
987
+ createPartialJson(data, textsToInclude) {
988
+ const filter = (obj) => {
989
+ if (typeof obj === "string") {
990
+ return textsToInclude.has(obj) ? obj : "SKIP";
991
+ } else if (Array.isArray(obj)) {
992
+ return obj.map(filter).filter((i) => this.hasTranslatable(i, textsToInclude));
993
+ } else if (obj !== null && typeof obj === "object") {
994
+ const result = {};
995
+ for (const [k, v] of Object.entries(obj)) {
996
+ const filtered = filter(v);
997
+ if (this.hasTranslatable(filtered, textsToInclude)) {
998
+ result[k] = filtered;
999
+ }
1000
+ }
1001
+ return result;
1002
+ }
1003
+ return obj;
1004
+ };
1005
+ return filter(data);
1006
+ }
1007
+ /**
1008
+ * Check if object contains translatable text
1009
+ */
1010
+ hasTranslatable(obj, textsSet) {
1011
+ if (typeof obj === "string") return textsSet.has(obj);
1012
+ if (Array.isArray(obj)) return obj.some((i) => this.hasTranslatable(i, textsSet));
1013
+ if (obj !== null && typeof obj === "object") {
1014
+ return Object.values(obj).some((v) => this.hasTranslatable(v, textsSet));
1015
+ }
1016
+ return false;
1017
+ }
1018
+ /**
1019
+ * Extract translations by comparing original and translated JSON
1020
+ */
1021
+ extractTranslationsByComparison(original, translated, uncachedTexts) {
1022
+ const translations = /* @__PURE__ */ new Map();
1023
+ const uncachedSet = new Set(uncachedTexts);
1024
+ const compare = (orig, trans) => {
1025
+ if (typeof orig === "string" && typeof trans === "string") {
1026
+ if (uncachedSet.has(orig) && trans !== "SKIP" && trans.trim()) {
1027
+ translations.set(orig, trans);
1028
+ }
1029
+ } else if (Array.isArray(orig) && Array.isArray(trans)) {
1030
+ for (let i = 0; i < Math.min(orig.length, trans.length); i++) {
1031
+ compare(orig[i], trans[i]);
1032
+ }
1033
+ } else if (orig !== null && typeof orig === "object" && trans !== null && typeof trans === "object") {
1034
+ for (const key of Object.keys(orig)) {
1035
+ if (key in trans) {
1036
+ compare(
1037
+ orig[key],
1038
+ trans[key]
1039
+ );
1040
+ }
1041
+ }
1042
+ }
1043
+ };
1044
+ compare(original, translated);
1045
+ return translations;
1046
+ }
1047
+ /**
1048
+ * Get translation statistics
1049
+ */
1050
+ getStats() {
1051
+ return this.cache.getStats();
1052
+ }
1053
+ /**
1054
+ * Clear translation cache
1055
+ */
1056
+ clearCache(sourceLang, targetLang) {
1057
+ this.cache.clear(sourceLang, targetLang);
1058
+ }
1059
+ };
1060
+ function createTranslator(client, configOrCache) {
1061
+ if (configOrCache instanceof TranslationCache) {
1062
+ return new JsonTranslator(client, configOrCache);
1063
+ }
1064
+ return new JsonTranslator(client, configOrCache?.cache, configOrCache?.model);
1065
+ }
1066
+
1067
+ // src/utils/schema.ts
1068
+ function generateSchemaFromExample(example) {
1069
+ if (example === null) {
1070
+ return { type: "null" };
1071
+ }
1072
+ if (Array.isArray(example)) {
1073
+ const itemSchema = example.length > 0 ? generateSchemaFromExample(example[0]) : { type: "string" };
1074
+ return { type: "array", items: itemSchema };
1075
+ }
1076
+ if (typeof example === "object") {
1077
+ const properties = {};
1078
+ const required = [];
1079
+ for (const [key, value] of Object.entries(example)) {
1080
+ properties[key] = generateSchemaFromExample(value);
1081
+ required.push(key);
1082
+ }
1083
+ return { type: "object", properties, required };
1084
+ }
1085
+ return { type: typeof example };
1086
+ }
1087
+ function schemaToPromptString(schema) {
1088
+ return JSON.stringify(schema, null, 2);
1089
+ }
1090
+ async function getStructuredOutput(client, prompt, schema, options) {
1091
+ const response = await client.chat(prompt, {
1092
+ ...options,
1093
+ temperature: 0,
1094
+ system: options?.system ?? "Return ONLY valid JSON matching the requested structure."
1095
+ });
1096
+ try {
1097
+ const parsed = extractJson(response.content);
1098
+ const result = schema.safeParse(parsed);
1099
+ if (result.success) {
1100
+ return { data: result.data, response };
1101
+ }
1102
+ return {
1103
+ error: "Schema validation failed",
1104
+ raw: parsed
1105
+ };
1106
+ } catch (error) {
1107
+ return {
1108
+ error: error instanceof Error ? error.message : "Failed to parse JSON",
1109
+ raw: response.content
1110
+ };
1111
+ }
1112
+ }
1113
+ async function getStructuredOutputWithRetry(client, prompt, schema, options) {
1114
+ const maxRetries = options?.maxRetries ?? 2;
1115
+ let retries = 0;
1116
+ let lastError = "";
1117
+ let lastRaw;
1118
+ while (retries <= maxRetries) {
1119
+ const result = await getStructuredOutput(client, prompt, schema, options);
1120
+ if ("data" in result) {
1121
+ return { data: result.data, retries };
1122
+ }
1123
+ lastError = result.error;
1124
+ lastRaw = result.raw;
1125
+ retries++;
1126
+ if (retries <= maxRetries) {
1127
+ console.warn(`Structured output validation failed (attempt ${retries}/${maxRetries + 1})`);
1128
+ }
1129
+ }
1130
+ return { error: lastError, raw: lastRaw, retries };
1131
+ }
1132
+
1133
+ exports.JsonTranslator = JsonTranslator;
1134
+ exports.LANGUAGE_NAMES = LANGUAGE_NAMES;
1135
+ exports.LLMError = LLMError;
1136
+ exports.Model = Model;
1137
+ exports.ModelPresets = ModelPresets;
1138
+ exports.SDKROUTER_BASE_URL = SDKROUTER_BASE_URL;
1139
+ exports.TranslationCache = TranslationCache;
1140
+ exports.buildModelAlias = buildModelAlias;
1141
+ exports.createAnthropicClient = createAnthropicClient;
1142
+ exports.createCache = createCache;
1143
+ exports.createLLMClient = createLLMClient;
1144
+ exports.createOpenAIClient = createOpenAIClient;
1145
+ exports.createSDKRouterClient = createSDKRouterClient;
1146
+ exports.createTranslator = createTranslator;
1147
+ exports.detectProvider = detectProvider;
1148
+ exports.detectScript = detectScript;
1149
+ exports.extractJson = extractJson;
1150
+ exports.extractPlaceholders = extractPlaceholders;
1151
+ exports.generateSchemaFromExample = generateSchemaFromExample;
1152
+ exports.getApiKey = getApiKey;
1153
+ exports.getConfiguredProvider = getConfiguredProvider;
1154
+ exports.getDefaultModel = getDefaultModel;
1155
+ exports.getStructuredOutput = getStructuredOutput;
1156
+ exports.getStructuredOutputWithRetry = getStructuredOutputWithRetry;
1157
+ exports.isLLMConfigured = isLLMConfigured;
1158
+ exports.isTechnicalContent = isTechnicalContent;
1159
+ exports.schemaToPromptString = schemaToPromptString;
1160
+ exports.validateJsonKeys = validateJsonKeys;
1161
+ exports.validateTranslation = validateTranslation;
1162
+ exports.validateTranslationKeys = validateJsonKeys;
1163
+ //# sourceMappingURL=index.cjs.map
1164
+ //# sourceMappingURL=index.cjs.map