@molecule/api-ai-translation-google 1.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/LICENSE +115 -0
- package/README.md +175 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +45 -0
- package/dist/protect.d.ts +56 -0
- package/dist/protect.d.ts.map +1 -0
- package/dist/protect.js +84 -0
- package/dist/provider.d.ts +25 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +214 -0
- package/dist/secrets.d.ts +16 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +24 -0
- package/dist/types.d.ts +15 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
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-09-24T08:17:10.267Z
|
|
7
|
+
-->
|
|
8
|
+
|
|
9
|
+
# @molecule/api-ai-translation-google
|
|
10
|
+
|
|
11
|
+
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
12
|
+
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
13
|
+
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
14
|
+
|
|
15
|
+
Google Cloud Translation provider for molecule.dev.
|
|
16
|
+
|
|
17
|
+
Implements the `@molecule/api-ai-translation` contract (`translate`,
|
|
18
|
+
`getSupportedLanguages`, `getUsage`) over the Cloud Translation API (Basic,
|
|
19
|
+
v2), batching large inputs (128 texts or ~25k characters per request).
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { setProvider, requireProvider } from '@molecule/api-ai-translation'
|
|
25
|
+
import { provider } from '@molecule/api-ai-translation-google'
|
|
26
|
+
|
|
27
|
+
setProvider(provider) // at startup — lazy; reads GOOGLE_TRANSLATE_API_KEY on first use
|
|
28
|
+
|
|
29
|
+
const { translations } = await requireProvider().translate({
|
|
30
|
+
text: ['{{count}} items in your cart'],
|
|
31
|
+
targetLang: 'de',
|
|
32
|
+
protect: ['{{count}}'],
|
|
33
|
+
})
|
|
34
|
+
// translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Type
|
|
38
|
+
|
|
39
|
+
`provider`
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npm install @molecule/api-ai-translation-google @molecule/api-ai-translation @molecule/api-secrets
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## API
|
|
48
|
+
|
|
49
|
+
### Interfaces
|
|
50
|
+
|
|
51
|
+
#### `GoogleTranslateConfig`
|
|
52
|
+
|
|
53
|
+
Configuration for the Google Cloud Translation provider.
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
interface GoogleTranslateConfig {
|
|
57
|
+
/** Google Cloud API key with the Cloud Translation API enabled. Defaults to GOOGLE_TRANSLATE_API_KEY. */
|
|
58
|
+
apiKey?: string
|
|
59
|
+
/** Base URL of the Translation API. Defaults to GOOGLE_TRANSLATE_BASE_URL, then 'https://translation.googleapis.com'. */
|
|
60
|
+
baseUrl?: string
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Functions
|
|
65
|
+
|
|
66
|
+
#### `createProvider(config)`
|
|
67
|
+
|
|
68
|
+
Creates a Google Cloud Translation provider instance.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
function createProvider(config?: GoogleTranslateConfig): AITranslationProvider
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- `config` — Google-specific configuration (API key, base URL).
|
|
75
|
+
|
|
76
|
+
**Returns:** An `AITranslationProvider` backed by the Cloud Translation API.
|
|
77
|
+
|
|
78
|
+
### Constants
|
|
79
|
+
|
|
80
|
+
#### `aiTranslationGoogleSecretDefinitions`
|
|
81
|
+
|
|
82
|
+
Secret definitions required by the Google Cloud Translation bond.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
const aiTranslationGoogleSecretDefinitions: SecretDefinition[]
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
#### `provider`
|
|
89
|
+
|
|
90
|
+
The provider implementation.
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
const provider: AITranslationProvider
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Core Interface
|
|
97
|
+
|
|
98
|
+
Implements `@molecule/api-ai-translation` interface.
|
|
99
|
+
|
|
100
|
+
## Bond Wiring
|
|
101
|
+
|
|
102
|
+
Setup function to register this provider with the core interface:
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
import { setProvider } from '@molecule/api-ai-translation'
|
|
106
|
+
import { provider } from '@molecule/api-ai-translation-google'
|
|
107
|
+
|
|
108
|
+
export function setupAiTranslationGoogle(): void {
|
|
109
|
+
setProvider(provider)
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Injection Notes
|
|
114
|
+
|
|
115
|
+
### Requirements
|
|
116
|
+
|
|
117
|
+
Peer dependencies:
|
|
118
|
+
|
|
119
|
+
- `@molecule/api-ai-translation` >=1.0.1
|
|
120
|
+
- `@molecule/api-secrets` ^1.0.1
|
|
121
|
+
|
|
122
|
+
### Environment Variables
|
|
123
|
+
|
|
124
|
+
- `GOOGLE_TRANSLATE_API_KEY` _(required)_ — Google Cloud Translation API key
|
|
125
|
+
- Setup: Create an API key in a Google Cloud project with the Cloud Translation API enabled.
|
|
126
|
+
- Get it here: [https://console.cloud.google.com/apis/credentials](https://console.cloud.google.com/apis/credentials)
|
|
127
|
+
- Example: `AIzaSy...`
|
|
128
|
+
|
|
129
|
+
### Runtime Dependencies
|
|
130
|
+
|
|
131
|
+
- `@molecule/api-ai-translation`
|
|
132
|
+
- `@molecule/api-secrets`
|
|
133
|
+
|
|
134
|
+
- **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
|
|
135
|
+
`setProvider(createProvider(config?))` to pass explicit config.
|
|
136
|
+
- Config: `GOOGLE_TRANSLATE_API_KEY` (required — a Google Cloud API key with the
|
|
137
|
+
Cloud Translation API enabled); `GOOGLE_TRANSLATE_BASE_URL` (optional endpoint override).
|
|
138
|
+
- **Language codes are Google's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`) —
|
|
139
|
+
not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from `getSupportedLanguages()`.
|
|
140
|
+
- **`protect` is the only safe way to keep placeholders.** Google ignores custom
|
|
141
|
+
tags and splits braces even inside `translate="no"`, so this bond sends each
|
|
142
|
+
protected substring as an index and restores the original afterwards.
|
|
143
|
+
- `formality`, `glossaryId`, `modelType`, `context` and `preserveFormatting` have no
|
|
144
|
+
v2 equivalent and are ignored.
|
|
145
|
+
- **`getUsage()` counts this process only** (`characterLimit` is `Infinity`): Google
|
|
146
|
+
has no usage endpoint — spend lives in the Cloud console, billed per character.
|
|
147
|
+
- Rate limits (429, and 403 "User Rate Limit Exceeded") and 5xx are retried with
|
|
148
|
+
backoff; other failures throw an `Error` whose `status` is the HTTP status.
|
|
149
|
+
|
|
150
|
+
## E2E Tests
|
|
151
|
+
|
|
152
|
+
Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
153
|
+
each item to this app's actual screens/flows, and check every box off one
|
|
154
|
+
by one. A box you can't check is an integration bug to fix — not a skip.
|
|
155
|
+
The sandbox has a live AI provider, so translations run for real; output is
|
|
156
|
+
non-deterministic, so assert on the resulting LANGUAGE/meaning, never an
|
|
157
|
+
exact string:
|
|
158
|
+
|
|
159
|
+
- [ ] Translating real text to a target language through the UI returns text
|
|
160
|
+
ACTUALLY in that language — English→Spanish produces recognizably Spanish,
|
|
161
|
+
not the original echoed back or left in English.
|
|
162
|
+
- [ ] Switching the target language (from the picker populated by
|
|
163
|
+
getSupportedLanguages('target')) changes the output language for the same
|
|
164
|
+
input — the same source re-translates into the newly chosen language.
|
|
165
|
+
- [ ] With sourceLang omitted the provider auto-detects: a known-language
|
|
166
|
+
input comes back with the correct detectedSourceLang, and if the UI shows
|
|
167
|
+
a detected-language label it names the right one.
|
|
168
|
+
- [ ] Text already in the target language is left sensible — unchanged or a
|
|
169
|
+
valid paraphrase, never mangled, doubled, or emptied.
|
|
170
|
+
- [ ] Empty or untranslatable input (whitespace, emoji, a bare code snippet)
|
|
171
|
+
is handled gracefully — a clear UI state, nothing crashes.
|
|
172
|
+
- [ ] A provider failure (bad key, quota exhausted, network drop) surfaces a
|
|
173
|
+
visible error in the UI, not an unhandled 500 or a silently blank result.
|
|
174
|
+
- [ ] The translate call runs server-side only — the provider key never
|
|
175
|
+
reaches the browser (check the network panel: no key in any request).
|
|
@@ -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-google` 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-google 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 {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the `@molecule/api-ai-translation` contract (`translate`,
|
|
5
|
+
* `getSupportedLanguages`, `getUsage`) over the Cloud Translation API (Basic,
|
|
6
|
+
* v2), batching large inputs (128 texts or ~25k characters per request).
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { setProvider, requireProvider } from '@molecule/api-ai-translation'
|
|
11
|
+
* import { provider } from '@molecule/api-ai-translation-google'
|
|
12
|
+
*
|
|
13
|
+
* setProvider(provider) // at startup — lazy; reads GOOGLE_TRANSLATE_API_KEY on first use
|
|
14
|
+
*
|
|
15
|
+
* const { translations } = await requireProvider().translate({
|
|
16
|
+
* text: ['{{count}} items in your cart'],
|
|
17
|
+
* targetLang: 'de',
|
|
18
|
+
* protect: ['{{count}}'],
|
|
19
|
+
* })
|
|
20
|
+
* // translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
|
|
25
|
+
* `setProvider(createProvider(config?))` to pass explicit config.
|
|
26
|
+
* - Config: `GOOGLE_TRANSLATE_API_KEY` (required — a Google Cloud API key with the
|
|
27
|
+
* Cloud Translation API enabled); `GOOGLE_TRANSLATE_BASE_URL` (optional endpoint override).
|
|
28
|
+
* - **Language codes are Google's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`) —
|
|
29
|
+
* not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from `getSupportedLanguages()`.
|
|
30
|
+
* - **`protect` is the only safe way to keep placeholders.** Google ignores custom
|
|
31
|
+
* tags and splits braces even inside `translate="no"`, so this bond sends each
|
|
32
|
+
* protected substring as an index and restores the original afterwards.
|
|
33
|
+
* - `formality`, `glossaryId`, `modelType`, `context` and `preserveFormatting` have no
|
|
34
|
+
* v2 equivalent and are ignored.
|
|
35
|
+
* - **`getUsage()` counts this process only** (`characterLimit` is `Infinity`): Google
|
|
36
|
+
* has no usage endpoint — spend lives in the Cloud console, billed per character.
|
|
37
|
+
* - Rate limits (429, and 403 "User Rate Limit Exceeded") and 5xx are retried with
|
|
38
|
+
* backoff; other failures throw an `Error` whose `status` is the HTTP status.
|
|
39
|
+
*
|
|
40
|
+
* @module
|
|
41
|
+
*/
|
|
42
|
+
export * from './browser-guard.js';
|
|
43
|
+
export * from './provider.js';
|
|
44
|
+
export * from './secrets.js';
|
|
45
|
+
export * from './types.js';
|
|
46
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the `@molecule/api-ai-translation` contract (`translate`,
|
|
5
|
+
* `getSupportedLanguages`, `getUsage`) over the Cloud Translation API (Basic,
|
|
6
|
+
* v2), batching large inputs (128 texts or ~25k characters per request).
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { setProvider, requireProvider } from '@molecule/api-ai-translation'
|
|
11
|
+
* import { provider } from '@molecule/api-ai-translation-google'
|
|
12
|
+
*
|
|
13
|
+
* setProvider(provider) // at startup — lazy; reads GOOGLE_TRANSLATE_API_KEY on first use
|
|
14
|
+
*
|
|
15
|
+
* const { translations } = await requireProvider().translate({
|
|
16
|
+
* text: ['{{count}} items in your cart'],
|
|
17
|
+
* targetLang: 'de',
|
|
18
|
+
* protect: ['{{count}}'],
|
|
19
|
+
* })
|
|
20
|
+
* // translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
|
|
25
|
+
* `setProvider(createProvider(config?))` to pass explicit config.
|
|
26
|
+
* - Config: `GOOGLE_TRANSLATE_API_KEY` (required — a Google Cloud API key with the
|
|
27
|
+
* Cloud Translation API enabled); `GOOGLE_TRANSLATE_BASE_URL` (optional endpoint override).
|
|
28
|
+
* - **Language codes are Google's**, lowercase BCP-47 style (`de`, `pt`, `zh-TW`) —
|
|
29
|
+
* not DeepL's (`DE`, `PT-BR`, `ZH-HANT`). Take them from `getSupportedLanguages()`.
|
|
30
|
+
* - **`protect` is the only safe way to keep placeholders.** Google ignores custom
|
|
31
|
+
* tags and splits braces even inside `translate="no"`, so this bond sends each
|
|
32
|
+
* protected substring as an index and restores the original afterwards.
|
|
33
|
+
* - `formality`, `glossaryId`, `modelType`, `context` and `preserveFormatting` have no
|
|
34
|
+
* v2 equivalent and are ignored.
|
|
35
|
+
* - **`getUsage()` counts this process only** (`characterLimit` is `Infinity`): Google
|
|
36
|
+
* has no usage endpoint — spend lives in the Cloud console, billed per character.
|
|
37
|
+
* - Rate limits (429, and 403 "User Rate Limit Exceeded") and 5xx are retried with
|
|
38
|
+
* backoff; other failures throw an `Error` whose `status` is the HTTP status.
|
|
39
|
+
*
|
|
40
|
+
* @module
|
|
41
|
+
*/
|
|
42
|
+
export * from './browser-guard.js';
|
|
43
|
+
export * from './provider.js';
|
|
44
|
+
export * from './secrets.js';
|
|
45
|
+
export * from './types.js';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps `TranslateParams.protect` substrings out of Google's reach.
|
|
3
|
+
*
|
|
4
|
+
* Google ignores unknown tags (it translated the names inside a custom `<x>`
|
|
5
|
+
* wrapper — `{{rating}}` → `{{ocjena}}`) and splits braces even inside a
|
|
6
|
+
* `translate="no"` span (`{{count}}` came back as `{{count` or with a stray `}`).
|
|
7
|
+
* So Google never sees a protected substring at all: each occurrence goes out as
|
|
8
|
+
* its INDEX inside `<span translate="no">`, and comes back as the original text,
|
|
9
|
+
* restored by index. Requests use `format=html`, so plain text is escaped on the
|
|
10
|
+
* way in and entities are decoded on the way out.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Escapes the HTML-significant characters of plain text.
|
|
16
|
+
*
|
|
17
|
+
* @param text - Plain text.
|
|
18
|
+
* @returns The text with `&`, `<`, `>` escaped.
|
|
19
|
+
*/
|
|
20
|
+
export declare function escapeHtml(text: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Decodes named and numeric character entities back to plain text.
|
|
23
|
+
*
|
|
24
|
+
* @param text - Text returned by an HTML-mode translation.
|
|
25
|
+
* @returns Plain text.
|
|
26
|
+
*/
|
|
27
|
+
export declare function decodeEntities(text: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* A text prepared for Google, plus what is needed to restore it.
|
|
30
|
+
*/
|
|
31
|
+
export interface MaskedText {
|
|
32
|
+
/** The HTML sent to Google. */
|
|
33
|
+
masked: string;
|
|
34
|
+
/** The protected substrings, in order of occurrence. */
|
|
35
|
+
originals: string[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Masks one text for an HTML-mode request.
|
|
39
|
+
*
|
|
40
|
+
* @param text - The caller's text.
|
|
41
|
+
* @param protect - Literal substrings to protect.
|
|
42
|
+
* @param callerMarkup - True when the caller set `tagHandling` (the text is markup already).
|
|
43
|
+
* @returns The masked text and its protected substrings.
|
|
44
|
+
*/
|
|
45
|
+
export declare function maskText(text: string, protect: string[], callerMarkup: boolean): MaskedText;
|
|
46
|
+
/**
|
|
47
|
+
* Restores a Google result: entities decoded (plain text only), then protected
|
|
48
|
+
* substrings back by index, keeping any whitespace Google moved inside the span.
|
|
49
|
+
*
|
|
50
|
+
* @param translated - Google's output.
|
|
51
|
+
* @param originals - The substrings `maskText` protected.
|
|
52
|
+
* @param callerMarkup - True when the caller set `tagHandling`.
|
|
53
|
+
* @returns The restored text.
|
|
54
|
+
*/
|
|
55
|
+
export declare function unmaskText(translated: string, originals: string[], callerMarkup: boolean): string;
|
|
56
|
+
//# sourceMappingURL=protect.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protect.d.ts","sourceRoot":"","sources":["../src/protect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAYH;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CASnD;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,+BAA+B;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,wDAAwD;IACxD,SAAS,EAAE,MAAM,EAAE,CAAA;CACpB;AAED;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,OAAO,GAAG,UAAU,CAe3F;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,OAAO,GAAG,MAAM,CASjG"}
|
package/dist/protect.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps `TranslateParams.protect` substrings out of Google's reach.
|
|
3
|
+
*
|
|
4
|
+
* Google ignores unknown tags (it translated the names inside a custom `<x>`
|
|
5
|
+
* wrapper — `{{rating}}` → `{{ocjena}}`) and splits braces even inside a
|
|
6
|
+
* `translate="no"` span (`{{count}}` came back as `{{count` or with a stray `}`).
|
|
7
|
+
* So Google never sees a protected substring at all: each occurrence goes out as
|
|
8
|
+
* its INDEX inside `<span translate="no">`, and comes back as the original text,
|
|
9
|
+
* restored by index. Requests use `format=html`, so plain text is escaped on the
|
|
10
|
+
* way in and entities are decoded on the way out.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
/** Named entities Google's HTML mode returns. */
|
|
15
|
+
const NAMED_ENTITIES = {
|
|
16
|
+
amp: '&',
|
|
17
|
+
lt: '<',
|
|
18
|
+
gt: '>',
|
|
19
|
+
quot: '"',
|
|
20
|
+
apos: "'",
|
|
21
|
+
nbsp: ' ',
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Escapes the HTML-significant characters of plain text.
|
|
25
|
+
*
|
|
26
|
+
* @param text - Plain text.
|
|
27
|
+
* @returns The text with `&`, `<`, `>` escaped.
|
|
28
|
+
*/
|
|
29
|
+
export function escapeHtml(text) {
|
|
30
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Decodes named and numeric character entities back to plain text.
|
|
34
|
+
*
|
|
35
|
+
* @param text - Text returned by an HTML-mode translation.
|
|
36
|
+
* @returns Plain text.
|
|
37
|
+
*/
|
|
38
|
+
export function decodeEntities(text) {
|
|
39
|
+
return text.replace(/&(#\d+|#x[0-9a-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (match, entity) => {
|
|
40
|
+
if (entity[0] !== '#')
|
|
41
|
+
return NAMED_ENTITIES[entity.toLowerCase()] ?? match;
|
|
42
|
+
const hex = entity[1] === 'x' || entity[1] === 'X';
|
|
43
|
+
return String.fromCodePoint(parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Masks one text for an HTML-mode request.
|
|
48
|
+
*
|
|
49
|
+
* @param text - The caller's text.
|
|
50
|
+
* @param protect - Literal substrings to protect.
|
|
51
|
+
* @param callerMarkup - True when the caller set `tagHandling` (the text is markup already).
|
|
52
|
+
* @returns The masked text and its protected substrings.
|
|
53
|
+
*/
|
|
54
|
+
export function maskText(text, protect, callerMarkup) {
|
|
55
|
+
const tokens = [...new Set(protect.filter((token) => token.length > 0))]
|
|
56
|
+
.map((token) => (callerMarkup ? token : escapeHtml(token)))
|
|
57
|
+
.sort((a, b) => b.length - a.length)
|
|
58
|
+
.map((token) => token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
59
|
+
const source = callerMarkup ? text : escapeHtml(text);
|
|
60
|
+
const originals = [];
|
|
61
|
+
const masked = tokens.length > 0
|
|
62
|
+
? source.replace(new RegExp(tokens.join('|'), 'g'), (match) => {
|
|
63
|
+
originals.push(callerMarkup ? match : decodeEntities(match));
|
|
64
|
+
return `<span translate="no">${originals.length - 1}</span>`;
|
|
65
|
+
})
|
|
66
|
+
: source;
|
|
67
|
+
return { masked, originals };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Restores a Google result: entities decoded (plain text only), then protected
|
|
71
|
+
* substrings back by index, keeping any whitespace Google moved inside the span.
|
|
72
|
+
*
|
|
73
|
+
* @param translated - Google's output.
|
|
74
|
+
* @param originals - The substrings `maskText` protected.
|
|
75
|
+
* @param callerMarkup - True when the caller set `tagHandling`.
|
|
76
|
+
* @returns The restored text.
|
|
77
|
+
*/
|
|
78
|
+
export function unmaskText(translated, originals, callerMarkup) {
|
|
79
|
+
const decoded = callerMarkup ? translated : decodeEntities(translated);
|
|
80
|
+
return decoded.replace(/<span translate="no">(\s*)(\d+)(\s*)<\/span>/g, (match, before, index, after) => {
|
|
81
|
+
const original = originals[Number(index)];
|
|
82
|
+
return original === undefined ? match : `${before}${original}${after}`;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation implementation of AITranslationProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses the Cloud Translation API (Basic, v2 REST) with an API key. Requests are
|
|
5
|
+
* always sent as HTML (`format=html`) so `protect` substrings can ride in
|
|
6
|
+
* `translate="no"` spans; plain-text input is escaped on the way in and decoded on
|
|
7
|
+
* the way out, so callers see plain text unless they set `tagHandling`.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import './secrets.js';
|
|
12
|
+
import type { AITranslationProvider } from '@molecule/api-ai-translation';
|
|
13
|
+
import type { GoogleTranslateConfig } from './types.js';
|
|
14
|
+
/**
|
|
15
|
+
* Creates a Google Cloud Translation provider instance.
|
|
16
|
+
*
|
|
17
|
+
* @param config - Google-specific configuration (API key, base URL).
|
|
18
|
+
* @returns An `AITranslationProvider` backed by the Cloud Translation API.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createProvider(config?: GoogleTranslateConfig): AITranslationProvider;
|
|
21
|
+
/**
|
|
22
|
+
* The provider implementation.
|
|
23
|
+
*/
|
|
24
|
+
export declare const provider: AITranslationProvider;
|
|
25
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EACV,qBAAqB,EAKtB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAkNvD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,qBAAqB,GAAG,qBAAqB,CAEpF;AAID;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,qBAUrB,CAAA"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation implementation of AITranslationProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses the Cloud Translation API (Basic, v2 REST) with an API key. Requests are
|
|
5
|
+
* always sent as HTML (`format=html`) so `protect` substrings can ride in
|
|
6
|
+
* `translate="no"` spans; plain-text input is escaped on the way in and decoded on
|
|
7
|
+
* the way out, so callers see plain text unless they set `tagHandling`.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
// Side-effect import: registers this bond's secret definitions so the
|
|
12
|
+
// runtime registry is populated even when provider.js is imported directly
|
|
13
|
+
// (not through the package barrel).
|
|
14
|
+
import './secrets.js';
|
|
15
|
+
import { maskText, unmaskText } from './protect.js';
|
|
16
|
+
/** Statuses worth retrying (403 only when it is a rate limit — see `isRetryable`). */
|
|
17
|
+
const RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);
|
|
18
|
+
/**
|
|
19
|
+
* Google answers bursts with 403 "User Rate Limit Exceeded" as well as 429, so a
|
|
20
|
+
* 403 is retried when its body says rate limit — and a real auth 403 fails at once.
|
|
21
|
+
*
|
|
22
|
+
* @param response - The response to classify.
|
|
23
|
+
* @returns True when the request should be retried.
|
|
24
|
+
*/
|
|
25
|
+
async function isRetryable(response) {
|
|
26
|
+
if (RETRYABLE_STATUS_CODES.has(response.status))
|
|
27
|
+
return true;
|
|
28
|
+
if (response.status !== 403)
|
|
29
|
+
return false;
|
|
30
|
+
const body = await response.clone().text();
|
|
31
|
+
return /rate ?limit/i.test(body);
|
|
32
|
+
}
|
|
33
|
+
/** Maximum retry attempts for retryable errors. */
|
|
34
|
+
const MAX_RETRIES = 5;
|
|
35
|
+
/** Maximum `q` entries per request (Cloud Translation v2 limit). */
|
|
36
|
+
const MAX_TEXTS_PER_REQUEST = 128;
|
|
37
|
+
/** Stay well under the v2 request-size limit; long batches are split by characters too. */
|
|
38
|
+
const MAX_CHARS_PER_REQUEST = 25_000;
|
|
39
|
+
/**
|
|
40
|
+
* Google Cloud Translation provider implementing `AITranslationProvider`.
|
|
41
|
+
*/
|
|
42
|
+
class GoogleTranslationProvider {
|
|
43
|
+
name = 'google';
|
|
44
|
+
apiKey;
|
|
45
|
+
baseUrl;
|
|
46
|
+
/** Characters sent by this process — Google has no usage endpoint. */
|
|
47
|
+
charactersSent = 0;
|
|
48
|
+
/**
|
|
49
|
+
* Creates a new Google Cloud Translation provider.
|
|
50
|
+
*
|
|
51
|
+
* @param config - Provider configuration. API key defaults to GOOGLE_TRANSLATE_API_KEY.
|
|
52
|
+
*/
|
|
53
|
+
constructor(config = {}) {
|
|
54
|
+
this.apiKey = config.apiKey ?? process.env.GOOGLE_TRANSLATE_API_KEY ?? '';
|
|
55
|
+
this.baseUrl =
|
|
56
|
+
config.baseUrl ??
|
|
57
|
+
process.env.GOOGLE_TRANSLATE_BASE_URL ??
|
|
58
|
+
'https://translation.googleapis.com';
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Translate one or more texts, batching by count and size.
|
|
62
|
+
*
|
|
63
|
+
* @param params - Translation parameters. `formality`, `glossaryId`, `modelType`,
|
|
64
|
+
* `context` and `preserveFormatting` have no v2 equivalent and are ignored.
|
|
65
|
+
* @returns One translation per input text, in order.
|
|
66
|
+
*/
|
|
67
|
+
async translate(params) {
|
|
68
|
+
const texts = Array.isArray(params.text) ? params.text : [params.text];
|
|
69
|
+
const translations = [];
|
|
70
|
+
let batch = [];
|
|
71
|
+
let batchChars = 0;
|
|
72
|
+
for (const text of texts) {
|
|
73
|
+
if (batch.length > 0 &&
|
|
74
|
+
(batch.length >= MAX_TEXTS_PER_REQUEST || batchChars + text.length > MAX_CHARS_PER_REQUEST)) {
|
|
75
|
+
translations.push(...(await this.callTranslate(batch, params)));
|
|
76
|
+
batch = [];
|
|
77
|
+
batchChars = 0;
|
|
78
|
+
}
|
|
79
|
+
batch.push(text);
|
|
80
|
+
batchChars += text.length;
|
|
81
|
+
}
|
|
82
|
+
if (batch.length > 0)
|
|
83
|
+
translations.push(...(await this.callTranslate(batch, params)));
|
|
84
|
+
return { translations };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* List the languages Google translates, named in English.
|
|
88
|
+
*
|
|
89
|
+
* @param _type - Ignored: Google's source and target lists are the same.
|
|
90
|
+
* @returns Supported languages (BCP-47-style codes such as 'de', 'zh-TW').
|
|
91
|
+
*/
|
|
92
|
+
async getSupportedLanguages(_type) {
|
|
93
|
+
const url = new URL('/language/translate/v2/languages', this.baseUrl);
|
|
94
|
+
url.searchParams.set('key', this.apiKey);
|
|
95
|
+
url.searchParams.set('target', 'en');
|
|
96
|
+
const response = await this.fetchWithRetry(url.toString(), { method: 'GET' });
|
|
97
|
+
if (!response.ok)
|
|
98
|
+
throw await this.buildError('languages', response);
|
|
99
|
+
const data = (await response.json());
|
|
100
|
+
return data.data.languages.map((lang) => ({
|
|
101
|
+
language: lang.language,
|
|
102
|
+
name: lang.name ?? lang.language,
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Google exposes no usage endpoint; this reports what THIS process has sent.
|
|
107
|
+
*
|
|
108
|
+
* @returns Characters sent since startup, and an unbounded limit.
|
|
109
|
+
*/
|
|
110
|
+
async getUsage() {
|
|
111
|
+
return { characterCount: this.charactersSent, characterLimit: Number.POSITIVE_INFINITY };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* One request to the v2 translate endpoint.
|
|
115
|
+
*
|
|
116
|
+
* @param texts - Texts for this batch.
|
|
117
|
+
* @param params - Translation parameters.
|
|
118
|
+
* @returns Translations for this batch, in order.
|
|
119
|
+
*/
|
|
120
|
+
async callTranslate(texts, params) {
|
|
121
|
+
const callerMarkup = params.tagHandling !== undefined;
|
|
122
|
+
const masked = texts.map((text) => maskText(text, params.protect ?? [], callerMarkup));
|
|
123
|
+
const url = new URL('/language/translate/v2', this.baseUrl);
|
|
124
|
+
url.searchParams.set('key', this.apiKey);
|
|
125
|
+
const body = {
|
|
126
|
+
q: masked.map((m) => m.masked),
|
|
127
|
+
target: params.targetLang,
|
|
128
|
+
format: 'html',
|
|
129
|
+
};
|
|
130
|
+
if (params.sourceLang)
|
|
131
|
+
body.source = params.sourceLang;
|
|
132
|
+
const response = await this.fetchWithRetry(url.toString(), {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: { 'Content-Type': 'application/json' },
|
|
135
|
+
body: JSON.stringify(body),
|
|
136
|
+
});
|
|
137
|
+
if (!response.ok)
|
|
138
|
+
throw await this.buildError('translate', response);
|
|
139
|
+
this.charactersSent += texts.reduce((sum, text) => sum + text.length, 0);
|
|
140
|
+
const data = (await response.json());
|
|
141
|
+
return data.data.translations.map((t, i) => ({
|
|
142
|
+
text: unmaskText(t.translatedText, masked[i].originals, callerMarkup),
|
|
143
|
+
detectedSourceLang: t.detectedSourceLanguage ?? params.sourceLang ?? '',
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Fetch with exponential backoff on rate-limit and server errors.
|
|
148
|
+
*
|
|
149
|
+
* @param url - The URL to fetch.
|
|
150
|
+
* @param init - Fetch request options.
|
|
151
|
+
* @returns The final response.
|
|
152
|
+
*/
|
|
153
|
+
async fetchWithRetry(url, init) {
|
|
154
|
+
let response = null;
|
|
155
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
156
|
+
response = await fetch(url, init);
|
|
157
|
+
if (attempt < MAX_RETRIES && (await isRetryable(response))) {
|
|
158
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(1000 * 2 ** attempt, 30_000)));
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
return response;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Builds an error from a failed response, carrying the HTTP status.
|
|
167
|
+
*
|
|
168
|
+
* @param endpoint - The endpoint name (for the message).
|
|
169
|
+
* @param response - The failed response.
|
|
170
|
+
* @returns An Error with a `status` property.
|
|
171
|
+
*/
|
|
172
|
+
async buildError(endpoint, response) {
|
|
173
|
+
const errorBody = await response.text();
|
|
174
|
+
let detail = `HTTP ${response.status}`;
|
|
175
|
+
try {
|
|
176
|
+
const parsed = JSON.parse(errorBody);
|
|
177
|
+
if (parsed.error?.message)
|
|
178
|
+
detail = parsed.error.message;
|
|
179
|
+
}
|
|
180
|
+
catch (_error) {
|
|
181
|
+
// JSON.parse failed — error body is not JSON; fall back to raw text if short enough.
|
|
182
|
+
if (errorBody.length > 0 && errorBody.length < 200)
|
|
183
|
+
detail = errorBody;
|
|
184
|
+
}
|
|
185
|
+
return Object.assign(new Error(`Google Translate ${endpoint} API error (${response.status}): ${detail}`), { status: response.status });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Creates a Google Cloud Translation provider instance.
|
|
190
|
+
*
|
|
191
|
+
* @param config - Google-specific configuration (API key, base URL).
|
|
192
|
+
* @returns An `AITranslationProvider` backed by the Cloud Translation API.
|
|
193
|
+
*/
|
|
194
|
+
export function createProvider(config) {
|
|
195
|
+
return new GoogleTranslationProvider(config);
|
|
196
|
+
}
|
|
197
|
+
/** Lazily-initialized provider singleton. Defers creation until first use so that env vars / secrets are resolved. */
|
|
198
|
+
let _provider = null;
|
|
199
|
+
/**
|
|
200
|
+
* The provider implementation.
|
|
201
|
+
*/
|
|
202
|
+
export const provider = new Proxy({}, {
|
|
203
|
+
get(_, prop, receiver) {
|
|
204
|
+
if (!_provider)
|
|
205
|
+
_provider = createProvider();
|
|
206
|
+
return Reflect.get(_provider, prop, receiver);
|
|
207
|
+
},
|
|
208
|
+
// 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)
|
|
209
|
+
set(_, prop, value) {
|
|
210
|
+
if (!_provider)
|
|
211
|
+
_provider = createProvider();
|
|
212
|
+
return Reflect.set(_provider, prop, value);
|
|
213
|
+
},
|
|
214
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation secret definitions — self-registered at import time so
|
|
3
|
+
* the 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 Google Cloud Translation bond. */
|
|
15
|
+
export declare const aiTranslationGoogleSecretDefinitions: 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,wEAAwE;AACxE,eAAO,MAAM,oCAAoC,EAAE,gBAAgB,EASlE,CAAA"}
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation secret definitions — self-registered at import time so
|
|
3
|
+
* the 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 Google Cloud Translation bond. */
|
|
15
|
+
export const aiTranslationGoogleSecretDefinitions = [
|
|
16
|
+
{
|
|
17
|
+
key: 'GOOGLE_TRANSLATE_API_KEY',
|
|
18
|
+
description: 'Google Cloud Translation API key — Create an API key in a Google Cloud project with the Cloud Translation API enabled.',
|
|
19
|
+
helpUrl: 'https://console.cloud.google.com/apis/credentials',
|
|
20
|
+
required: true,
|
|
21
|
+
example: 'AIzaSy...',
|
|
22
|
+
},
|
|
23
|
+
];
|
|
24
|
+
registerSecrets(aiTranslationGoogleSecretDefinitions);
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Cloud Translation provider configuration.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for the Google Cloud Translation provider.
|
|
8
|
+
*/
|
|
9
|
+
export interface GoogleTranslateConfig {
|
|
10
|
+
/** Google Cloud API key with the Cloud Translation API enabled. Defaults to GOOGLE_TRANSLATE_API_KEY. */
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
/** Base URL of the Translation API. Defaults to GOOGLE_TRANSLATE_BASE_URL, then 'https://translation.googleapis.com'. */
|
|
13
|
+
baseUrl?: string;
|
|
14
|
+
}
|
|
15
|
+
//# 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;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,yGAAyG;IACzG,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,yHAAyH;IACzH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB"}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ai-translation-google",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Google Cloud Translation provider for molecule.dev — text translation via the Google Translate API",
|
|
5
|
+
"homepage": "https://www.molecule.dev/packages/api-ai-translation-google",
|
|
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
|
+
"google",
|
|
29
|
+
"google-translate"
|
|
30
|
+
],
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/molecule-dev/molecule.git",
|
|
35
|
+
"directory": "packages/api/bonds/ai-translation/google"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@molecule/api-ai-translation": ">=1.0.1",
|
|
39
|
+
"@molecule/api-secrets": "^1.0.1"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@molecule/api-ai-translation": "1.1.0",
|
|
43
|
+
"@types/node": "26.1.2",
|
|
44
|
+
"typescript": "6.0.3",
|
|
45
|
+
"vitest": "4.1.11"
|
|
46
|
+
}
|
|
47
|
+
}
|