@alaikis/translation-sdk 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/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@alaikis/translation-sdk",
3
+ "version": "1.0.0",
4
+ "description": "Laker Translation Service SDK for TypeScript/JavaScript",
5
+ "main": "translation-client.js",
6
+ "types": "translation-client.d.ts",
7
+ "files": [
8
+ "*.js",
9
+ "*.d.ts"
10
+ ],
11
+ "keywords": [
12
+ "translation",
13
+ "grpc-web",
14
+ "laker",
15
+ "llm"
16
+ ],
17
+ "author": "alaikis",
18
+ "license": "MIT",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/alaikis/laker-translate-sdk.git",
22
+ "directory": "js"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/alaikis/laker-translate-sdk/issues"
26
+ },
27
+ "homepage": "https://github.com/alaikis/laker-translate-sdk#readme"
28
+ }
@@ -0,0 +1,502 @@
1
+ /**
2
+ * Translation Service gRPC-Web TypeScript/JavaScript Client
3
+ *
4
+ * Auto-generated for api.laker.dev Translation Service
5
+ * Service: TranslationService
6
+ * Source: proto/translation.proto
7
+ */
8
+ export interface TranslateRecord {
9
+ id: string;
10
+ text: string;
11
+ translate: string;
12
+ isCustom: boolean;
13
+ }
14
+ export interface GetSenseTranslateRequest {
15
+ senseId: string;
16
+ fingerprint?: string;
17
+ page?: number;
18
+ pageSize?: number;
19
+ }
20
+ export interface GetSenseTranslateResponse {
21
+ senseId: string;
22
+ total: number;
23
+ page: number;
24
+ pageSize: number;
25
+ translations: TranslateRecord[];
26
+ }
27
+ export interface TranslateStreamRequest {
28
+ senseId: string;
29
+ fingerprint?: string;
30
+ batchSize?: number;
31
+ }
32
+ export interface TranslateStreamResponse {
33
+ batch: number;
34
+ hasMore: boolean;
35
+ total: number;
36
+ translations: TranslateRecord[];
37
+ }
38
+ /**
39
+ * Result of template extraction
40
+ */
41
+ export interface TemplateExtractResult {
42
+ isTemplated: boolean;
43
+ srcTemplate: string;
44
+ dstTemplate: string;
45
+ variables: string[];
46
+ }
47
+ export interface LLMTranslateRequest {
48
+ text: string;
49
+ fromLang?: string;
50
+ toLang: string;
51
+ provider?: string;
52
+ senseId?: string;
53
+ }
54
+ export interface LLMTranslateResponse {
55
+ originalText: string;
56
+ translatedText: string;
57
+ provider: string;
58
+ timestamp: number;
59
+ finished: boolean;
60
+ cached: boolean;
61
+ fromLang?: string;
62
+ toLang?: string;
63
+ }
64
+ /**
65
+ * Result of translation lookup in TranslationPool
66
+ */
67
+ export interface TranslationLookupResult {
68
+ found: boolean;
69
+ translation: string;
70
+ source: 'special' | 'common' | null;
71
+ }
72
+ /**
73
+ * Cross-tab cache synchronization options
74
+ */
75
+ export interface CrossTabOptions {
76
+ enabled: boolean;
77
+ channelName?: string;
78
+ storageKeyPrefix?: string;
79
+ }
80
+ /**
81
+ * Automatic template extraction from text containing numeric variables
82
+ * @param text Original text that may contain numeric variables
83
+ * @returns Template extraction result
84
+ */
85
+ export declare function extractTemplate(text: string): TemplateExtractResult;
86
+ /**
87
+ * Translation options
88
+ */
89
+ export interface TranslationServiceOptions {
90
+ senseId: string;
91
+ fingerprint?: string;
92
+ crossTab?: boolean;
93
+ crossTabChannelName?: string;
94
+ crossTabStorageKeyPrefix?: string;
95
+ }
96
+ /**
97
+ * TranslationService - Main entry point for translation operations
98
+ * Provides a clean API with automatic caching and cross-tab synchronization
99
+ *
100
+ * Features:
101
+ * - Lazy initialization: automatically initializes on first translate() call
102
+ * - Streaming batch load: uses streaming API for efficient initialization
103
+ * - On-demand loading: automatically loads when fingerprint changes
104
+ * - Cross-tab sync: optional Broadcast Channel + localStorage synchronization
105
+ *
106
+ * Usage:
107
+ * - Simple: Just create and call translate() - initialization is automatic
108
+ * - Advanced: Call initialize() explicitly to preload all translations upfront
109
+ */
110
+ export declare class TranslationService {
111
+ private client;
112
+ private pool;
113
+ private initialized;
114
+ private initPromise;
115
+ private options;
116
+ /**
117
+ * Create a new TranslationService instance
118
+ * @param client TranslationClient instance (or base URL string to create one automatically)
119
+ * @param options Translation service options including senseId and optional fingerprint/cross-tab settings
120
+ */
121
+ constructor(client: TranslationClient | string, options: TranslationServiceOptions);
122
+ /**
123
+ * Ensure the service is initialized (lazy initialization)
124
+ * Called automatically by translate() if needed
125
+ */
126
+ private ensureInitialized;
127
+ /**
128
+ * Actual initialization logic
129
+ */
130
+ private doInitialize;
131
+ /**
132
+ * Initialize the translation service - loads all translations from backend
133
+ *
134
+ * This is optional - translate() will automatically initialize if needed.
135
+ * Call this explicitly if you want to preload all translations upfront.
136
+ *
137
+ * Automatically handles cross-tab synchronization if enabled.
138
+ */
139
+ initialize(): Promise<void>;
140
+ /**
141
+ * Check if service has been initialized
142
+ */
143
+ isInitialized(): boolean;
144
+ /**
145
+ * Switch to a different fingerprint (for personalized/custom translations)
146
+ * Automatically loads all translations for this fingerprint
147
+ * @param fingerprint - The fingerprint to switch to
148
+ */
149
+ switchFingerprint(fingerprint: string): Promise<void>;
150
+ /**
151
+ * Clear the current fingerprint - frees memory
152
+ */
153
+ clearCurrentFingerprint(): void;
154
+ /**
155
+ * Add a custom translation to the current pool
156
+ * @param text - Original text
157
+ * @param translation - Translated text
158
+ */
159
+ addCustomTranslation(text: string, translation: string): void;
160
+ /**
161
+ * Lookup translation in cache
162
+ * Note: If not initialized, will return not found
163
+ * @param text - Text to lookup
164
+ * @returns Lookup result with found flag and translation if available
165
+ */
166
+ lookup(text: string): TranslationLookupResult;
167
+ /**
168
+ * Translate text with automatic caching
169
+ *
170
+ * Features:
171
+ * - Lazy initialization: automatically initializes on first call
172
+ * - Checks cache first
173
+ * - If not found in cache, requests from backend and caches result
174
+ *
175
+ * @param text - Text to translate
176
+ * @param toLang - Target language (2-letter code)
177
+ * @param fromLang - Optional source language (2-letter code)
178
+ * @param provider - Optional translation provider name
179
+ * @returns Translation response
180
+ */
181
+ translate(text: string, toLang: string, fromLang?: string, provider?: string): Promise<LLMTranslateResponse>;
182
+ /**
183
+ * Direct translation - bypasses cache and always requests from backend
184
+ * Use this for one-off translations when you don't need caching
185
+ *
186
+ * @param text - Text to translate
187
+ * @param toLang - Target language (2-letter code)
188
+ * @param fromLang - Optional source language (2-letter code)
189
+ * @param provider - Optional translation provider name
190
+ * @returns Translation response
191
+ */
192
+ translateDirect(text: string, toLang: string, fromLang?: string, provider?: string): Promise<LLMTranslateResponse>;
193
+ /**
194
+ * Stream translations from backend in batches
195
+ * Used for bulk loading all translations in a sense
196
+ *
197
+ * @param request - Stream request parameters
198
+ * @param onBatch - Callback for each batch received
199
+ */
200
+ streamTranslate(request: TranslateStreamRequest, onBatch: (response: TranslateStreamResponse) => boolean | void): Promise<void>;
201
+ /**
202
+ * Get the sense ID this service is connected to
203
+ */
204
+ getSenseId(): string;
205
+ /**
206
+ * Clear all cached data to free memory
207
+ */
208
+ clearAll(): void;
209
+ /**
210
+ * Destroy the service, close connections and free resources
211
+ * Should be called when the service is no longer needed
212
+ */
213
+ destroy(): void;
214
+ }
215
+ /**
216
+ * Cross-tab cache synchronization options for TranslationClient
217
+ */
218
+ export interface ClientCrossTabOptions {
219
+ enabled: boolean;
220
+ channelName?: string;
221
+ storageKey?: string;
222
+ }
223
+ /**
224
+ * TranslationClient - Low-level gRPC-Web compatible client for TranslationService
225
+ * Uses JSON over HTTP transport for compatibility
226
+ * Includes LRU cache with optional Broadcast Channel + localStorage synchronization
227
+ */
228
+ export declare class TranslationClient {
229
+ private baseUrl;
230
+ private token;
231
+ private timeout;
232
+ private cache;
233
+ private cacheEnabled;
234
+ private crossTabOptions;
235
+ private broadcastChannel;
236
+ private storageKey;
237
+ /**
238
+ * Create a new TranslationClient
239
+ * @param baseUrl Base URL of the gRPC-Web endpoint, defaults to https://api.hottol.com/laker/
240
+ * @param token JWT authentication token (optional)
241
+ * @param timeout Request timeout in milliseconds (default: 30000)
242
+ * @param cacheSize LRU cache size (default: 1000, set to 0 to disable cache)
243
+ * @param crossTabOptions Cross-tab synchronization options (default: disabled)
244
+ */
245
+ constructor(baseUrl?: string, token?: string, timeout?: number, cacheSize?: number, crossTabOptions?: Partial<ClientCrossTabOptions>);
246
+ /**
247
+ * Initialize cross-tab synchronization via Broadcast Channel
248
+ */
249
+ private initCrossTabSync;
250
+ /**
251
+ * Load cache from localStorage
252
+ */
253
+ private loadFromStorage;
254
+ /**
255
+ * Save cache to localStorage
256
+ */
257
+ private saveToStorage;
258
+ /**
259
+ * Get all cache entries for storage/broadcast
260
+ */
261
+ private getAllCacheEntries;
262
+ /**
263
+ * Broadcast full cache to other tabs
264
+ */
265
+ private broadcastFullCache;
266
+ /**
267
+ * Broadcast a single cache update to other tabs
268
+ */
269
+ private broadcastCacheUpdate;
270
+ /**
271
+ * Set or update the JWT authentication token
272
+ * @param token JWT token
273
+ */
274
+ setToken(token: string): void;
275
+ /**
276
+ * Enable or disable cache
277
+ * @param enabled Whether to enable cache
278
+ */
279
+ setCacheEnabled(enabled: boolean): void;
280
+ /**
281
+ * Clear the translation cache (also clears localStorage and broadcasts to other tabs)
282
+ */
283
+ clearCache(): void;
284
+ /**
285
+ * Get current cache size
286
+ */
287
+ getCacheSize(): number;
288
+ /**
289
+ * Check if cross-tab synchronization is enabled
290
+ */
291
+ isCrossTabEnabled(): boolean;
292
+ /**
293
+ * Destroy the client, close broadcast channel and free resources
294
+ */
295
+ destroy(): void;
296
+ /**
297
+ 凤 * GetSenseTranslate - One-shot unary request with pagination
298
+ * @param request Request parameters
299
+ */
300
+ getSenseTranslate(request: GetSenseTranslateRequest): Promise<GetSenseTranslateResponse>;
301
+ /**
302
+ * TranslateStream - Server streaming, receives multiple batches progressively
303
+ * @param request Request parameters
304
+ * @param onBatch Callback for each batch received. Return false to stop streaming early.
305
+ */
306
+ translateStream(request: TranslateStreamRequest, onBatch: (response: TranslateStreamResponse) => boolean | void): Promise<void>;
307
+ /**
308
+ * Collect all streaming responses into an array
309
+ * @param request Request parameters
310
+ */
311
+ translateStreamCollect(request: TranslateStreamRequest): Promise<TranslateStreamResponse[]>;
312
+ /**
313
+ * LLMTranslate - One-shot large language model translation
314
+ * Uses LRU cache to avoid repeated requests for the same text
315
+ * With cross-tab enabled, automatically syncs cache across browser tabs
316
+ * @param request Translation request
317
+ * @param skipCache If true, bypass cache and always request from backend
318
+ */
319
+ llmTranslate(request: LLMTranslateRequest, skipCache?: boolean): Promise<LLMTranslateResponse>;
320
+ /**
321
+ * LLMTranslateStream - Streaming large language model translation
322
+ * Note: Streaming requests are not cached
323
+ * @param request Translation request
324
+ * @param onResponse Callback for each response chunk
325
+ */
326
+ llmTranslateStream(request: LLMTranslateRequest, onResponse: (response: LLMTranslateResponse) => boolean | void): Promise<void>;
327
+ private getHeaders;
328
+ private fetchJson;
329
+ private fetchWithTimeout;
330
+ }
331
+ /**
332
+ * AppTranslation - Application-level translation interface
333
+ * Single entry point for all translation needs with automatic initialization,
334
+ * intelligent caching, and on-demand loading.
335
+ *
336
+ * Features:
337
+ * - Single entry point: just provide token and senseId
338
+ * - Automatic streaming batch initialization
339
+ * - On-demand loading when fingerprint changes
340
+ * - Intelligent translation with cache-first strategy
341
+ * - Cross-tab synchronization support
342
+ *
343
+ * Usage:
344
+ * ```typescript
345
+ * // Create instance
346
+ * const appTranslate = new AppTranslation({
347
+ * token: 'your-jwt-token',
348
+ * senseId: 'your-sense-id',
349
+ * baseUrl: 'https://api.laker.dev'
350
+ * });
351
+ *
352
+ * // Simple translation - auto-initializes
353
+ * const result = await appTranslate.translate('Hello', 'zh');
354
+ *
355
+ * // Switch fingerprint - auto-loads special translations
356
+ * await appTranslate.setFingerprint('user-123');
357
+ *
358
+ * // Destroy when done
359
+ * appTranslate.destroy();
360
+ * ```
361
+ */
362
+ export declare class AppTranslation {
363
+ private client;
364
+ private service;
365
+ private config;
366
+ private currentFingerprint;
367
+ private useCache;
368
+ /**
369
+ * Create a new AppTranslation instance
370
+ * @param config Configuration options
371
+ */
372
+ constructor(config: AppTranslationConfig);
373
+ /**
374
+ * Update the authentication token
375
+ * @param token New JWT token
376
+ */
377
+ setToken(token: string): void;
378
+ /**
379
+ * Set or change the current fingerprint
380
+ * Automatically loads special translations for this fingerprint
381
+ * @param fingerprint The fingerprint to use
382
+ */
383
+ setFingerprint(fingerprint: string): Promise<void>;
384
+ /**
385
+ * Clear the current fingerprint
386
+ * Falls back to common translations
387
+ */
388
+ clearFingerprint(): void;
389
+ /**
390
+ * Get the current fingerprint
391
+ */
392
+ getFingerprint(): string | null;
393
+ /**
394
+ * Translate text with automatic caching and initialization
395
+ *
396
+ * - First call initializes the service automatically
397
+ * - Checks cache first (fingerprint-specific → common)
398
+ * - Falls back to LLM translation if not found
399
+ * - Caches result automatically (unless useCache: false)
400
+ *
401
+ * @param text Text to translate
402
+ * @param toLang Target language code (e.g., 'zh', 'en')
403
+ * @param fromLang Optional source language code (auto-detected if not provided)
404
+ * @returns Translation result
405
+ */
406
+ translate(text: string, toLang: string, fromLang?: string): Promise<string>;
407
+ /**
408
+ * Translate text with full response details
409
+ * @param text Text to translate
410
+ * @param toLang Target language code
411
+ * @param fromLang Optional source language code
412
+ * @returns Full translation response
413
+ */
414
+ translateWithDetails(text: string, toLang: string, fromLang?: string): Promise<LLMTranslateResponse>;
415
+ /**
416
+ * Translate text without using cache (always request from backend)
417
+ * @param text Text to translate
418
+ * @param toLang Target language code
419
+ * @param fromLang Optional source language code
420
+ * @returns Translation result
421
+ */
422
+ translateNoCache(text: string, toLang: string, fromLang?: string): Promise<string>;
423
+ /**
424
+ * Batch translate multiple texts
425
+ * @param texts Array of texts to translate
426
+ * @param toLang Target language code
427
+ * @param fromLang Optional source language code
428
+ * @returns Array of translated texts in same order
429
+ */
430
+ translateBatch(texts: string[], toLang: string, fromLang?: string): Promise<string[]>;
431
+ /**
432
+ * Check if cache is enabled
433
+ * @returns true if cache is enabled
434
+ */
435
+ isCacheEnabled(): boolean;
436
+ /**
437
+ * Check if a translation exists in cache
438
+ * @param text Text to check
439
+ * @returns true if translation exists in cache
440
+ */
441
+ hasTranslation(text: string): boolean;
442
+ /**
443
+ * Get translation from cache without requesting from backend
444
+ * @param text Text to look up
445
+ * @returns Translation if found, null otherwise
446
+ */
447
+ getCached(text: string): string | null;
448
+ /**
449
+ * Add a custom translation to the cache
450
+ * @param text Original text
451
+ * @param translation Translated text
452
+ */
453
+ addTranslation(text: string, translation: string): void;
454
+ /**
455
+ * Preload all translations for current context
456
+ * Call this to warm up the cache before translating
457
+ */
458
+ preload(): Promise<void>;
459
+ /**
460
+ * Check if the service is initialized
461
+ */
462
+ isInitialized(): boolean;
463
+ /**
464
+ * Clear all cached translations
465
+ */
466
+ clearCache(): void;
467
+ /**
468
+ * Destroy the instance and free resources
469
+ * Call this when the instance is no longer needed
470
+ */
471
+ destroy(): void;
472
+ }
473
+ /**
474
+ * Configuration for AppTranslation
475
+ */
476
+ export interface AppTranslationConfig {
477
+ /** JWT authentication token */
478
+ token: string;
479
+ /** Translation sense ID */
480
+ senseId: string;
481
+ /** API base URL (optional, defaults to https://api.hottol.com/laker/) */
482
+ baseUrl?: string;
483
+ /** Request timeout in milliseconds (optional, defaults to 30000) */
484
+ timeout?: number;
485
+ /** LRU cache size (optional, defaults to 1000, set to 0 to disable cache) */
486
+ cacheSize?: number;
487
+ /** Initial fingerprint (optional) */
488
+ fingerprint?: string;
489
+ /** Enable cross-tab synchronization (optional, defaults to false) */
490
+ crossTab?: boolean;
491
+ /** Enable cache (optional, defaults to true. Set to false to disable all caching) */
492
+ useCache?: boolean;
493
+ }
494
+ /**
495
+ * Create an AppTranslation instance with simplified configuration
496
+ * @param token JWT authentication token
497
+ * @param senseId Translation sense ID
498
+ * @param options Additional options
499
+ * @returns AppTranslation instance
500
+ */
501
+ export declare function createTranslation(token: string, senseId: string, options?: Partial<AppTranslationConfig>): AppTranslation;
502
+ export default TranslationClient;