@molecule/api-ai-translation-amazon 0.0.0-stage → 0.0.1-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,306 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-11-13T05:08:54.389Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/api-ai-translation-amazon
10
+
11
+ Amazon Translate provider for molecule.dev.
12
+
13
+ Implements the `@molecule/api-ai-translation` contract (`translate`,
14
+ `getSupportedLanguages`, `getUsage`) over Amazon Translate's TranslateText
15
+ API — one text per call, source language auto-detected by default, AWS
16
+ terminology resources usable as glossaries.
17
+
18
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
19
+ > It is written to be read by coding agents as much as by people, and is generated from this
20
+ > package's source — edit `src/index.ts` JSDoc, not this file.
21
+
22
+ ## Quick Start
23
+
24
+ ```typescript
25
+ import { setProvider, requireProvider } from '@molecule/api-ai-translation'
26
+ import { provider } from '@molecule/api-ai-translation-amazon'
27
+
28
+ setProvider(provider) // at startup — lazy; reads AWS_* config on first use
29
+
30
+ const { translations } = await requireProvider().translate({
31
+ text: ['{{count}} items in your cart'],
32
+ targetLang: 'de',
33
+ protect: ['{{count}}'],
34
+ })
35
+ // translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
36
+ ```
37
+
38
+ ## Type
39
+
40
+ `provider`
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ npm install @molecule/api-ai-translation-amazon @aws-sdk/client-translate @aws-sdk/credential-provider-node @molecule/api-ai-translation @molecule/api-analytics @molecule/api-bond @molecule/api-proxy-agent @molecule/api-secrets
46
+ ```
47
+
48
+ ## API
49
+
50
+ ### Interfaces
51
+
52
+ #### `MaskedText`
53
+
54
+ A text prepared for Amazon Translate, plus what is needed to restore it.
55
+
56
+ ```typescript
57
+ interface MaskedText {
58
+ /** The plain text sent to Amazon Translate. */
59
+ masked: string
60
+ /** The protected substrings, in order of occurrence. */
61
+ originals: string[]
62
+ /** The numeric offset the tokens start at (collision avoidance — see {@link maskText}). */
63
+ offset: number
64
+ }
65
+ ```
66
+
67
+ #### `AwsCredentials`
68
+
69
+ An explicit AWS credential pair. Omit to resolve credentials through the
70
+ AWS default chain (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, shared
71
+ config files, or an instance role) at send time.
72
+
73
+ ```typescript
74
+ interface AwsCredentials {
75
+ /** The AWS access key ID. */
76
+ accessKeyId: string
77
+ /** The AWS secret access key. */
78
+ secretAccessKey: string
79
+ }
80
+ ```
81
+
82
+ #### `AmazonTranslateConfig`
83
+
84
+ Configuration for the Amazon Translate provider.
85
+
86
+ ```typescript
87
+ interface AmazonTranslateConfig {
88
+ /** AWS region to call Translate in. Defaults to AWS_TRANSLATE_REGION, then AWS_REGION, then 'us-east-1'. */
89
+ region?: string
90
+ /** Endpoint URL override. Defaults to the AWS regional endpoint. */
91
+ endpoint?: string
92
+ /** Explicit credentials. Omit to use the AWS default chain. */
93
+ credentials?: AwsCredentials
94
+ }
95
+ ```
96
+
97
+ ### Functions
98
+
99
+ #### `maskText(text, protect)`
100
+
101
+ Masks one text for a plain-text request.
102
+
103
+ Token numbering starts ABOVE the highest `{{N}}` number already present in
104
+ the caller's text, so a text that itself carries placeholder-shaped content
105
+ (`{{count}}` is protected, but a stray literal `{{0}}` is not) can never
106
+ collide with the mask: restore only rewrites tokens in the masked range.
107
+
108
+ ```typescript
109
+ function maskText(text: string, protect: string[]): MaskedText
110
+ ```
111
+
112
+ - `text` — The caller's text.
113
+ - `protect` — Literal substrings to protect.
114
+
115
+ **Returns:** The masked text, its protected substrings, and the token offset.
116
+
117
+ #### `unmaskText(translated, originals, offset)`
118
+
119
+ Restores an Amazon Translate result: protected substrings back by index,
120
+ keeping any whitespace the translator moved around the token.
121
+
122
+ Tokens outside this mask's range (a collision-avoided offset guarantees
123
+ there are none) pass through untouched.
124
+
125
+ ```typescript
126
+ function unmaskText(translated: string, originals: string[], offset: number): string
127
+ ```
128
+
129
+ - `translated` — Amazon Translate's output.
130
+ - `originals` — The substrings `maskText` protected.
131
+ - `offset` — The token offset `maskText` used.
132
+
133
+ **Returns:** The restored text.
134
+
135
+ #### `resolveRegion(config)`
136
+
137
+ Resolves the region at CLIENT-CONSTRUCTION time, not import time, so a
138
+ region resolved into `process.env` after this module loads (late secrets
139
+ resolution via a secrets bond) is honored — the SES bond's lesson.
140
+
141
+ ```typescript
142
+ function resolveRegion(config?: AmazonTranslateConfig): string
143
+ ```
144
+
145
+ - `config` — Explicit config, when the provider was created with one.
146
+
147
+ **Returns:** The region to call Amazon Translate in.
148
+
149
+ #### `buildTranslateClient(config)`
150
+
151
+ Builds a Translate client from a config (or the environment when omitted).
152
+
153
+ The AWS SDK v3 builds its own `https.Agent` and reads no proxy variable, so
154
+ on a host whose only egress path is a proxy every call fails with a bare
155
+ connection error unless the agent is passed in via `requestHandler` — the
156
+ SES bond's fix, mirrored here.
157
+
158
+ ```typescript
159
+ function buildTranslateClient(config?: AmazonTranslateConfig): TranslateClient
160
+ ```
161
+
162
+ - `config` — Explicit config. Omitted keys fall back to the environment.
163
+
164
+ **Returns:** The configured client.
165
+
166
+ #### `createProvider(config)`
167
+
168
+ Creates an Amazon Translate provider instance.
169
+
170
+ ```typescript
171
+ function createProvider(config?: AmazonTranslateConfig): AITranslationProvider
172
+ ```
173
+
174
+ - `config` — AWS-specific configuration (region, endpoint, credentials).
175
+
176
+ **Returns:** An `AITranslationProvider` backed by Amazon Translate.
177
+
178
+ ### Constants
179
+
180
+ #### `provider`
181
+
182
+ The provider implementation.
183
+
184
+ ```typescript
185
+ const provider: AITranslationProvider
186
+ ```
187
+
188
+ #### `aiTranslationAmazonSecretDefinitions`
189
+
190
+ Secret definitions required by the Amazon Translate bond.
191
+
192
+ ```typescript
193
+ const aiTranslationAmazonSecretDefinitions: SecretDefinition[]
194
+ ```
195
+
196
+ ## Core Interface
197
+
198
+ Implements `@molecule/api-ai-translation` interface.
199
+
200
+ ## Bond Wiring
201
+
202
+ Setup function to register this provider with the core interface:
203
+
204
+ ```typescript
205
+ import { setProvider } from '@molecule/api-ai-translation'
206
+ import { provider } from '@molecule/api-ai-translation-amazon'
207
+
208
+ export function setupAiTranslationAmazon(): void {
209
+ setProvider(provider)
210
+ }
211
+ ```
212
+
213
+ ## Injection Notes
214
+
215
+ ### Requirements
216
+
217
+ Peer dependencies:
218
+
219
+ - `@molecule/api-ai-translation` >=1.0.1
220
+ - `@molecule/api-bond` ^1.0.1
221
+ - `@molecule/api-secrets` ^1.0.1
222
+
223
+ ### Environment Variables
224
+
225
+ - `AWS_ACCESS_KEY_ID` _(required)_ — AWS access key ID
226
+ - Setup: Create an IAM user with the needed policy (SES/S3/SQS) and create an access key under Security credentials.
227
+ - Get it here: [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)
228
+ - Example: `AKIA...`
229
+ - `AWS_SECRET_ACCESS_KEY` _(required)_ — AWS secret access key
230
+ - Setup: Shown once when creating the IAM access key — store it immediately.
231
+ - `AWS_TRANSLATE_REGION` _(optional)_ — AWS Translate region — default: `us-east-1`
232
+ - Setup: The AWS region to call Amazon Translate in. Source language 'auto' additionally needs a region where Amazon Comprehend runs.
233
+ - Example: `us-east-1`
234
+
235
+ ### Runtime Dependencies
236
+
237
+ - `@aws-sdk/client-translate`
238
+ - `@aws-sdk/credential-provider-node`
239
+ - `@molecule/api-ai-translation`
240
+ - `@molecule/api-analytics`
241
+ - `@molecule/api-bond`
242
+ - `@molecule/api-proxy-agent`
243
+ - `@molecule/api-secrets`
244
+
245
+ - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
246
+ `setProvider(createProvider(config?))` to pass explicit config.
247
+ - Config: `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (required — an IAM key
248
+ with `translate:TranslateText`); `AWS_TRANSLATE_REGION` (optional — falls
249
+ back to `AWS_REGION`, then `us-east-1`); `AWS_TRANSLATE_ENDPOINT` (optional
250
+ endpoint override).
251
+ - **Language codes are Amazon's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`)
252
+ — not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from
253
+ `getSupportedLanguages()` (the live ListLanguages endpoint).
254
+ - **Omitting `sourceLang` means `auto`** — Amazon detects the source language
255
+ (through Amazon Comprehend), and the detection runs only in regions where
256
+ Comprehend exists (us-east-1 qualifies); elsewhere pass `sourceLang`
257
+ explicitly.
258
+ - **`protect` is the only safe way to keep placeholders.** TranslateText has
259
+ no tag-handling mode, so this bond sends each protected substring as a
260
+ numbered `{{N}}` token — numbers carry no letters a translator could
261
+ case-change — and restores the original afterwards. The numbering starts
262
+ above any `{{N}}` already in your text, so placeholder-shaped content that
263
+ is NOT protected can never collide with the mask.
264
+ - `formality` maps onto Amazon's `Settings.Formality` (formal/informal are
265
+ supported for a subset of target languages — others reject the setting).
266
+ `glossaryId` maps onto a custom terminology resource name (create it in
267
+ the SAME account/region first — `TerminologyNames`). `preserveFormatting`,
268
+ `tagHandling`, `context` and `modelType` are ignored.
269
+ - **One text per call** — Amazon's TranslateText takes a single string, so an
270
+ array input makes one call per text (in order). Per-text cap: 10,000 bytes
271
+ of UTF-8, enforced locally before any upstream call.
272
+ - **`getUsage()` counts this process only** (`characterLimit` is `Infinity`):
273
+ Amazon has no usage endpoint — spend lives in the AWS console, billed per
274
+ character.
275
+ - Throttling and transient failures are retried by the AWS SDK's own retry
276
+ strategy; everything else throws (tracked through `trackBondFailure`).
277
+ - On hosts whose egress path is an HTTP proxy the SDK's agent is set from
278
+ `@molecule/api-proxy-agent` automatically; the AWS SDK otherwise ignores
279
+ proxy variables entirely.
280
+
281
+ ## E2E Tests
282
+
283
+ Integration checklist — drive the real UI (live preview, no mocks), adapt
284
+ each item to this app's actual screens/flows, and check every box off one
285
+ by one. A box you can't check is an integration bug to fix — not a skip.
286
+ The sandbox has a live AI provider, so translations run for real; output is
287
+ non-deterministic, so assert on the resulting LANGUAGE/meaning, never an
288
+ exact string:
289
+
290
+ - [ ] Translating real text to a target language through the UI returns text
291
+ ACTUALLY in that language — English→Spanish produces recognizably Spanish,
292
+ not the original echoed back or left in English.
293
+ - [ ] Switching the target language (from the picker populated by
294
+ getSupportedLanguages('target')) changes the output language for the same
295
+ input — the same source re-translates into the newly chosen language.
296
+ - [ ] With sourceLang omitted the provider auto-detects: a known-language
297
+ input comes back with the correct detectedSourceLang, and if the UI shows
298
+ a detected-language label it names the right one.
299
+ - [ ] Text already in the target language is left sensible — unchanged or a
300
+ valid paraphrase, never mangled, doubled, or emptied.
301
+ - [ ] Empty or untranslatable input (whitespace, emoji, a bare code snippet)
302
+ is handled gracefully — a clear UI state, nothing crashes.
303
+ - [ ] A provider failure (bad key, quota exhausted, network drop) surfaces a
304
+ visible error in the UI, not an unhandled 500 or a silently blank result.
305
+ - [ ] The translate call runs server-side only — the provider key never
306
+ reaches the browser (check the network panel: no key in any request).
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai-translation-amazon` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai-translation-amazon is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Amazon Translate provider for molecule.dev.
3
+ *
4
+ * Implements the `@molecule/api-ai-translation` contract (`translate`,
5
+ * `getSupportedLanguages`, `getUsage`) over Amazon Translate's TranslateText
6
+ * API — one text per call, source language auto-detected by default, AWS
7
+ * terminology resources usable as glossaries.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { setProvider, requireProvider } from '@molecule/api-ai-translation'
12
+ * import { provider } from '@molecule/api-ai-translation-amazon'
13
+ *
14
+ * setProvider(provider) // at startup — lazy; reads AWS_* config on first use
15
+ *
16
+ * const { translations } = await requireProvider().translate({
17
+ * text: ['{{count}} items in your cart'],
18
+ * targetLang: 'de',
19
+ * protect: ['{{count}}'],
20
+ * })
21
+ * // translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
22
+ * ```
23
+ *
24
+ * @remarks
25
+ * - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
26
+ * `setProvider(createProvider(config?))` to pass explicit config.
27
+ * - Config: `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (required — an IAM key
28
+ * with `translate:TranslateText`); `AWS_TRANSLATE_REGION` (optional — falls
29
+ * back to `AWS_REGION`, then `us-east-1`); `AWS_TRANSLATE_ENDPOINT` (optional
30
+ * endpoint override).
31
+ * - **Language codes are Amazon's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`)
32
+ * — not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from
33
+ * `getSupportedLanguages()` (the live ListLanguages endpoint).
34
+ * - **Omitting `sourceLang` means `auto`** — Amazon detects the source language
35
+ * (through Amazon Comprehend), and the detection runs only in regions where
36
+ * Comprehend exists (us-east-1 qualifies); elsewhere pass `sourceLang`
37
+ * explicitly.
38
+ * - **`protect` is the only safe way to keep placeholders.** TranslateText has
39
+ * no tag-handling mode, so this bond sends each protected substring as a
40
+ * numbered `{{N}}` token — numbers carry no letters a translator could
41
+ * case-change — and restores the original afterwards. The numbering starts
42
+ * above any `{{N}}` already in your text, so placeholder-shaped content that
43
+ * is NOT protected can never collide with the mask.
44
+ * - `formality` maps onto Amazon's `Settings.Formality` (formal/informal are
45
+ * supported for a subset of target languages — others reject the setting).
46
+ * `glossaryId` maps onto a custom terminology resource name (create it in
47
+ * the SAME account/region first — `TerminologyNames`). `preserveFormatting`,
48
+ * `tagHandling`, `context` and `modelType` are ignored.
49
+ * - **One text per call** — Amazon's TranslateText takes a single string, so an
50
+ * array input makes one call per text (in order). Per-text cap: 10,000 bytes
51
+ * of UTF-8, enforced locally before any upstream call.
52
+ * - **`getUsage()` counts this process only** (`characterLimit` is `Infinity`):
53
+ * Amazon has no usage endpoint — spend lives in the AWS console, billed per
54
+ * character.
55
+ * - Throttling and transient failures are retried by the AWS SDK's own retry
56
+ * strategy; everything else throws (tracked through `trackBondFailure`).
57
+ * - On hosts whose egress path is an HTTP proxy the SDK's agent is set from
58
+ * `@molecule/api-proxy-agent` automatically; the AWS SDK otherwise ignores
59
+ * proxy variables entirely.
60
+ *
61
+ * @module
62
+ */
63
+ export * from './browser-guard.js';
64
+ export * from './protect.js';
65
+ export * from './provider.js';
66
+ export * from './secrets.js';
67
+ export * from './types.js';
68
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,cAAc,CAAA;AAC5B,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Amazon Translate provider for molecule.dev.
3
+ *
4
+ * Implements the `@molecule/api-ai-translation` contract (`translate`,
5
+ * `getSupportedLanguages`, `getUsage`) over Amazon Translate's TranslateText
6
+ * API — one text per call, source language auto-detected by default, AWS
7
+ * terminology resources usable as glossaries.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { setProvider, requireProvider } from '@molecule/api-ai-translation'
12
+ * import { provider } from '@molecule/api-ai-translation-amazon'
13
+ *
14
+ * setProvider(provider) // at startup — lazy; reads AWS_* config on first use
15
+ *
16
+ * const { translations } = await requireProvider().translate({
17
+ * text: ['{{count}} items in your cart'],
18
+ * targetLang: 'de',
19
+ * protect: ['{{count}}'],
20
+ * })
21
+ * // translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
22
+ * ```
23
+ *
24
+ * @remarks
25
+ * - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
26
+ * `setProvider(createProvider(config?))` to pass explicit config.
27
+ * - Config: `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (required — an IAM key
28
+ * with `translate:TranslateText`); `AWS_TRANSLATE_REGION` (optional — falls
29
+ * back to `AWS_REGION`, then `us-east-1`); `AWS_TRANSLATE_ENDPOINT` (optional
30
+ * endpoint override).
31
+ * - **Language codes are Amazon's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`)
32
+ * — not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from
33
+ * `getSupportedLanguages()` (the live ListLanguages endpoint).
34
+ * - **Omitting `sourceLang` means `auto`** — Amazon detects the source language
35
+ * (through Amazon Comprehend), and the detection runs only in regions where
36
+ * Comprehend exists (us-east-1 qualifies); elsewhere pass `sourceLang`
37
+ * explicitly.
38
+ * - **`protect` is the only safe way to keep placeholders.** TranslateText has
39
+ * no tag-handling mode, so this bond sends each protected substring as a
40
+ * numbered `{{N}}` token — numbers carry no letters a translator could
41
+ * case-change — and restores the original afterwards. The numbering starts
42
+ * above any `{{N}}` already in your text, so placeholder-shaped content that
43
+ * is NOT protected can never collide with the mask.
44
+ * - `formality` maps onto Amazon's `Settings.Formality` (formal/informal are
45
+ * supported for a subset of target languages — others reject the setting).
46
+ * `glossaryId` maps onto a custom terminology resource name (create it in
47
+ * the SAME account/region first — `TerminologyNames`). `preserveFormatting`,
48
+ * `tagHandling`, `context` and `modelType` are ignored.
49
+ * - **One text per call** — Amazon's TranslateText takes a single string, so an
50
+ * array input makes one call per text (in order). Per-text cap: 10,000 bytes
51
+ * of UTF-8, enforced locally before any upstream call.
52
+ * - **`getUsage()` counts this process only** (`characterLimit` is `Infinity`):
53
+ * Amazon has no usage endpoint — spend lives in the AWS console, billed per
54
+ * character.
55
+ * - Throttling and transient failures are retried by the AWS SDK's own retry
56
+ * strategy; everything else throws (tracked through `trackBondFailure`).
57
+ * - On hosts whose egress path is an HTTP proxy the SDK's agent is set from
58
+ * `@molecule/api-proxy-agent` automatically; the AWS SDK otherwise ignores
59
+ * proxy variables entirely.
60
+ *
61
+ * @module
62
+ */
63
+ export * from './browser-guard.js';
64
+ export * from './protect.js';
65
+ export * from './provider.js';
66
+ export * from './secrets.js';
67
+ export * from './types.js';
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Keeps `TranslateParams.protect` substrings out of Amazon Translate's reach.
3
+ *
4
+ * Amazon Translate has no tag-handling mode (TranslateText takes plain text),
5
+ * so unlike the Google bond this cannot ride `translate="no"` spans. Instead
6
+ * each protected occurrence goes out as a NUMBERED placeholder token,
7
+ * `{{0}}`-style with a numeric offset, and comes back as the original text,
8
+ * restored by index. The shape was chosen against the live API: numeric-only
9
+ * tokens carry no letters a translator could case-change, and German (the
10
+ * most reordering-heavy of the common targets) passed them through verbatim
11
+ * in testing (2026-11-13).
12
+ *
13
+ * @module
14
+ */
15
+ /**
16
+ * A text prepared for Amazon Translate, plus what is needed to restore it.
17
+ */
18
+ export interface MaskedText {
19
+ /** The plain text sent to Amazon Translate. */
20
+ masked: string;
21
+ /** The protected substrings, in order of occurrence. */
22
+ originals: string[];
23
+ /** The numeric offset the tokens start at (collision avoidance — see {@link maskText}). */
24
+ offset: number;
25
+ }
26
+ /**
27
+ * Masks one text for a plain-text request.
28
+ *
29
+ * Token numbering starts ABOVE the highest `{{N}}` number already present in
30
+ * the caller's text, so a text that itself carries placeholder-shaped content
31
+ * (`{{count}}` is protected, but a stray literal `{{0}}` is not) can never
32
+ * collide with the mask: restore only rewrites tokens in the masked range.
33
+ *
34
+ * @param text - The caller's text.
35
+ * @param protect - Literal substrings to protect.
36
+ * @returns The masked text, its protected substrings, and the token offset.
37
+ */
38
+ export declare function maskText(text: string, protect: string[]): MaskedText;
39
+ /**
40
+ * Restores an Amazon Translate result: protected substrings back by index,
41
+ * keeping any whitespace the translator moved around the token.
42
+ *
43
+ * Tokens outside this mask's range (a collision-avoided offset guarantees
44
+ * there are none) pass through untouched.
45
+ *
46
+ * @param translated - Amazon Translate's output.
47
+ * @param originals - The substrings `maskText` protected.
48
+ * @param offset - The token offset `maskText` used.
49
+ * @returns The restored text.
50
+ */
51
+ export declare function unmaskText(translated: string, originals: string[], offset: number): string;
52
+ //# sourceMappingURL=protect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protect.d.ts","sourceRoot":"","sources":["../src/protect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAQH;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,+CAA+C;IAC/C,MAAM,EAAE,MAAM,CAAA;IACd,wDAAwD;IACxD,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB,2FAA2F;IAC3F,MAAM,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,UAAU,CAepE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAM1F"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Keeps `TranslateParams.protect` substrings out of Amazon Translate's reach.
3
+ *
4
+ * Amazon Translate has no tag-handling mode (TranslateText takes plain text),
5
+ * so unlike the Google bond this cannot ride `translate="no"` spans. Instead
6
+ * each protected occurrence goes out as a NUMBERED placeholder token,
7
+ * `{{0}}`-style with a numeric offset, and comes back as the original text,
8
+ * restored by index. The shape was chosen against the live API: numeric-only
9
+ * tokens carry no letters a translator could case-change, and German (the
10
+ * most reordering-heavy of the common targets) passed them through verbatim
11
+ * in testing (2026-11-13).
12
+ *
13
+ * @module
14
+ */
15
+ /** What a masked token looks like: `{{N}}`, digits only. */
16
+ const TOKEN_PATTERN = /\{\{\s*(\d+)\s*\}\}/g;
17
+ /** Regex metacharacters, escaped so a token can carry them literally. */
18
+ const REGEX_SPECIALS = /[.*+?^${}()|[\]\\]/g;
19
+ /**
20
+ * Masks one text for a plain-text request.
21
+ *
22
+ * Token numbering starts ABOVE the highest `{{N}}` number already present in
23
+ * the caller's text, so a text that itself carries placeholder-shaped content
24
+ * (`{{count}}` is protected, but a stray literal `{{0}}` is not) can never
25
+ * collide with the mask: restore only rewrites tokens in the masked range.
26
+ *
27
+ * @param text - The caller's text.
28
+ * @param protect - Literal substrings to protect.
29
+ * @returns The masked text, its protected substrings, and the token offset.
30
+ */
31
+ export function maskText(text, protect) {
32
+ const tokens = [...new Set(protect.filter((token) => token.length > 0))]
33
+ .sort((a, b) => b.length - a.length)
34
+ .map((token) => token.replace(REGEX_SPECIALS, '\\$&'));
35
+ const existing = [...text.matchAll(TOKEN_PATTERN)].map((match) => Number(match[1]));
36
+ const offset = existing.length > 0 ? Math.max(...existing) + 1 : 0;
37
+ const originals = [];
38
+ const masked = tokens.length > 0
39
+ ? text.replace(new RegExp(tokens.join('|'), 'g'), (match) => {
40
+ originals.push(match);
41
+ return `{{${offset + originals.length - 1}}}`;
42
+ })
43
+ : text;
44
+ return { masked, originals, offset };
45
+ }
46
+ /**
47
+ * Restores an Amazon Translate result: protected substrings back by index,
48
+ * keeping any whitespace the translator moved around the token.
49
+ *
50
+ * Tokens outside this mask's range (a collision-avoided offset guarantees
51
+ * there are none) pass through untouched.
52
+ *
53
+ * @param translated - Amazon Translate's output.
54
+ * @param originals - The substrings `maskText` protected.
55
+ * @param offset - The token offset `maskText` used.
56
+ * @returns The restored text.
57
+ */
58
+ export function unmaskText(translated, originals, offset) {
59
+ return translated.replace(TOKEN_PATTERN, (match, number) => {
60
+ const index = Number(number) - offset;
61
+ const original = index >= 0 && index < originals.length ? originals[index] : undefined;
62
+ return original === undefined ? match : original;
63
+ });
64
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Amazon Translate implementation of AITranslationProvider.
3
+ *
4
+ * Uses the Amazon Translate `TranslateText` API (one text per call — the API
5
+ * takes a single string) through the AWS SDK v3, which retries throttling and
6
+ * transient errors with its own backoff.
7
+ *
8
+ * @module
9
+ */
10
+ import './secrets.js';
11
+ import { TranslateClient } from '@aws-sdk/client-translate';
12
+ import type { AITranslationProvider } from '@molecule/api-ai-translation';
13
+ import type { AmazonTranslateConfig } from './types.js';
14
+ /**
15
+ * Resolves the region at CLIENT-CONSTRUCTION time, not import time, so a
16
+ * region resolved into `process.env` after this module loads (late secrets
17
+ * resolution via a secrets bond) is honored — the SES bond's lesson.
18
+ *
19
+ * @param config - Explicit config, when the provider was created with one.
20
+ * @returns The region to call Amazon Translate in.
21
+ */
22
+ export declare function resolveRegion(config?: AmazonTranslateConfig): string;
23
+ /**
24
+ * Builds a Translate client from a config (or the environment when omitted).
25
+ *
26
+ * The AWS SDK v3 builds its own `https.Agent` and reads no proxy variable, so
27
+ * on a host whose only egress path is a proxy every call fails with a bare
28
+ * connection error unless the agent is passed in via `requestHandler` — the
29
+ * SES bond's fix, mirrored here.
30
+ *
31
+ * @param config - Explicit config. Omitted keys fall back to the environment.
32
+ * @returns The configured client.
33
+ */
34
+ export declare function buildTranslateClient(config?: AmazonTranslateConfig): TranslateClient;
35
+ /**
36
+ * Creates an Amazon Translate provider instance.
37
+ *
38
+ * @param config - AWS-specific configuration (region, endpoint, credentials).
39
+ * @returns An `AITranslationProvider` backed by Amazon Translate.
40
+ */
41
+ export declare function createProvider(config?: AmazonTranslateConfig): AITranslationProvider;
42
+ /**
43
+ * The provider implementation.
44
+ */
45
+ export declare const provider: AITranslationProvider;
46
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,cAAc,CAAA;AACrB,OAAO,EAEL,eAAe,EAEhB,MAAM,2BAA2B,CAAA;AAGlC,OAAO,KAAK,EACV,qBAAqB,EAKtB,MAAM,8BAA8B,CAAA;AAMrC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAYvD;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,MAAM,CAAC,EAAE,qBAAqB,GAAG,MAAM,CAIpE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,CAAC,EAAE,qBAAqB,GAAG,eAAe,CAWpF;AAwID;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,qBAAqB,GAAG,qBAAqB,CAEpF;AAID;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,qBAUrB,CAAA"}
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Amazon Translate implementation of AITranslationProvider.
3
+ *
4
+ * Uses the Amazon Translate `TranslateText` API (one text per call — the API
5
+ * takes a single string) through the AWS SDK v3, which retries throttling and
6
+ * transient errors with its own backoff.
7
+ *
8
+ * @module
9
+ */
10
+ // Side-effect import: registers this bond's secret definitions so the
11
+ // runtime registry is populated even when provider.js is imported directly
12
+ // (not through the package barrel).
13
+ import './secrets.js';
14
+ import { ListLanguagesCommand, TranslateClient, TranslateTextCommand, } from '@aws-sdk/client-translate';
15
+ import { defaultProvider } from '@aws-sdk/credential-provider-node';
16
+ import { trackBondFailure } from '@molecule/api-analytics';
17
+ import { getLogger } from '@molecule/api-bond';
18
+ import { getProxyAgents } from '@molecule/api-proxy-agent';
19
+ import { maskText, unmaskText } from './protect.js';
20
+ const logger = getLogger();
21
+ /**
22
+ * Maximum `TranslateParams.text` length per call (AWS: "The text string can be
23
+ * a maximum of 10,000 bytes long. Depending on your character set, this may be
24
+ * fewer than 10,000 characters") — enforced locally so an oversized text fails
25
+ * before any upstream call.
26
+ */
27
+ const MAX_BYTES_PER_TEXT = 10_000;
28
+ /**
29
+ * Resolves the region at CLIENT-CONSTRUCTION time, not import time, so a
30
+ * region resolved into `process.env` after this module loads (late secrets
31
+ * resolution via a secrets bond) is honored — the SES bond's lesson.
32
+ *
33
+ * @param config - Explicit config, when the provider was created with one.
34
+ * @returns The region to call Amazon Translate in.
35
+ */
36
+ export function resolveRegion(config) {
37
+ return (config?.region ?? (process.env.AWS_TRANSLATE_REGION || process.env.AWS_REGION || 'us-east-1'));
38
+ }
39
+ /**
40
+ * Builds a Translate client from a config (or the environment when omitted).
41
+ *
42
+ * The AWS SDK v3 builds its own `https.Agent` and reads no proxy variable, so
43
+ * on a host whose only egress path is a proxy every call fails with a bare
44
+ * connection error unless the agent is passed in via `requestHandler` — the
45
+ * SES bond's fix, mirrored here.
46
+ *
47
+ * @param config - Explicit config. Omitted keys fall back to the environment.
48
+ * @returns The configured client.
49
+ */
50
+ export function buildTranslateClient(config) {
51
+ const region = resolveRegion(config);
52
+ const endpoint = config?.endpoint ?? process.env.AWS_TRANSLATE_ENDPOINT;
53
+ const credentials = config?.credentials;
54
+ const proxy = getProxyAgents(endpoint || `https://translate.${region}.amazonaws.com`);
55
+ return new TranslateClient({
56
+ region,
57
+ ...(credentials ? { credentials } : { credentialDefaultProvider: defaultProvider }),
58
+ ...(endpoint ? { endpoint } : {}),
59
+ ...(proxy ? { requestHandler: proxy } : {}),
60
+ });
61
+ }
62
+ /**
63
+ * Maps the core's formality preference onto Amazon Translate's `Settings.Formality`.
64
+ *
65
+ * @param formality - The caller's formality preference.
66
+ * @returns `FORMAL`, `INFORMAL`, or undefined when Amazon should pick (and for
67
+ * languages where formality does not apply, Amazon rejects the setting).
68
+ */
69
+ function formalitySetting(formality) {
70
+ switch (formality) {
71
+ case 'more':
72
+ case 'prefer_more':
73
+ return 'FORMAL';
74
+ case 'less':
75
+ case 'prefer_less':
76
+ return 'INFORMAL';
77
+ default:
78
+ return undefined;
79
+ }
80
+ }
81
+ /**
82
+ * Amazon Translate provider implementing `AITranslationProvider`.
83
+ */
84
+ class AmazonTranslationProvider {
85
+ name = 'amazon';
86
+ /** Built on first use — NOT at construction — and memoized. */
87
+ client = null;
88
+ config;
89
+ /** Characters sent by this process — Amazon has no usage endpoint. */
90
+ charactersSent = 0;
91
+ constructor(config) {
92
+ this.config = config;
93
+ }
94
+ /**
95
+ * Returns the memoized client, building it from config/environment on first use.
96
+ *
97
+ * @returns The configured Translate client.
98
+ */
99
+ getClient() {
100
+ if (!this.client)
101
+ this.client = buildTranslateClient(this.config);
102
+ return this.client;
103
+ }
104
+ /**
105
+ * Translate one or more texts, one TranslateText call per text.
106
+ *
107
+ * @param params - Translation parameters. `preserveFormatting`, `tagHandling`,
108
+ * `context` and `modelType` have no TranslateText equivalent and are ignored.
109
+ * @returns One translation per input text, in order.
110
+ */
111
+ async translate(params) {
112
+ const texts = Array.isArray(params.text) ? params.text : [params.text];
113
+ const translations = [];
114
+ for (const text of texts) {
115
+ translations.push(await this.translateOne(text, params));
116
+ }
117
+ return { translations };
118
+ }
119
+ /**
120
+ * List the languages Amazon Translate translates, named in English.
121
+ *
122
+ * @param _type - Ignored: Amazon's source and target lists are the same.
123
+ * @returns Supported languages (Amazon's codes, e.g. 'de', 'zh-TW').
124
+ */
125
+ async getSupportedLanguages(_type) {
126
+ const response = await this.getClient().send(new ListLanguagesCommand({ DisplayLanguageCode: 'en' }));
127
+ return (response.Languages ?? []).map((language) => ({
128
+ language: language.LanguageCode ?? '',
129
+ name: language.LanguageName ?? language.LanguageCode ?? '',
130
+ }));
131
+ }
132
+ /**
133
+ * Amazon exposes no usage endpoint; this reports what THIS process has sent.
134
+ *
135
+ * @returns Characters sent since startup, and an unbounded limit.
136
+ */
137
+ async getUsage() {
138
+ return { characterCount: this.charactersSent, characterLimit: Number.POSITIVE_INFINITY };
139
+ }
140
+ /**
141
+ * One TranslateText call.
142
+ *
143
+ * @param text - One caller text (plain text — see the bond's remarks).
144
+ * @param params - Translation parameters.
145
+ * @returns The translation with its detected source language.
146
+ */
147
+ async translateOne(text, params) {
148
+ if (text.length === 0)
149
+ throw new Error('Amazon Translate needs a non-empty text per call.');
150
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES_PER_TEXT) {
151
+ throw new Error(`Amazon Translate accepts up to 10,000 bytes of text per call, got ${Buffer.byteLength(text, 'utf8')} bytes. ` +
152
+ 'Split the text and call again (TranslateText takes ONE text per call).');
153
+ }
154
+ const masked = maskText(text, params.protect ?? []);
155
+ const formality = formalitySetting(params.formality);
156
+ try {
157
+ const response = await this.getClient().send(new TranslateTextCommand({
158
+ Text: masked.masked,
159
+ SourceLanguageCode: params.sourceLang ?? 'auto',
160
+ TargetLanguageCode: params.targetLang,
161
+ ...(formality ? { Settings: { Formality: formality } } : {}),
162
+ ...(params.glossaryId ? { TerminologyNames: [params.glossaryId] } : {}),
163
+ }));
164
+ this.charactersSent += text.length;
165
+ return {
166
+ text: unmaskText(response.TranslatedText ?? '', masked.originals, masked.offset),
167
+ detectedSourceLang: response.SourceLanguageCode ?? params.sourceLang ?? '',
168
+ };
169
+ }
170
+ catch (error) {
171
+ trackBondFailure({ bond: 'ai-translation-amazon', operation: 'translate', error });
172
+ logger.error('Amazon Translate error:', error);
173
+ throw error;
174
+ }
175
+ }
176
+ }
177
+ /**
178
+ * Creates an Amazon Translate provider instance.
179
+ *
180
+ * @param config - AWS-specific configuration (region, endpoint, credentials).
181
+ * @returns An `AITranslationProvider` backed by Amazon Translate.
182
+ */
183
+ export function createProvider(config) {
184
+ return new AmazonTranslationProvider(config);
185
+ }
186
+ /** Lazily-initialized provider singleton. Defers creation until first use so that env vars / secrets are resolved. */
187
+ let _provider = null;
188
+ /**
189
+ * The provider implementation.
190
+ */
191
+ export const provider = new Proxy({}, {
192
+ get(_, prop, receiver) {
193
+ if (!_provider)
194
+ _provider = createProvider();
195
+ return Reflect.get(_provider, prop, receiver);
196
+ },
197
+ // set trap: methods run with `this` bound to the proxy — without it, instance-state writes land on the dummy target and are lost (see api-push-notifications-web-push)
198
+ set(_, prop, value) {
199
+ if (!_provider)
200
+ _provider = createProvider();
201
+ return Reflect.set(_provider, prop, value);
202
+ },
203
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Amazon Translate secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import type { SecretDefinition } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the Amazon Translate bond. */
15
+ export declare const aiTranslationAmazonSecretDefinitions: SecretDefinition[];
16
+ //# sourceMappingURL=secrets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,gEAAgE;AAChE,eAAO,MAAM,oCAAoC,EAAE,gBAAgB,EAwBlE,CAAA"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Amazon Translate secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import { registerSecrets } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the Amazon Translate bond. */
15
+ export const aiTranslationAmazonSecretDefinitions = [
16
+ {
17
+ key: 'AWS_ACCESS_KEY_ID',
18
+ description: 'AWS access key ID — Create an IAM user with the needed policy (SES/S3/SQS) and create an access key under Security credentials.',
19
+ helpUrl: 'https://console.aws.amazon.com/iam/',
20
+ required: true,
21
+ example: 'AKIA...',
22
+ },
23
+ {
24
+ key: 'AWS_SECRET_ACCESS_KEY',
25
+ description: 'AWS secret access key — Shown once when creating the IAM access key — store it immediately.',
26
+ helpUrl: 'https://console.aws.amazon.com/iam/',
27
+ required: true,
28
+ },
29
+ {
30
+ key: 'AWS_TRANSLATE_REGION',
31
+ description: "AWS Translate region — The AWS region to call Amazon Translate in. Source language 'auto' additionally needs a region where Amazon Comprehend runs.",
32
+ required: false,
33
+ example: 'us-east-1',
34
+ default: 'us-east-1',
35
+ },
36
+ ];
37
+ registerSecrets(aiTranslationAmazonSecretDefinitions);
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Amazon Translate provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * An explicit AWS credential pair. Omit to resolve credentials through the
8
+ * AWS default chain (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, shared
9
+ * config files, or an instance role) at send time.
10
+ */
11
+ export interface AwsCredentials {
12
+ /** The AWS access key ID. */
13
+ accessKeyId: string;
14
+ /** The AWS secret access key. */
15
+ secretAccessKey: string;
16
+ }
17
+ /**
18
+ * Configuration for the Amazon Translate provider.
19
+ */
20
+ export interface AmazonTranslateConfig {
21
+ /** AWS region to call Translate in. Defaults to AWS_TRANSLATE_REGION, then AWS_REGION, then 'us-east-1'. */
22
+ region?: string;
23
+ /** Endpoint URL override. Defaults to the AWS regional endpoint. */
24
+ endpoint?: string;
25
+ /** Explicit credentials. Omit to use the AWS default chain. */
26
+ credentials?: AwsCredentials;
27
+ }
28
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,6BAA6B;IAC7B,WAAW,EAAE,MAAM,CAAA;IACnB,iCAAiC;IACjC,eAAe,EAAE,MAAM,CAAA;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,4GAA4G;IAC5G,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,+DAA+D;IAC/D,WAAW,CAAC,EAAE,cAAc,CAAA;CAC7B"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Amazon Translate provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@molecule/api-ai-translation-amazon",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-stage",
4
+ "description": "Amazon Translate provider for molecule.dev — text translation via AWS Translate",
5
+ "homepage": "https://www.molecule.dev/packages/api-ai-translation-amazon",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "test": "vitest run",
12
+ "test:watch": "vitest"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md"
23
+ ],
24
+ "keywords": [
25
+ "molecule",
26
+ "ai",
27
+ "translation",
28
+ "amazon",
29
+ "aws",
30
+ "amazon-translate"
31
+ ],
32
+ "license": "Apache-2.0",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/molecule-dev/molecule.git",
36
+ "directory": "packages/api/bonds/ai-translation/amazon"
37
+ },
38
+ "dependencies": {
39
+ "@aws-sdk/client-translate": "3.1156.0",
40
+ "@aws-sdk/credential-provider-node": "3.972.88",
41
+ "@molecule/api-analytics": "1.1.2",
42
+ "@molecule/api-proxy-agent": "1.1.2"
43
+ },
44
+ "peerDependencies": {
45
+ "@molecule/api-ai-translation": ">=1.0.1",
46
+ "@molecule/api-bond": "^1.0.1",
47
+ "@molecule/api-secrets": "^1.0.1"
48
+ },
49
+ "devDependencies": {
50
+ "@molecule/api-ai-translation": "1.1.1",
51
+ "@molecule/api-bond": "1.0.4",
52
+ "@types/node": "26.6.5",
53
+ "typescript": "6.0.3",
54
+ "vitest": "4.1.12"
55
+ }
56
+ }