@shipi18n/core 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @shipi18n/core
2
+
3
+ ## 2.0.0
4
+
5
+ Initial open-source release of the **bring-your-own-LLM** translation engine.
6
+
7
+ - Provider-agnostic adapters: `anthropic` (default, `claude-opus-4-8`), `openai`, or a custom
8
+ `{ complete }` adapter. Optional peer deps loaded lazily.
9
+ - `translateJSON({ content, from, to, provider, apiKey?, model?, existing? })` — structure-preserving
10
+ flatten/unflatten, batching, placeholder preserve + validate, and incremental (only-changed) mode.
11
+ - No hosted API and no Shipi18n account — your key calls your LLM directly.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,16 @@
1
+ @shipi18n/core
2
+ Copyright 2025 Shipi18n
3
+
4
+ This product includes software developed at Shipi18n (https://github.com/Shipi18n).
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @shipi18n/core
2
+
3
+ Open-source, **bring-your-own-LLM** i18n translation engine. Translate locale JSON with your own
4
+ OpenAI or Anthropic key — no Shipi18n account, no hosted API, no per-word fees. Provider-agnostic and
5
+ extensible.
6
+
7
+ ```bash
8
+ npm i @shipi18n/core @anthropic-ai/sdk # or: npm i @shipi18n/core openai
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```js
14
+ import { translateJSON } from '@shipi18n/core'
15
+
16
+ const { result, stats } = await translateJSON({
17
+ content: { greeting: 'Hello {{name}}', items: 'You have {{count}} items' },
18
+ from: 'en',
19
+ to: 'es',
20
+ provider: 'anthropic', // 'anthropic' | 'openai' | a custom { complete } adapter
21
+ apiKey: process.env.ANTHROPIC_API_KEY, // optional — falls back to the provider's env var
22
+ })
23
+
24
+ console.log(result) // { greeting: 'Hola {{name}}', items: 'Tienes {{count}} elementos' }
25
+ console.log(stats) // { translated, reused, placeholderWarnings }
26
+ ```
27
+
28
+ The API key is resolved from `apiKey` or, if omitted, the provider's env var
29
+ (`ANTHROPIC_API_KEY` / `OPENAI_API_KEY`). Your key is used to call **your** LLM directly.
30
+
31
+ ## What it does
32
+
33
+ - **Structure-preserving** — flattens/unflattens nested JSON; non-string leaves pass through untouched.
34
+ - **Placeholder-safe** — preserves and validates `{{name}}`, `{count}`, `%s`, `%d`, `%1$s`, `$t(...)`, `%{name}`, and HTML tags.
35
+ - **Batched** — groups strings per request to minimize round-trips.
36
+ - **Incremental** — pass `existing` to reuse prior translations and only translate new/changed keys.
37
+
38
+ ## Incremental translation
39
+
40
+ ```js
41
+ const { result } = await translateJSON({
42
+ content: source, from: 'en', to: 'fr',
43
+ provider: 'anthropic',
44
+ existing: previousFrench, // only new/empty keys are sent to the LLM
45
+ })
46
+ ```
47
+
48
+ ## Custom provider
49
+
50
+ Any object with a `complete(prompt, opts) => Promise<string>` method works — bring any model:
51
+
52
+ ```js
53
+ const myAdapter = {
54
+ name: 'my-llm',
55
+ async complete(prompt) { /* call your model, return its text */ },
56
+ }
57
+ await translateJSON({ content, from: 'en', to: 'de', provider: myAdapter })
58
+ ```
59
+
60
+ ## API
61
+
62
+ - `translateJSON({ content, from, to, provider, apiKey?, model?, existing? })` → `{ result, stats }`
63
+ - `translateStrings(texts, { adapter, from, to, batchSize? })` → `string[]`
64
+ - `flatten(obj)` / `unflatten(flat)`
65
+ - `extractPlaceholders(str)` / `validatePlaceholders(source, translation)`
66
+ - `getLanguageName(code)`
67
+ - `anthropicAdapter(config)` / `openaiAdapter(config)` / `resolveAdapter(provider, config)`
68
+
69
+ ## License
70
+
71
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@shipi18n/core",
3
+ "version": "2.0.0",
4
+ "description": "Open-source, bring-your-own-LLM i18n translation engine. Provider-agnostic (OpenAI, Anthropic, ...).",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./adapters": "./src/adapters/index.js"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "!src/__tests__",
14
+ "LICENSE",
15
+ "NOTICE",
16
+ "README.md",
17
+ "CHANGELOG.md"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "keywords": [
23
+ "i18n",
24
+ "translation",
25
+ "llm",
26
+ "openai",
27
+ "anthropic",
28
+ "localization",
29
+ "bring-your-own-key"
30
+ ],
31
+ "license": "Apache-2.0",
32
+ "author": "Shipi18n",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/Shipi18n/shipi18n.git",
36
+ "directory": "packages/core"
37
+ },
38
+ "peerDependencies": {
39
+ "@anthropic-ai/sdk": "^0.114.0",
40
+ "openai": ">=4.0.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@anthropic-ai/sdk": {
44
+ "optional": true
45
+ },
46
+ "openai": {
47
+ "optional": true
48
+ }
49
+ },
50
+ "devDependencies": {
51
+ "jest": "^29.7.0"
52
+ },
53
+ "scripts": {
54
+ "test": "NODE_OPTIONS='--experimental-vm-modules' jest",
55
+ "test:watch": "NODE_OPTIONS='--experimental-vm-modules' jest --watch"
56
+ }
57
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * LLM provider adapters. Each adapter exposes a single method:
3
+ * complete(prompt: string, opts?: { maxTokens?: number }): Promise<string>
4
+ *
5
+ * This is the ONLY provider-specific surface in @shipi18n/core. The translation
6
+ * engine, prompts, placeholder handling, and batching are all provider-agnostic.
7
+ *
8
+ * @typedef {Object} LLMAdapter
9
+ * @property {(prompt: string, opts?: { maxTokens?: number }) => Promise<string>} complete
10
+ * @property {string} name
11
+ */
12
+
13
+ /**
14
+ * Anthropic Claude adapter. Requires the optional peer dep `@anthropic-ai/sdk`.
15
+ * Key resolved from opts.apiKey or the ANTHROPIC_API_KEY env var (SDK default).
16
+ * @param {{ apiKey?: string, model?: string }} [config]
17
+ * @returns {LLMAdapter}
18
+ */
19
+ export function anthropicAdapter(config = {}) {
20
+ const model = config.model || 'claude-opus-4-8'
21
+ let clientPromise = null
22
+ const getClient = async () => {
23
+ if (!clientPromise) {
24
+ clientPromise = import('@anthropic-ai/sdk')
25
+ .then(({ default: Anthropic }) => new Anthropic(config.apiKey ? { apiKey: config.apiKey } : {}))
26
+ .catch(() => {
27
+ throw new Error(
28
+ "The 'anthropic' provider requires the '@anthropic-ai/sdk' package. Install it with: npm i @anthropic-ai/sdk"
29
+ )
30
+ })
31
+ }
32
+ return clientPromise
33
+ }
34
+
35
+ return {
36
+ name: 'anthropic',
37
+ async complete(prompt, opts = {}) {
38
+ const client = await getClient()
39
+ // Adaptive thinking + generous default; the model decides depth.
40
+ const res = await client.messages.create({
41
+ model,
42
+ max_tokens: opts.maxTokens || 4096,
43
+ messages: [{ role: 'user', content: prompt }],
44
+ })
45
+ const text = (res.content || []).find((b) => b.type === 'text')
46
+ if (!text) throw new Error('Anthropic response contained no text block')
47
+ return text.text.trim()
48
+ },
49
+ }
50
+ }
51
+
52
+ /**
53
+ * OpenAI adapter. Requires the optional peer dep `openai`.
54
+ * Key resolved from opts.apiKey or the OPENAI_API_KEY env var (SDK default).
55
+ * @param {{ apiKey?: string, model?: string }} [config]
56
+ * @returns {LLMAdapter}
57
+ */
58
+ export function openaiAdapter(config = {}) {
59
+ const model = config.model || 'gpt-4o'
60
+ let clientPromise = null
61
+ const getClient = async () => {
62
+ if (!clientPromise) {
63
+ clientPromise = import('openai')
64
+ .then(({ default: OpenAI }) => new OpenAI(config.apiKey ? { apiKey: config.apiKey } : {}))
65
+ .catch(() => {
66
+ throw new Error(
67
+ "The 'openai' provider requires the 'openai' package. Install it with: npm i openai"
68
+ )
69
+ })
70
+ }
71
+ return clientPromise
72
+ }
73
+
74
+ return {
75
+ name: 'openai',
76
+ async complete(prompt, opts = {}) {
77
+ const client = await getClient()
78
+ const res = await client.chat.completions.create({
79
+ model,
80
+ max_tokens: opts.maxTokens || 4096,
81
+ messages: [{ role: 'user', content: prompt }],
82
+ })
83
+ const content = res.choices?.[0]?.message?.content
84
+ if (!content) throw new Error('OpenAI response contained no content')
85
+ return content.trim()
86
+ },
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Resolve a provider name (+ config) to an adapter instance.
92
+ * @param {'anthropic'|'openai'|LLMAdapter} provider
93
+ * @param {{ apiKey?: string, model?: string }} [config]
94
+ * @returns {LLMAdapter}
95
+ */
96
+ export function resolveAdapter(provider, config = {}) {
97
+ if (provider && typeof provider === 'object' && typeof provider.complete === 'function') {
98
+ return provider // already an adapter (also lets users bring a custom provider)
99
+ }
100
+ switch (provider) {
101
+ case 'anthropic':
102
+ return anthropicAdapter(config)
103
+ case 'openai':
104
+ return openaiAdapter(config)
105
+ default:
106
+ throw new Error(
107
+ `Unknown provider '${provider}'. Use 'anthropic', 'openai', or pass a custom { complete } adapter.`
108
+ )
109
+ }
110
+ }
package/src/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @shipi18n/core — open-source, bring-your-own-LLM i18n translation engine.
3
+ *
4
+ * @example
5
+ * import { translateJSON } from '@shipi18n/core'
6
+ * const { result } = await translateJSON({
7
+ * content: { greeting: 'Hello {{name}}' },
8
+ * from: 'en', to: 'es',
9
+ * provider: 'anthropic', // or 'openai', or a custom { complete } adapter
10
+ * apiKey: process.env.ANTHROPIC_API_KEY,
11
+ * })
12
+ */
13
+ export { translateJSON, translateStrings, flatten, unflatten } from './translate.js'
14
+ export { extractPlaceholders, validatePlaceholders } from './placeholders.js'
15
+ export { getLanguageName, LANGUAGE_NAMES } from './languages.js'
16
+ export { anthropicAdapter, openaiAdapter, resolveAdapter } from './adapters/index.js'
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Language code → human-readable name. Ported from the backend so prompts read
3
+ * naturally ("Translate from English to Spanish") rather than using bare codes.
4
+ */
5
+ export const LANGUAGE_NAMES = {
6
+ en: 'English', es: 'Spanish', fr: 'French', de: 'German', it: 'Italian',
7
+ pt: 'Portuguese', nl: 'Dutch', ru: 'Russian', zh: 'Chinese', 'zh-CN': 'Chinese (Simplified)',
8
+ 'zh-TW': 'Chinese (Traditional)', ja: 'Japanese', ko: 'Korean', ar: 'Arabic', hi: 'Hindi',
9
+ tr: 'Turkish', pl: 'Polish', vi: 'Vietnamese', th: 'Thai', id: 'Indonesian', ms: 'Malay',
10
+ sv: 'Swedish', da: 'Danish', no: 'Norwegian', fi: 'Finnish', cs: 'Czech', sk: 'Slovak',
11
+ hu: 'Hungarian', ro: 'Romanian', bg: 'Bulgarian', uk: 'Ukrainian', el: 'Greek',
12
+ he: 'Hebrew', fa: 'Persian',
13
+ }
14
+
15
+ /**
16
+ * @param {string} code e.g. "es" or "pt-BR"
17
+ * @returns {string} the language name, falling back to the base code, then the code
18
+ */
19
+ export function getLanguageName(code) {
20
+ if (!code) return code
21
+ if (LANGUAGE_NAMES[code]) return LANGUAGE_NAMES[code]
22
+ const base = code.split('-')[0]
23
+ return LANGUAGE_NAMES[base] || code
24
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Placeholder detection + validation.
3
+ *
4
+ * i18n strings embed placeholders that must survive translation byte-for-byte:
5
+ * - i18next / ICU: {{name}}, {count}
6
+ * - printf: %s, %d, %1$s
7
+ * - i18next nesting: $t(some.key)
8
+ * - React-intl: {name}
9
+ * - Ruby / others: %{name}
10
+ *
11
+ * The translation prompt instructs the model to preserve these; these helpers
12
+ * VERIFY the model obeyed, so callers can retry or flag drift.
13
+ */
14
+
15
+ const PLACEHOLDER_PATTERNS = [
16
+ /\{\{[^}]+\}\}/g, // {{name}}
17
+ /\$t\([^)]*\)/g, // $t(key)
18
+ /%\{[^}]+\}/g, // %{name}
19
+ /%\d+\$[sdfx]/g, // %1$s
20
+ /%[sdfx]/g, // %s %d
21
+ /\{[a-zA-Z0-9_.]+\}/g, // {count} {name} (after the {{ }} pass)
22
+ ]
23
+
24
+ /**
25
+ * Extract all placeholders from a string, in a stable, comparable multiset.
26
+ * @param {string} str
27
+ * @returns {string[]} sorted list of placeholder tokens (duplicates preserved)
28
+ */
29
+ export function extractPlaceholders(str) {
30
+ if (typeof str !== 'string') return []
31
+ let working = str
32
+ const found = []
33
+ for (const pattern of PLACEHOLDER_PATTERNS) {
34
+ const matches = working.match(pattern) || []
35
+ for (const m of matches) found.push(m)
36
+ // blank out matched spans so later, looser patterns don't double-count
37
+ working = working.replace(pattern, (m) => ' '.repeat(m.length))
38
+ }
39
+ return found.sort()
40
+ }
41
+
42
+ /**
43
+ * Does the translation preserve exactly the placeholders of the source?
44
+ * @param {string} source
45
+ * @param {string} translation
46
+ * @returns {{ ok: boolean, missing: string[], added: string[] }}
47
+ */
48
+ export function validatePlaceholders(source, translation) {
49
+ const src = extractPlaceholders(source)
50
+ const out = extractPlaceholders(translation)
51
+ const outCounts = tally(out)
52
+ const srcCounts = tally(src)
53
+ const missing = []
54
+ const added = []
55
+ for (const [ph, n] of Object.entries(srcCounts)) {
56
+ const diff = n - (outCounts[ph] || 0)
57
+ for (let i = 0; i < diff; i++) missing.push(ph)
58
+ }
59
+ for (const [ph, n] of Object.entries(outCounts)) {
60
+ const diff = n - (srcCounts[ph] || 0)
61
+ for (let i = 0; i < diff; i++) added.push(ph)
62
+ }
63
+ return { ok: missing.length === 0 && added.length === 0, missing, added }
64
+ }
65
+
66
+ function tally(arr) {
67
+ const t = {}
68
+ for (const x of arr) t[x] = (t[x] || 0) + 1
69
+ return t
70
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Core translation engine — provider-agnostic. Ported from the backend's
3
+ * context-aware Claude path, with the single `client.messages.create` call
4
+ * replaced by an injected LLMAdapter.
5
+ */
6
+ import { resolveAdapter } from './adapters/index.js'
7
+ import { getLanguageName } from './languages.js'
8
+ import { validatePlaceholders } from './placeholders.js'
9
+
10
+ const BATCH_PROMPT = `You are a professional software localizer. Translate each UI string accurately.
11
+
12
+ Translate from {SOURCE_LANG} to {TARGET_LANG}.
13
+
14
+ STRINGS TO TRANSLATE (JSON array):
15
+ {TEXTS}
16
+
17
+ Requirements:
18
+ 1. Preserve ALL placeholders exactly as they appear: {{name}}, {count}, %s, %d, %1$s, $t(...), %{name}.
19
+ 2. Do not translate placeholder contents, HTML tags, or code.
20
+ 3. Keep the tone appropriate for application UI (concise, natural).
21
+ 4. Return ONLY a JSON array of translated strings, in the same order and length as the input. No prose, no markdown fences.`
22
+
23
+ /**
24
+ * Flatten a nested object into dot-path → string entries (arrays indexed).
25
+ * Non-string leaves (numbers, booleans, null) are left in place and not translated.
26
+ */
27
+ export function flatten(obj, prefix = '', out = {}) {
28
+ for (const [key, value] of Object.entries(obj)) {
29
+ const path = prefix ? `${prefix}.${key}` : key
30
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
31
+ flatten(value, path, out)
32
+ } else if (Array.isArray(value)) {
33
+ value.forEach((v, i) => {
34
+ if (v && typeof v === 'object') flatten(v, `${path}.${i}`, out)
35
+ else out[`${path}.${i}`] = v
36
+ })
37
+ } else {
38
+ out[path] = value
39
+ }
40
+ }
41
+ return out
42
+ }
43
+
44
+ /** Rebuild a nested object from dot-path entries. */
45
+ export function unflatten(flat) {
46
+ const root = {}
47
+ for (const [path, value] of Object.entries(flat)) {
48
+ const parts = path.split('.')
49
+ let node = root
50
+ for (let i = 0; i < parts.length - 1; i++) {
51
+ const key = parts[i]
52
+ const nextIsIndex = /^\d+$/.test(parts[i + 1])
53
+ if (node[key] == null) node[key] = nextIsIndex ? [] : {}
54
+ node = node[key]
55
+ }
56
+ node[parts[parts.length - 1]] = value
57
+ }
58
+ return root
59
+ }
60
+
61
+ function parseJsonArray(text, expectedLength) {
62
+ let parsed
63
+ try {
64
+ parsed = JSON.parse(text)
65
+ } catch {
66
+ const match = text.match(/\[[\s\S]*\]/)
67
+ if (!match) throw new Error('LLM did not return a JSON array')
68
+ parsed = JSON.parse(match[0])
69
+ }
70
+ if (!Array.isArray(parsed) || parsed.length !== expectedLength) {
71
+ throw new Error(`Expected ${expectedLength} translations, got ${parsed?.length ?? 0}`)
72
+ }
73
+ return parsed
74
+ }
75
+
76
+ function chunk(arr, size) {
77
+ const out = []
78
+ for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size))
79
+ return out
80
+ }
81
+
82
+ /**
83
+ * Translate a batch of strings via the adapter.
84
+ * @param {string[]} texts
85
+ * @param {object} opts { adapter, from, to, batchSize }
86
+ * @returns {Promise<string[]>}
87
+ */
88
+ export async function translateStrings(texts, { adapter, from, to, batchSize = 40 }) {
89
+ const results = new Array(texts.length)
90
+ const batches = chunk(
91
+ texts.map((t, i) => ({ t, i })),
92
+ batchSize
93
+ )
94
+ for (const batch of batches) {
95
+ const prompt = BATCH_PROMPT
96
+ .replace('{SOURCE_LANG}', getLanguageName(from))
97
+ .replace('{TARGET_LANG}', getLanguageName(to))
98
+ .replace('{TEXTS}', JSON.stringify(batch.map((b) => b.t), null, 2))
99
+ const raw = await adapter.complete(prompt, { maxTokens: 8192 })
100
+ const translated = parseJsonArray(raw, batch.length)
101
+ batch.forEach((b, idx) => {
102
+ results[b.i] = translated[idx]
103
+ })
104
+ }
105
+ return results
106
+ }
107
+
108
+ /**
109
+ * Translate a locale JSON object from one language to another, preserving
110
+ * structure and placeholders. BYO-LLM: pass provider + key (or a custom adapter).
111
+ *
112
+ * @param {object} params
113
+ * @param {Record<string, any>} params.content source locale object
114
+ * @param {string} params.from source language code
115
+ * @param {string} params.to target language code
116
+ * @param {'anthropic'|'openai'|object} params.provider provider name or a custom adapter
117
+ * @param {string} [params.apiKey] LLM API key (else provider env var)
118
+ * @param {string} [params.model] override the provider's default model
119
+ * @param {Record<string,any>} [params.existing] prior translation → only re-translate changed/new keys (incremental)
120
+ * @returns {Promise<{ result: object, stats: { translated: number, reused: number, placeholderWarnings: Array }}>}
121
+ */
122
+ export async function translateJSON({ content, from, to, provider, apiKey, model, existing }) {
123
+ const adapter = resolveAdapter(provider, { apiKey, model })
124
+ const sourceFlat = flatten(content)
125
+ const existingFlat = existing ? flatten(existing) : {}
126
+
127
+ // Incremental: only translate keys that are new or whose source presumably changed.
128
+ // (Without a stored source snapshot we treat "already has a translation" as reusable;
129
+ // callers that track source hashes can pass a filtered `existing`.)
130
+ const entries = Object.entries(sourceFlat)
131
+ const toTranslate = []
132
+ const outFlat = {}
133
+ for (const [path, value] of entries) {
134
+ if (typeof value !== 'string') {
135
+ outFlat[path] = value // non-string leaves pass through untouched
136
+ } else if (existingFlat[path] != null && existingFlat[path] !== '') {
137
+ outFlat[path] = existingFlat[path] // reuse prior translation
138
+ } else {
139
+ toTranslate.push({ path, value })
140
+ }
141
+ }
142
+
143
+ const placeholderWarnings = []
144
+ if (toTranslate.length > 0) {
145
+ const translated = await translateStrings(
146
+ toTranslate.map((e) => e.value),
147
+ { adapter, from, to }
148
+ )
149
+ toTranslate.forEach((e, i) => {
150
+ const out = translated[i]
151
+ outFlat[e.path] = out
152
+ const check = validatePlaceholders(e.value, out)
153
+ if (!check.ok) {
154
+ placeholderWarnings.push({ path: e.path, source: e.value, translation: out, ...check })
155
+ }
156
+ })
157
+ }
158
+
159
+ return {
160
+ result: unflatten(outFlat),
161
+ stats: {
162
+ translated: toTranslate.length,
163
+ reused: entries.length - toTranslate.length - entries.filter(([, v]) => typeof v !== 'string').length,
164
+ placeholderWarnings,
165
+ },
166
+ }
167
+ }