generaltranslation 9.5.0 → 9.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/adapter/createGtApi.js +49 -51
- package/dist/{derive-t_E3ftJN.cjs → derive-BgahX4Pv.cjs} +8 -30
- package/dist/derive-BgahX4Pv.cjs.map +1 -0
- package/dist/{derive-Cv5_y8Tf.mjs → derive-BotyrXAq.mjs} +9 -31
- package/dist/derive-BotyrXAq.mjs.map +1 -0
- package/dist/{derive-texIAHzc.d.mts → derive-VfZjYfIU.d.mts} +1 -1
- package/dist/{diagnostics-DYtVjOm5.d.mts → diagnostics-BKjlDmJK.d.mts} +1 -1
- package/dist/diagnostics.d.mts +1 -1
- package/dist/errors.cjs +7 -2
- package/dist/errors.d.cts +2 -9
- package/dist/errors.d.mts +2 -9
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/{file-Dga6cyM8.mjs → file-BZmC4OTj.mjs} +1 -1
- package/dist/{file-B37WkCqM.cjs.map → file-BZmC4OTj.mjs.map} +1 -1
- package/dist/{file-B37WkCqM.cjs → file-DNWSAhTC.cjs} +1 -1
- package/dist/{file-Dga6cyM8.mjs.map → file-DNWSAhTC.cjs.map} +1 -1
- package/dist/id.d.mts +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/internal.cjs +2 -2
- package/dist/internal.d.mts +3 -3
- package/dist/internal.mjs +2 -2
- package/dist/openapi.json +743 -93
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.d.mts +1 -1
- package/dist/runtime.mjs +1 -1
- package/dist/{runtimeTranslate-CVw143pQ.mjs → runtimeTranslate-CI936gg9.mjs} +3 -7
- package/dist/runtimeTranslate-CI936gg9.mjs.map +1 -0
- package/dist/{runtimeTranslate-DJioRjb6.cjs → runtimeTranslate-_gLYFBvE.cjs} +3 -7
- package/dist/runtimeTranslate-_gLYFBvE.cjs.map +1 -0
- package/dist/translate/utils/unwrapApiResult.js +2 -7
- package/dist/translate/utils/validateResponse.js +1 -1
- package/dist/{types-Si4UstLL.d.mts → types-CEsh60Yt.d.mts} +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +1 -1
- package/dist/utils/isSupportedFileFormatTransform.js +1 -0
- package/package.json +2 -2
- package/dist/ApiError-BCjEo_CM.cjs +0 -18
- package/dist/ApiError-BCjEo_CM.cjs.map +0 -1
- package/dist/ApiError-DxWKM0Xt.mjs +0 -13
- package/dist/ApiError-DxWKM0Xt.mjs.map +0 -1
- package/dist/derive-Cv5_y8Tf.mjs.map +0 -1
- package/dist/derive-t_E3ftJN.cjs.map +0 -1
- package/dist/errors/ApiError.d.ts +0 -5
- package/dist/errors/ApiError.js +0 -27
- package/dist/runtimeTranslate-CVw143pQ.mjs.map +0 -1
- package/dist/runtimeTranslate-DJioRjb6.cjs.map +0 -1
package/dist/runtime.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_runtimeTranslate = require("./runtimeTranslate-
|
|
2
|
+
const require_runtimeTranslate = require("./runtimeTranslate-_gLYFBvE.cjs");
|
|
3
3
|
let _generaltranslation_format = require("@generaltranslation/format");
|
|
4
4
|
//#region src/runtime.ts
|
|
5
5
|
/**
|
package/dist/runtime.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-
|
|
1
|
+
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-CEsh60Yt.mjs";
|
|
2
2
|
import { UserTokenProvider } from "@generaltranslation/api";
|
|
3
3
|
import { LocaleConfig } from "@generaltranslation/format";
|
|
4
4
|
import { CustomMapping, CustomRegionMapping, CutoffFormatOptions, FormatVariables, LocaleProperties, StringFormat } from "@generaltranslation/format/types";
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as noSourceLocaleProvidedError, f as noTargetLocaleProvidedError, l as invalidLocaleError, n as translateMany, t as translate, u as invalidLocalesError } from "./runtimeTranslate-
|
|
1
|
+
import { d as noSourceLocaleProvidedError, f as noTargetLocaleProvidedError, l as invalidLocaleError, n as translateMany, t as translate, u as invalidLocalesError } from "./runtimeTranslate-CI936gg9.mjs";
|
|
2
2
|
import { LocaleConfig, getRegionProperties, isValidLocale, requiresTranslation, resolveAliasLocale, resolveCanonicalLocale } from "@generaltranslation/format";
|
|
3
3
|
//#region src/runtime.ts
|
|
4
4
|
/**
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { t as createDiagnosticMessage } from "./diagnostics-DKA2SkZB.mjs";
|
|
2
2
|
import { t as hashSource } from "./id-B2wA7-S-.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import { ModelProvider, createApiClient, translate } from "@generaltranslation/api";
|
|
3
|
+
import { ApiError, ModelProvider, createApiClient, translate } from "@generaltranslation/api";
|
|
5
4
|
import { resolveCanonicalLocale, standardizeLocale } from "@generaltranslation/format";
|
|
6
5
|
//#region src/settings/settings.ts
|
|
7
6
|
const libraryDefaultLocale = "en";
|
|
@@ -316,10 +315,7 @@ function hasDecodedError(result) {
|
|
|
316
315
|
*/
|
|
317
316
|
function unwrapApiResult(result) {
|
|
318
317
|
if (result.data !== void 0) return result.data;
|
|
319
|
-
if (result.response)
|
|
320
|
-
const details = isErrorResult(result.error) ? result.error.error : typeof result.error === "string" ? result.error : result.response.statusText;
|
|
321
|
-
throw new ApiError(details, result.response.status, details);
|
|
322
|
-
}
|
|
318
|
+
if (result.response) throw ApiError.fromResponse(result.error, result.response);
|
|
323
319
|
throw result.error;
|
|
324
320
|
}
|
|
325
321
|
//#endregion
|
|
@@ -503,4 +499,4 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
503
499
|
//#endregion
|
|
504
500
|
export { unwrapApiResult as a, gtInstanceLogger as c, noSourceLocaleProvidedError as d, noTargetLocaleProvidedError as f, libraryDefaultLocale as g, defaultRuntimeApiUrl as h, isErrorResult as i, invalidLocaleError as l, defaultCacheUrl as m, translateMany as n, isModelProvider as o, defaultBaseUrl as p, validateAuth as r, supportedModelProviders as s, translate$1 as t, invalidLocalesError as u };
|
|
505
501
|
|
|
506
|
-
//# sourceMappingURL=runtimeTranslate-
|
|
502
|
+
//# sourceMappingURL=runtimeTranslate-CI936gg9.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeTranslate-CI936gg9.mjs","names":["translate","translateEndpoint"],"sources":["../src/settings/settings.ts","../src/settings/settingsUrls.ts","../src/logging/errors.ts","../src/logging/logger.ts","../src/adapter/modelProvider.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/unwrapApiResult.ts","../src/translate/utils/validateResponse.ts","../src/translate/runtimeTranslate.ts"],"sourcesContent":["export const libraryDefaultLocale = 'en' as const;\nexport const defaultTimeout = 60000;\n","export const defaultCacheUrl = 'https://cdn.gtx.dev' as const;\nexport const defaultBaseUrl = 'https://api.gtx.dev' as const;\nexport const defaultRuntimeApiUrl = 'https://api.gtx.dev' as const;\n","import { createDiagnosticMessage } from './diagnostics';\n\nconst GT_SOURCE = 'GT';\n\nexport const translationTimeoutError = (timeout: number) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Translation request timed out after ${timeout}ms`,\n fix: 'Try again, or increase the request timeout if the source content is large',\n });\n\nexport const translationRequestFailedError = (error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Translation request could not be completed',\n fix: 'Check your network connection and translation credentials, then try again',\n details: error,\n });\n\nexport const apiError = (status: number, statusText: string, error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `The translation API returned ${status} ${statusText}`,\n fix: 'Check the request configuration and try again',\n details: error,\n });\n\nexport const noTargetLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify targetLocale in the GT constructor`,\n });\n\nexport const noSourceLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify sourceLocale in the GT constructor`,\n });\n\nexport const noProjectIdProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified project ID`,\n fix: `Pass a project ID to \\`${functionName}\\` or specify projectId in the GT constructor`,\n });\n\nexport const noApiKeyProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified API key`,\n fix: `Pass an API key to \\`${functionName}\\` or specify apiKey in the GT constructor`,\n });\n\nexport const invalidLocaleError = (locale: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Locale \"${locale}\" is not valid`,\n fix: 'Use a valid BCP 47 locale code or add a custom mapping',\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `These locales are not valid: ${locales.join(', ')}`,\n fix: 'Use valid BCP 47 locale codes or add custom mappings',\n });\n","/**\n * Comprehensive logging system for the General Translation library.\n * Provides structured logging with multiple levels and configurable output.\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport type LogMetadataValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Date\n | Error\n | LogMetadataValue[]\n | { [key: string]: LogMetadataValue };\n\nexport type LogMetadata = Record<string, LogMetadataValue>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: Date;\n context?: string;\n metadata?: LogMetadata;\n}\n\nexport interface LoggerConfig {\n /** Minimum log level to output. */\n level: LogLevel;\n /** Whether to include timestamps in log output. */\n includeTimestamp: boolean;\n /** Whether to include context information. */\n includeContext: boolean;\n /** Custom prefix for all log messages. */\n prefix?: string;\n /** Whether to output to console (default: true) */\n enableConsole: boolean;\n /** Custom log handlers. */\n handlers?: LogHandler[];\n}\n\nexport interface LogHandler {\n handle(entry: LogEntry): void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n off: 4,\n};\n\nconst LOG_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n off: '', // No color needed since 'off' level logs are never displayed\n};\n\nconst RESET_COLOR = '\\x1b[0m';\n\n/**\n * Get the configured log level from environment variable or default to 'warn'\n */\nfunction getConfiguredLogLevel(): LogLevel {\n if (typeof process !== 'undefined' && process.env?._GT_LOG_LEVEL) {\n const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();\n if (envLevel in LOG_LEVELS) {\n return envLevel as LogLevel;\n }\n }\n return 'warn';\n}\n\n/**\n * Console log handler that outputs formatted messages to console\n */\nexport class ConsoleLogHandler implements LogHandler {\n private config: LoggerConfig;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n }\n\n handle(entry: LogEntry): void {\n const parts: string[] = [];\n\n // Add timestamp if enabled\n if (this.config.includeTimestamp) {\n parts.push(`[${entry.timestamp.toISOString()}]`);\n }\n\n // Add level with color\n const colorCode = LOG_COLORS[entry.level];\n const levelText = `[${entry.level.toUpperCase()}]`;\n parts.push(`${colorCode}${levelText}${RESET_COLOR}`);\n\n // Add prefix if configured\n if (this.config.prefix) {\n parts.push(`[${this.config.prefix}]`);\n }\n\n // Add context if available and enabled.\n if (this.config.includeContext && entry.context) {\n parts.push(`[${entry.context}]`);\n }\n\n // Add the main message\n parts.push(entry.message);\n\n // Format metadata if available.\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n parts.push(`\\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);\n }\n\n const formattedMessage = parts.join(' ');\n\n // Output to appropriate console method based on level\n switch (entry.level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(formattedMessage);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(formattedMessage);\n break;\n case 'warn':\n console.warn(formattedMessage);\n break;\n case 'error':\n console.error(formattedMessage);\n break;\n }\n }\n}\n\n/**\n * Main Logger class providing structured logging capabilities.\n */\nexport class Logger {\n private config: LoggerConfig;\n private handlers: LogHandler[];\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n enableConsole: true,\n handlers: [],\n ...config,\n };\n\n this.handlers = [...(this.config.handlers || [])];\n\n // Add console handler if enabled\n if (this.config.enableConsole) {\n this.handlers.push(new ConsoleLogHandler(this.config));\n }\n }\n\n /**\n * Add a custom log handler\n */\n addHandler(handler: LogHandler): void {\n this.handlers.push(handler);\n }\n\n /**\n * Remove a log handler\n */\n removeHandler(handler: LogHandler): void {\n const index = this.handlers.indexOf(handler);\n if (index > -1) {\n this.handlers.splice(index, 1);\n }\n }\n\n /**\n * Update logger configuration\n */\n configure(config: Partial<LoggerConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Check if a log level should be output based on current configuration\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n /**\n * Internal logging method that creates log entries and passes them to handlers\n */\n private log(\n level: LogLevel,\n message: string,\n context?: string,\n metadata?: LogMetadata\n ): void {\n if (!this.shouldLog(level)) {\n return;\n }\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n metadata,\n };\n\n // Pass to all handlers\n this.handlers.forEach((handler) => {\n try {\n handler.handle(entry);\n } catch (error) {\n // Prevent logging errors from breaking the application\n console.error('Error in log handler:', error);\n }\n });\n }\n\n /**\n * Log a debug message\n * Used for detailed diagnostic information, typically of interest only when diagnosing problems\n */\n debug(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('debug', message, context, metadata);\n }\n\n /**\n * Log an info message\n * Used for general information about application operation.\n */\n info(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('info', message, context, metadata);\n }\n\n /**\n * Log a warning message\n * Used for potentially problematic situations that don't prevent operation\n */\n warn(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('warn', message, context, metadata);\n }\n\n /**\n * Log an error message\n * Used for error events that might still allow the application to continue.\n */\n error(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('error', message, context, metadata);\n }\n\n /**\n * Create a child logger with a specific context\n */\n child(context: string): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Get current logger configuration\n */\n getConfig(): LoggerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Context logger that automatically includes context information.\n */\nexport class ContextLogger {\n private logger: Logger;\n private context: string;\n\n constructor(logger: Logger, context: string) {\n this.logger = logger;\n this.context = context;\n }\n\n debug(message: string, metadata?: LogMetadata): void {\n this.logger.debug(message, this.context, metadata);\n }\n\n info(message: string, metadata?: LogMetadata): void {\n this.logger.info(message, this.context, metadata);\n }\n\n warn(message: string, metadata?: LogMetadata): void {\n this.logger.warn(message, this.context, metadata);\n }\n\n error(message: string, metadata?: LogMetadata): void {\n this.logger.error(message, this.context, metadata);\n }\n\n child(childContext: string): ContextLogger {\n return new ContextLogger(this.logger, `${this.context}:${childContext}`);\n }\n}\n\n// Default logger instance. Pure annotations let bundlers drop the logger from\n// consumers that only import constants from the same chunk.\nexport const defaultLogger = /* @__PURE__ */ new Logger({\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n prefix: 'GT',\n});\n\n// Convenience functions using the default logger.\nexport const debug = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.debug(message, context, metadata);\n\nexport const info = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.info(message, context, metadata);\n\nexport const warn = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.warn(message, context, metadata);\n\nexport const error = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.error(message, context, metadata);\n\n// Create context-specific loggers for different parts of the system\nexport const fetchLogger = /* @__PURE__ */ defaultLogger.child('fetch');\nexport const gtInstanceLogger =\n /* @__PURE__ */ defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { ModelProvider } from '@generaltranslation/api';\n\nexport type { ModelProvider };\n\nexport const supportedModelProviders =\n /* @__PURE__ */ Object.values(ModelProvider);\n\nexport function isModelProvider(value: unknown): value is ModelProvider {\n return supportedModelProviders.includes(value as ModelProvider);\n}\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps a fetch implementation with the runtime translation timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeoutMs - The timeout in milliseconds. Omitted selects `defaultTimeout`,\n * `0` is a literal zero, and `false` disables the runtime-owned timer.\n * @param fetchImplementation - The fetch implementation to call. Defaults to global fetch.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeoutMs: number | false = defaultTimeout,\n fetchImplementation: typeof fetch = globalThis.fetch\n) {\n const controller = new AbortController();\n const signals = [controller.signal];\n if (options.signal) signals.push(options.signal);\n if (url instanceof Request) signals.push(url.signal);\n const signal = AbortSignal.any(signals);\n\n // Only a rejection with the SDK's own abort reason is a timeout. Native and\n // reason-preserving custom fetches keep distinct cancellations, even if the\n // SDK timer fires while they are cleaning up.\n let timedOut = false;\n const timeoutId =\n timeoutMs === false\n ? null\n : setTimeout(() => {\n timedOut = !signal.aborted;\n controller.abort();\n }, timeoutMs);\n\n try {\n const response = await fetchImplementation(url, { ...options, signal });\n return response;\n } catch (error) {\n if (timedOut && timeoutMs !== false && error === controller.signal.reason) {\n throw translationTimeoutError(timeoutMs);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { ApiError } from '@generaltranslation/api';\n\nexport function isErrorResult(error: unknown): error is { error: string } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'error' in error &&\n typeof error.error === 'string'\n );\n}\n\nexport function hasDecodedError(result: { error: unknown }): boolean {\n return isErrorResult(result.error) || typeof result.error === 'string';\n}\n\n/**\n * Unwraps a `@generaltranslation/api` SDK result, returning its data or\n * throwing an `ApiError` built from the failed response.\n */\nexport function unwrapApiResult<T>(result: {\n data: T | undefined;\n error: unknown;\n response?: Response;\n}): Exclude<T, undefined> {\n if (result.data !== undefined) {\n // TypeScript cannot narrow a generic T after excluding undefined; the\n // runtime guard above establishes the exact Exclude<T, undefined> result.\n return result.data as Exclude<T, undefined>;\n }\n if (result.response) {\n throw ApiError.fromResponse(result.error, result.response);\n }\n throw result.error;\n}\n","import { apiError } from '../../logging/errors';\nimport { ApiError } from '@generaltranslation/api';\n\nexport async function validateResponse(response: Response) {\n if (!response.ok) {\n let errorMsg = 'Unknown error';\n try {\n const text = await response.text();\n try {\n const errorJson = JSON.parse(text) as { error: string };\n errorMsg = errorJson.error;\n } catch {\n errorMsg = text || 'Unknown error';\n }\n } catch {\n // response.text() failed, keep 'Unknown error'\n }\n const errorMessage = apiError(\n response.status,\n response.statusText,\n errorMsg\n );\n const error = new ApiError(errorMessage, response.status, errorMsg);\n throw error;\n }\n}\n","import {\n createApiClient,\n translate as translateEndpoint,\n type JsonObject,\n type JsonValue,\n type RuntimeTranslationResponse,\n type TranslateData,\n} from '@generaltranslation/api';\nimport {\n resolveCanonicalLocale,\n standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n Content,\n GTProp,\n JsxChildren,\n JsxElement,\n} from '@generaltranslation/format/types';\nimport type {\n TranslateConfig,\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n} from '../types';\nimport type {\n EntryMetadata,\n TranslateManyEntry,\n TranslateOptions,\n} from '../types-dir/api/entry';\nimport { libraryDefaultLocale } from '../settings/settings';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n noApiKeyProvidedError,\n noProjectIdProvidedError,\n noTargetLocaleProvidedError,\n} from '../logging/errors';\nimport { gtInstanceLogger } from '../logging/logger';\nimport { createDiagnosticMessage } from '../logging/diagnostics';\nimport { hashSource } from '../id';\nimport {\n isModelProvider,\n supportedModelProviders,\n} from '../adapter/modelProvider';\nimport { fetchWithTimeout } from './utils/fetchWithTimeout';\nimport { hasDecodedError, unwrapApiResult } from './utils/unwrapApiResult';\nimport { validateResponse } from './utils/validateResponse';\n\ntype TranslateFunctionName = 'translate' | 'translateMany';\ntype TranslateDefaults = Partial<\n Pick<TranslateOptions, 'sourceLocale' | 'targetLocale'>\n>;\n\n/**\n * @internal\n * Credential/provider errors are reported before the project error, and both\n * before any locale validation. GT/GTRuntime share this ordering.\n */\nexport function validateAuth<\n T extends Pick<TranslateConfig, 'apiKey' | 'userTokenProvider' | 'projectId'>,\n>(\n functionName: string,\n config: T\n): asserts config is T & { projectId: string } {\n const errors: string[] = [];\n if (!config.apiKey && !config.userTokenProvider) {\n errors.push(noApiKeyProvidedError(functionName));\n }\n if (!config.projectId) {\n errors.push(noProjectIdProvidedError(functionName));\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n}\n\n/**\n * @internal\n *\n * Shared preparation for every translation surface (classes and the tooling\n * facade): normalize the string shorthand, validate auth, require a target\n * locale, default the source locale and canonicalize both for the wire.\n *\n * @param defaults - Instance defaults supplied by GT/GTRuntime. Facade calls pass none.\n */\nfunction prepareTranslation(\n functionName: TranslateFunctionName,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults: TranslateDefaults = {}\n): {\n options: TranslateOptions & { sourceLocale: string };\n config: TranslationRequestConfig;\n} {\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n validateAuth(functionName, config);\n\n const targetLocale = options?.targetLocale || defaults.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError(functionName);\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n const { customMapping, ...requestConfig } = config;\n // Mapping resolves aliases; standardization also canonicalizes configured\n // spellings such as en-us before they cross the service boundary.\n const resolveServiceLocale = (locale: string) =>\n standardizeLocale(resolveCanonicalLocale(locale, customMapping));\n\n return {\n options: {\n ...options,\n targetLocale: resolveServiceLocale(targetLocale),\n sourceLocale: resolveServiceLocale(\n options?.sourceLocale || defaults.sourceLocale || libraryDefaultLocale\n ),\n },\n config: requestConfig,\n };\n}\n\n/**\n * @internal\n * Translates a single entry with explicit configuration and optional locale defaults.\n */\nexport async function translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslationResult | TranslationError> {\n const prepared = prepareTranslation('translate', options, config, defaults);\n const results = await executeTranslationBatch(\n [source],\n prepared.options,\n prepared.config\n );\n return results[0];\n}\n\n/**\n * @internal\n * Translates multiple entries in one request with explicit configuration.\n * Returns an array for array input and a record for record input.\n */\nexport async function translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult>;\nexport async function translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const prepared = prepareTranslation(\n 'translateMany',\n options,\n config,\n defaults\n );\n return await executeTranslationBatch(\n sources,\n prepared.options,\n prepared.config\n );\n}\n\ntype RuntimeTranslationResult = RuntimeTranslationResponse[string];\n\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isGtProp(value: JsonValue | undefined): value is JsonObject & GTProp {\n if (!isJsonObject(value)) return false;\n if (value.t !== undefined && value.t !== 'p' && value.t !== 'b') return false;\n if (\n ['pl', 'ti', 'alt', 'arl', 'arb', 'ard'].some(\n (key) => value[key] !== undefined && typeof value[key] !== 'string'\n )\n ) {\n return false;\n }\n return (\n value.b === undefined ||\n (isJsonObject(value.b) && Object.values(value.b).every(isJsxChildren))\n );\n}\n\nfunction isJsxElement(\n value: JsonValue | undefined\n): value is JsonObject & JsxElement {\n if (!isJsonObject(value)) return false;\n return (\n (value.t === undefined || typeof value.t === 'string') &&\n (value.i === undefined || typeof value.i === 'number') &&\n (value.d === undefined || isGtProp(value.d)) &&\n (value.c === undefined || isJsxChildren(value.c))\n );\n}\n\nfunction isJsxChild(\n value: JsonValue | undefined\n): value is JsonValue & (string | JsxElement) {\n return typeof value === 'string' || isJsxElement(value);\n}\n\nfunction isJsxChildren(\n value: JsonValue | undefined\n): value is JsonValue & JsxChildren {\n return (\n value === null ||\n typeof value === 'boolean' ||\n isJsxChild(value) ||\n (Array.isArray(value) && value.every(isJsxChild))\n );\n}\n\n// JsonValue is wider than core's format-specific Content union, so narrow each\n// successful translation by dataFormat at the API boundary.\nfunction toTranslationResult(\n result: RuntimeTranslationResult\n): TranslationResult {\n if (!result.success) return result;\n if (result.dataFormat === 'JSX' && isJsxChildren(result.translation)) {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n if (result.dataFormat !== 'JSX' && typeof result.translation === 'string') {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n return {\n success: false,\n error: 'Invalid translation returned',\n code: 500,\n };\n}\n\n/**\n * @internal\n *\n * Translates multiple entries in a single API request for better performance.\n * This function batches multiple translation requests together and sends them\n * to the GT translation API in one call.\n *\n * @param requests - The entries to translate. Can be an array (entries are hashed and results returned in order) or a record keyed by hash (skips hash calculation, returns a record).\n * @param globalMetadata - The metadata for the translation.\n * @param config - The configuration for the translation, including transport settings such as `fetch`, `apiVersion` and `timeoutMs`.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nasync function executeTranslationBatch<\n T extends TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n>(\n requests: T,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nasync function executeTranslationBatch(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const isArray = Array.isArray(requests);\n\n // normalize and map from requests to requests record\n const hashOrder: string[] | undefined = isArray ? [] : undefined;\n const requestsObject: Record<\n string,\n { source: Content; metadata?: EntryMetadata }\n > = {};\n\n const entries: [string | undefined, TranslateManyEntry][] = isArray\n ? requests.map((r) => [undefined, r])\n : Object.entries(requests);\n\n for (const [key, request] of entries) {\n const normalized =\n typeof request === 'string' ? { source: request } : request;\n const { source, metadata } = normalized;\n const hash =\n key ??\n metadata?.hash ??\n hashSource({\n source,\n ...(metadata?.context && { context: metadata.context }),\n ...(metadata?.maxChars != null && { maxChars: metadata.maxChars }),\n ...(metadata?.fileFormat && { fileFormat: metadata.fileFormat }),\n dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n if (\n globalMetadata.modelProvider !== undefined &&\n !isModelProvider(globalMetadata.modelProvider)\n ) {\n throw new Error(\n createDiagnosticMessage({\n source: 'generaltranslation',\n severity: 'Error',\n whatHappened: 'The configured model provider is not supported',\n details: String(globalMetadata.modelProvider),\n fix: `Use one of: ${supportedModelProviders.join(', ')}`,\n })\n );\n }\n\n // Translation deliberately has no generic network/5xx/429 retries and owns\n // its timeout through fetchWithTimeout, so the SDK timer is disabled.\n const client = createApiClient({\n apiKey: config.apiKey,\n apiVersion: config.apiVersion,\n userTokenProvider: config.userTokenProvider,\n baseUrl: config.baseUrl || defaultRuntimeApiUrl,\n fetch: (input, init) =>\n fetchWithTimeout(input, init ?? {}, config.timeoutMs, config.fetch),\n projectId: config.projectId,\n retryPolicy: 'none',\n timeoutMs: false,\n });\n const body = {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: {\n ...globalMetadata,\n modelProvider: globalMetadata.modelProvider,\n },\n } satisfies TranslateData['body'];\n const result = await translateEndpoint({ body, client });\n\n // The generated client only decodes JSON errors, so non-JSON response bodies\n // must be re-read here to preserve legacy ApiError details.\n if (\n result.data === undefined &&\n result.response &&\n !hasDecodedError(result)\n ) {\n await validateResponse(result.response);\n throw result.error;\n }\n\n const runtimeResponse = unwrapApiResult(result);\n const response: Record<string, TranslationResult> = Object.fromEntries(\n Object.entries(runtimeResponse).map(([hash, translationResult]) => [\n hash,\n toTranslationResult(translationResult),\n ])\n );\n\n // If input was an array, map the record response back to an array in input order\n if (hashOrder) {\n return hashOrder.map(\n (hash) =>\n response[hash] ?? {\n success: false,\n error: 'No translation returned',\n code: 500,\n }\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AAO;EACP,MAAM;EACP,CACJ;AAIH,QAAO"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
const require_diagnostics = require("./diagnostics-DKtiPUvo.cjs");
|
|
2
2
|
const require_id = require("./id-DJ_59q21.cjs");
|
|
3
|
-
const require_ApiError = require("./ApiError-BCjEo_CM.cjs");
|
|
4
3
|
let _generaltranslation_api = require("@generaltranslation/api");
|
|
5
4
|
let _generaltranslation_format = require("@generaltranslation/format");
|
|
6
5
|
//#region src/settings/settings.ts
|
|
@@ -316,10 +315,7 @@ function hasDecodedError(result) {
|
|
|
316
315
|
*/
|
|
317
316
|
function unwrapApiResult(result) {
|
|
318
317
|
if (result.data !== void 0) return result.data;
|
|
319
|
-
if (result.response)
|
|
320
|
-
const details = isErrorResult(result.error) ? result.error.error : typeof result.error === "string" ? result.error : result.response.statusText;
|
|
321
|
-
throw new require_ApiError.ApiError(details, result.response.status, details);
|
|
322
|
-
}
|
|
318
|
+
if (result.response) throw _generaltranslation_api.ApiError.fromResponse(result.error, result.response);
|
|
323
319
|
throw result.error;
|
|
324
320
|
}
|
|
325
321
|
//#endregion
|
|
@@ -335,7 +331,7 @@ async function validateResponse(response) {
|
|
|
335
331
|
errorMsg = text || "Unknown error";
|
|
336
332
|
}
|
|
337
333
|
} catch {}
|
|
338
|
-
throw new
|
|
334
|
+
throw new _generaltranslation_api.ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
|
|
339
335
|
}
|
|
340
336
|
}
|
|
341
337
|
//#endregion
|
|
@@ -598,4 +594,4 @@ Object.defineProperty(exports, "validateAuth", {
|
|
|
598
594
|
}
|
|
599
595
|
});
|
|
600
596
|
|
|
601
|
-
//# sourceMappingURL=runtimeTranslate-
|
|
597
|
+
//# sourceMappingURL=runtimeTranslate-_gLYFBvE.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeTranslate-_gLYFBvE.cjs","names":["createDiagnosticMessage","ModelProvider","ApiError","ApiError","hashSource","createDiagnosticMessage"],"sources":["../src/settings/settings.ts","../src/settings/settingsUrls.ts","../src/logging/errors.ts","../src/logging/logger.ts","../src/adapter/modelProvider.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/unwrapApiResult.ts","../src/translate/utils/validateResponse.ts","../src/translate/runtimeTranslate.ts"],"sourcesContent":["export const libraryDefaultLocale = 'en' as const;\nexport const defaultTimeout = 60000;\n","export const defaultCacheUrl = 'https://cdn.gtx.dev' as const;\nexport const defaultBaseUrl = 'https://api.gtx.dev' as const;\nexport const defaultRuntimeApiUrl = 'https://api.gtx.dev' as const;\n","import { createDiagnosticMessage } from './diagnostics';\n\nconst GT_SOURCE = 'GT';\n\nexport const translationTimeoutError = (timeout: number) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Translation request timed out after ${timeout}ms`,\n fix: 'Try again, or increase the request timeout if the source content is large',\n });\n\nexport const translationRequestFailedError = (error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Translation request could not be completed',\n fix: 'Check your network connection and translation credentials, then try again',\n details: error,\n });\n\nexport const apiError = (status: number, statusText: string, error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `The translation API returned ${status} ${statusText}`,\n fix: 'Check the request configuration and try again',\n details: error,\n });\n\nexport const noTargetLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify targetLocale in the GT constructor`,\n });\n\nexport const noSourceLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify sourceLocale in the GT constructor`,\n });\n\nexport const noProjectIdProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified project ID`,\n fix: `Pass a project ID to \\`${functionName}\\` or specify projectId in the GT constructor`,\n });\n\nexport const noApiKeyProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified API key`,\n fix: `Pass an API key to \\`${functionName}\\` or specify apiKey in the GT constructor`,\n });\n\nexport const invalidLocaleError = (locale: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Locale \"${locale}\" is not valid`,\n fix: 'Use a valid BCP 47 locale code or add a custom mapping',\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `These locales are not valid: ${locales.join(', ')}`,\n fix: 'Use valid BCP 47 locale codes or add custom mappings',\n });\n","/**\n * Comprehensive logging system for the General Translation library.\n * Provides structured logging with multiple levels and configurable output.\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport type LogMetadataValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Date\n | Error\n | LogMetadataValue[]\n | { [key: string]: LogMetadataValue };\n\nexport type LogMetadata = Record<string, LogMetadataValue>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: Date;\n context?: string;\n metadata?: LogMetadata;\n}\n\nexport interface LoggerConfig {\n /** Minimum log level to output. */\n level: LogLevel;\n /** Whether to include timestamps in log output. */\n includeTimestamp: boolean;\n /** Whether to include context information. */\n includeContext: boolean;\n /** Custom prefix for all log messages. */\n prefix?: string;\n /** Whether to output to console (default: true) */\n enableConsole: boolean;\n /** Custom log handlers. */\n handlers?: LogHandler[];\n}\n\nexport interface LogHandler {\n handle(entry: LogEntry): void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n off: 4,\n};\n\nconst LOG_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n off: '', // No color needed since 'off' level logs are never displayed\n};\n\nconst RESET_COLOR = '\\x1b[0m';\n\n/**\n * Get the configured log level from environment variable or default to 'warn'\n */\nfunction getConfiguredLogLevel(): LogLevel {\n if (typeof process !== 'undefined' && process.env?._GT_LOG_LEVEL) {\n const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();\n if (envLevel in LOG_LEVELS) {\n return envLevel as LogLevel;\n }\n }\n return 'warn';\n}\n\n/**\n * Console log handler that outputs formatted messages to console\n */\nexport class ConsoleLogHandler implements LogHandler {\n private config: LoggerConfig;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n }\n\n handle(entry: LogEntry): void {\n const parts: string[] = [];\n\n // Add timestamp if enabled\n if (this.config.includeTimestamp) {\n parts.push(`[${entry.timestamp.toISOString()}]`);\n }\n\n // Add level with color\n const colorCode = LOG_COLORS[entry.level];\n const levelText = `[${entry.level.toUpperCase()}]`;\n parts.push(`${colorCode}${levelText}${RESET_COLOR}`);\n\n // Add prefix if configured\n if (this.config.prefix) {\n parts.push(`[${this.config.prefix}]`);\n }\n\n // Add context if available and enabled.\n if (this.config.includeContext && entry.context) {\n parts.push(`[${entry.context}]`);\n }\n\n // Add the main message\n parts.push(entry.message);\n\n // Format metadata if available.\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n parts.push(`\\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);\n }\n\n const formattedMessage = parts.join(' ');\n\n // Output to appropriate console method based on level\n switch (entry.level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(formattedMessage);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(formattedMessage);\n break;\n case 'warn':\n console.warn(formattedMessage);\n break;\n case 'error':\n console.error(formattedMessage);\n break;\n }\n }\n}\n\n/**\n * Main Logger class providing structured logging capabilities.\n */\nexport class Logger {\n private config: LoggerConfig;\n private handlers: LogHandler[];\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n enableConsole: true,\n handlers: [],\n ...config,\n };\n\n this.handlers = [...(this.config.handlers || [])];\n\n // Add console handler if enabled\n if (this.config.enableConsole) {\n this.handlers.push(new ConsoleLogHandler(this.config));\n }\n }\n\n /**\n * Add a custom log handler\n */\n addHandler(handler: LogHandler): void {\n this.handlers.push(handler);\n }\n\n /**\n * Remove a log handler\n */\n removeHandler(handler: LogHandler): void {\n const index = this.handlers.indexOf(handler);\n if (index > -1) {\n this.handlers.splice(index, 1);\n }\n }\n\n /**\n * Update logger configuration\n */\n configure(config: Partial<LoggerConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Check if a log level should be output based on current configuration\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n /**\n * Internal logging method that creates log entries and passes them to handlers\n */\n private log(\n level: LogLevel,\n message: string,\n context?: string,\n metadata?: LogMetadata\n ): void {\n if (!this.shouldLog(level)) {\n return;\n }\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n metadata,\n };\n\n // Pass to all handlers\n this.handlers.forEach((handler) => {\n try {\n handler.handle(entry);\n } catch (error) {\n // Prevent logging errors from breaking the application\n console.error('Error in log handler:', error);\n }\n });\n }\n\n /**\n * Log a debug message\n * Used for detailed diagnostic information, typically of interest only when diagnosing problems\n */\n debug(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('debug', message, context, metadata);\n }\n\n /**\n * Log an info message\n * Used for general information about application operation.\n */\n info(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('info', message, context, metadata);\n }\n\n /**\n * Log a warning message\n * Used for potentially problematic situations that don't prevent operation\n */\n warn(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('warn', message, context, metadata);\n }\n\n /**\n * Log an error message\n * Used for error events that might still allow the application to continue.\n */\n error(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('error', message, context, metadata);\n }\n\n /**\n * Create a child logger with a specific context\n */\n child(context: string): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Get current logger configuration\n */\n getConfig(): LoggerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Context logger that automatically includes context information.\n */\nexport class ContextLogger {\n private logger: Logger;\n private context: string;\n\n constructor(logger: Logger, context: string) {\n this.logger = logger;\n this.context = context;\n }\n\n debug(message: string, metadata?: LogMetadata): void {\n this.logger.debug(message, this.context, metadata);\n }\n\n info(message: string, metadata?: LogMetadata): void {\n this.logger.info(message, this.context, metadata);\n }\n\n warn(message: string, metadata?: LogMetadata): void {\n this.logger.warn(message, this.context, metadata);\n }\n\n error(message: string, metadata?: LogMetadata): void {\n this.logger.error(message, this.context, metadata);\n }\n\n child(childContext: string): ContextLogger {\n return new ContextLogger(this.logger, `${this.context}:${childContext}`);\n }\n}\n\n// Default logger instance. Pure annotations let bundlers drop the logger from\n// consumers that only import constants from the same chunk.\nexport const defaultLogger = /* @__PURE__ */ new Logger({\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n prefix: 'GT',\n});\n\n// Convenience functions using the default logger.\nexport const debug = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.debug(message, context, metadata);\n\nexport const info = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.info(message, context, metadata);\n\nexport const warn = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.warn(message, context, metadata);\n\nexport const error = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.error(message, context, metadata);\n\n// Create context-specific loggers for different parts of the system\nexport const fetchLogger = /* @__PURE__ */ defaultLogger.child('fetch');\nexport const gtInstanceLogger =\n /* @__PURE__ */ defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { ModelProvider } from '@generaltranslation/api';\n\nexport type { ModelProvider };\n\nexport const supportedModelProviders =\n /* @__PURE__ */ Object.values(ModelProvider);\n\nexport function isModelProvider(value: unknown): value is ModelProvider {\n return supportedModelProviders.includes(value as ModelProvider);\n}\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps a fetch implementation with the runtime translation timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeoutMs - The timeout in milliseconds. Omitted selects `defaultTimeout`,\n * `0` is a literal zero, and `false` disables the runtime-owned timer.\n * @param fetchImplementation - The fetch implementation to call. Defaults to global fetch.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeoutMs: number | false = defaultTimeout,\n fetchImplementation: typeof fetch = globalThis.fetch\n) {\n const controller = new AbortController();\n const signals = [controller.signal];\n if (options.signal) signals.push(options.signal);\n if (url instanceof Request) signals.push(url.signal);\n const signal = AbortSignal.any(signals);\n\n // Only a rejection with the SDK's own abort reason is a timeout. Native and\n // reason-preserving custom fetches keep distinct cancellations, even if the\n // SDK timer fires while they are cleaning up.\n let timedOut = false;\n const timeoutId =\n timeoutMs === false\n ? null\n : setTimeout(() => {\n timedOut = !signal.aborted;\n controller.abort();\n }, timeoutMs);\n\n try {\n const response = await fetchImplementation(url, { ...options, signal });\n return response;\n } catch (error) {\n if (timedOut && timeoutMs !== false && error === controller.signal.reason) {\n throw translationTimeoutError(timeoutMs);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { ApiError } from '@generaltranslation/api';\n\nexport function isErrorResult(error: unknown): error is { error: string } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'error' in error &&\n typeof error.error === 'string'\n );\n}\n\nexport function hasDecodedError(result: { error: unknown }): boolean {\n return isErrorResult(result.error) || typeof result.error === 'string';\n}\n\n/**\n * Unwraps a `@generaltranslation/api` SDK result, returning its data or\n * throwing an `ApiError` built from the failed response.\n */\nexport function unwrapApiResult<T>(result: {\n data: T | undefined;\n error: unknown;\n response?: Response;\n}): Exclude<T, undefined> {\n if (result.data !== undefined) {\n // TypeScript cannot narrow a generic T after excluding undefined; the\n // runtime guard above establishes the exact Exclude<T, undefined> result.\n return result.data as Exclude<T, undefined>;\n }\n if (result.response) {\n throw ApiError.fromResponse(result.error, result.response);\n }\n throw result.error;\n}\n","import { apiError } from '../../logging/errors';\nimport { ApiError } from '@generaltranslation/api';\n\nexport async function validateResponse(response: Response) {\n if (!response.ok) {\n let errorMsg = 'Unknown error';\n try {\n const text = await response.text();\n try {\n const errorJson = JSON.parse(text) as { error: string };\n errorMsg = errorJson.error;\n } catch {\n errorMsg = text || 'Unknown error';\n }\n } catch {\n // response.text() failed, keep 'Unknown error'\n }\n const errorMessage = apiError(\n response.status,\n response.statusText,\n errorMsg\n );\n const error = new ApiError(errorMessage, response.status, errorMsg);\n throw error;\n }\n}\n","import {\n createApiClient,\n translate as translateEndpoint,\n type JsonObject,\n type JsonValue,\n type RuntimeTranslationResponse,\n type TranslateData,\n} from '@generaltranslation/api';\nimport {\n resolveCanonicalLocale,\n standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n Content,\n GTProp,\n JsxChildren,\n JsxElement,\n} from '@generaltranslation/format/types';\nimport type {\n TranslateConfig,\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n} from '../types';\nimport type {\n EntryMetadata,\n TranslateManyEntry,\n TranslateOptions,\n} from '../types-dir/api/entry';\nimport { libraryDefaultLocale } from '../settings/settings';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n noApiKeyProvidedError,\n noProjectIdProvidedError,\n noTargetLocaleProvidedError,\n} from '../logging/errors';\nimport { gtInstanceLogger } from '../logging/logger';\nimport { createDiagnosticMessage } from '../logging/diagnostics';\nimport { hashSource } from '../id';\nimport {\n isModelProvider,\n supportedModelProviders,\n} from '../adapter/modelProvider';\nimport { fetchWithTimeout } from './utils/fetchWithTimeout';\nimport { hasDecodedError, unwrapApiResult } from './utils/unwrapApiResult';\nimport { validateResponse } from './utils/validateResponse';\n\ntype TranslateFunctionName = 'translate' | 'translateMany';\ntype TranslateDefaults = Partial<\n Pick<TranslateOptions, 'sourceLocale' | 'targetLocale'>\n>;\n\n/**\n * @internal\n * Credential/provider errors are reported before the project error, and both\n * before any locale validation. GT/GTRuntime share this ordering.\n */\nexport function validateAuth<\n T extends Pick<TranslateConfig, 'apiKey' | 'userTokenProvider' | 'projectId'>,\n>(\n functionName: string,\n config: T\n): asserts config is T & { projectId: string } {\n const errors: string[] = [];\n if (!config.apiKey && !config.userTokenProvider) {\n errors.push(noApiKeyProvidedError(functionName));\n }\n if (!config.projectId) {\n errors.push(noProjectIdProvidedError(functionName));\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n}\n\n/**\n * @internal\n *\n * Shared preparation for every translation surface (classes and the tooling\n * facade): normalize the string shorthand, validate auth, require a target\n * locale, default the source locale and canonicalize both for the wire.\n *\n * @param defaults - Instance defaults supplied by GT/GTRuntime. Facade calls pass none.\n */\nfunction prepareTranslation(\n functionName: TranslateFunctionName,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults: TranslateDefaults = {}\n): {\n options: TranslateOptions & { sourceLocale: string };\n config: TranslationRequestConfig;\n} {\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n validateAuth(functionName, config);\n\n const targetLocale = options?.targetLocale || defaults.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError(functionName);\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n const { customMapping, ...requestConfig } = config;\n // Mapping resolves aliases; standardization also canonicalizes configured\n // spellings such as en-us before they cross the service boundary.\n const resolveServiceLocale = (locale: string) =>\n standardizeLocale(resolveCanonicalLocale(locale, customMapping));\n\n return {\n options: {\n ...options,\n targetLocale: resolveServiceLocale(targetLocale),\n sourceLocale: resolveServiceLocale(\n options?.sourceLocale || defaults.sourceLocale || libraryDefaultLocale\n ),\n },\n config: requestConfig,\n };\n}\n\n/**\n * @internal\n * Translates a single entry with explicit configuration and optional locale defaults.\n */\nexport async function translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslationResult | TranslationError> {\n const prepared = prepareTranslation('translate', options, config, defaults);\n const results = await executeTranslationBatch(\n [source],\n prepared.options,\n prepared.config\n );\n return results[0];\n}\n\n/**\n * @internal\n * Translates multiple entries in one request with explicit configuration.\n * Returns an array for array input and a record for record input.\n */\nexport async function translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult>;\nexport async function translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const prepared = prepareTranslation(\n 'translateMany',\n options,\n config,\n defaults\n );\n return await executeTranslationBatch(\n sources,\n prepared.options,\n prepared.config\n );\n}\n\ntype RuntimeTranslationResult = RuntimeTranslationResponse[string];\n\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isGtProp(value: JsonValue | undefined): value is JsonObject & GTProp {\n if (!isJsonObject(value)) return false;\n if (value.t !== undefined && value.t !== 'p' && value.t !== 'b') return false;\n if (\n ['pl', 'ti', 'alt', 'arl', 'arb', 'ard'].some(\n (key) => value[key] !== undefined && typeof value[key] !== 'string'\n )\n ) {\n return false;\n }\n return (\n value.b === undefined ||\n (isJsonObject(value.b) && Object.values(value.b).every(isJsxChildren))\n );\n}\n\nfunction isJsxElement(\n value: JsonValue | undefined\n): value is JsonObject & JsxElement {\n if (!isJsonObject(value)) return false;\n return (\n (value.t === undefined || typeof value.t === 'string') &&\n (value.i === undefined || typeof value.i === 'number') &&\n (value.d === undefined || isGtProp(value.d)) &&\n (value.c === undefined || isJsxChildren(value.c))\n );\n}\n\nfunction isJsxChild(\n value: JsonValue | undefined\n): value is JsonValue & (string | JsxElement) {\n return typeof value === 'string' || isJsxElement(value);\n}\n\nfunction isJsxChildren(\n value: JsonValue | undefined\n): value is JsonValue & JsxChildren {\n return (\n value === null ||\n typeof value === 'boolean' ||\n isJsxChild(value) ||\n (Array.isArray(value) && value.every(isJsxChild))\n );\n}\n\n// JsonValue is wider than core's format-specific Content union, so narrow each\n// successful translation by dataFormat at the API boundary.\nfunction toTranslationResult(\n result: RuntimeTranslationResult\n): TranslationResult {\n if (!result.success) return result;\n if (result.dataFormat === 'JSX' && isJsxChildren(result.translation)) {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n if (result.dataFormat !== 'JSX' && typeof result.translation === 'string') {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n return {\n success: false,\n error: 'Invalid translation returned',\n code: 500,\n };\n}\n\n/**\n * @internal\n *\n * Translates multiple entries in a single API request for better performance.\n * This function batches multiple translation requests together and sends them\n * to the GT translation API in one call.\n *\n * @param requests - The entries to translate. Can be an array (entries are hashed and results returned in order) or a record keyed by hash (skips hash calculation, returns a record).\n * @param globalMetadata - The metadata for the translation.\n * @param config - The configuration for the translation, including transport settings such as `fetch`, `apiVersion` and `timeoutMs`.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nasync function executeTranslationBatch<\n T extends TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n>(\n requests: T,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nasync function executeTranslationBatch(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const isArray = Array.isArray(requests);\n\n // normalize and map from requests to requests record\n const hashOrder: string[] | undefined = isArray ? [] : undefined;\n const requestsObject: Record<\n string,\n { source: Content; metadata?: EntryMetadata }\n > = {};\n\n const entries: [string | undefined, TranslateManyEntry][] = isArray\n ? requests.map((r) => [undefined, r])\n : Object.entries(requests);\n\n for (const [key, request] of entries) {\n const normalized =\n typeof request === 'string' ? { source: request } : request;\n const { source, metadata } = normalized;\n const hash =\n key ??\n metadata?.hash ??\n hashSource({\n source,\n ...(metadata?.context && { context: metadata.context }),\n ...(metadata?.maxChars != null && { maxChars: metadata.maxChars }),\n ...(metadata?.fileFormat && { fileFormat: metadata.fileFormat }),\n dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n if (\n globalMetadata.modelProvider !== undefined &&\n !isModelProvider(globalMetadata.modelProvider)\n ) {\n throw new Error(\n createDiagnosticMessage({\n source: 'generaltranslation',\n severity: 'Error',\n whatHappened: 'The configured model provider is not supported',\n details: String(globalMetadata.modelProvider),\n fix: `Use one of: ${supportedModelProviders.join(', ')}`,\n })\n );\n }\n\n // Translation deliberately has no generic network/5xx/429 retries and owns\n // its timeout through fetchWithTimeout, so the SDK timer is disabled.\n const client = createApiClient({\n apiKey: config.apiKey,\n apiVersion: config.apiVersion,\n userTokenProvider: config.userTokenProvider,\n baseUrl: config.baseUrl || defaultRuntimeApiUrl,\n fetch: (input, init) =>\n fetchWithTimeout(input, init ?? {}, config.timeoutMs, config.fetch),\n projectId: config.projectId,\n retryPolicy: 'none',\n timeoutMs: false,\n });\n const body = {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: {\n ...globalMetadata,\n modelProvider: globalMetadata.modelProvider,\n },\n } satisfies TranslateData['body'];\n const result = await translateEndpoint({ body, client });\n\n // The generated client only decodes JSON errors, so non-JSON response bodies\n // must be re-read here to preserve legacy ApiError details.\n if (\n result.data === undefined &&\n result.response &&\n !hasDecodedError(result)\n ) {\n await validateResponse(result.response);\n throw result.error;\n }\n\n const runtimeResponse = unwrapApiResult(result);\n const response: Record<string, TranslationResult> = Object.fromEntries(\n Object.entries(runtimeResponse).map(([hash, translationResult]) => [\n hash,\n toTranslationResult(translationResult),\n ])\n );\n\n // If input was an array, map the record response back to an array in input order\n if (hashOrder) {\n return hashOrder.map(\n (hash) =>\n response[hash] ?? {\n success: false,\n error: 'No translation returned',\n code: 500,\n }\n );\n }\n\n // If input was a record, return the record response directly\n return response;\n}\n"],"mappings":";;;;;AAAA,MAAa,uBAAuB;AACpC,MAAa,iBAAiB;;;ACD9B,MAAa,kBAAkB;AAC/B,MAAa,iBAAiB;AAC9B,MAAa,uBAAuB;;;ACApC,MAAM,YAAY;AAElB,MAAa,2BAA2B,YACtCA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,uCAAuC,QAAQ;CAC7D,KAAK;CACN,CAAC;AAWJ,MAAa,YAAY,QAAgB,YAAoB,UAC3DA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,gCAAgC,OAAO,GAAG;CACxD,KAAK;CACL,SAAS;CACV,CAAC;AAEJ,MAAa,+BAA+B,iBAC1CA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR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,cAAc;EACd,SAAS,OAAO,eAAe,cAAc;EAC7C,KAAK,eAAe,wBAAwB,KAAK,KAAK;EACvD,CAAC,CACH;CAKH,MAAM,UAAA,GAAA,wBAAA,iBAAyB;EAC7B,QAAQ,OAAO;EACf,YAAY,OAAO;EACnB,mBAAmB,OAAO;EAC1B,SAAS,OAAO,WAAA;EAChB,QAAQ,OAAO,SACb,iBAAiB,OAAO,QAAQ,EAAE,EAAE,OAAO,WAAW,OAAO,MAAM;EACrE,WAAW,OAAO;EAClB,aAAa;EACb,WAAW;EACZ,CAAC;CAUF,MAAM,SAAS,OAAA,GAAA,wBAAA,WAAwB;EAAE,MAAA;GARvC,UAAU;GACV,cAAc,eAAe;GAC7B,cAAc,eAAe;GAC7B,UAAU;IACR,GAAG;IACH,eAAe,eAAe;IAC/B;GAE0C;EAAE;EAAQ,CAAC;AAIxD,KACE,OAAO,SAAS,KAAA,KAChB,OAAO,YACP,CAAC,gBAAgB,OAAO,EACxB;AACA,QAAM,iBAAiB,OAAO,SAAS;AACvC,QAAM,OAAO;;CAGf,MAAM,kBAAkB,gBAAgB,OAAO;CAC/C,MAAM,WAA8C,OAAO,YACzD,OAAO,QAAQ,gBAAgB,CAAC,KAAK,CAAC,MAAM,uBAAuB,CACjE,MACA,oBAAoB,kBAAkB,CACvC,CAAC,CACH;AAGD,KAAI,UACF,QAAO,UAAU,KACd,SACC,SAAS,SAAS;EAChB,SAAS;EACT,OAAO;EACP,MAAM;EACP,CACJ;AAIH,QAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ApiError } from '
|
|
1
|
+
import { ApiError } from '@generaltranslation/api';
|
|
2
2
|
export function isErrorResult(error) {
|
|
3
3
|
return (typeof error === 'object' &&
|
|
4
4
|
error !== null &&
|
|
@@ -19,12 +19,7 @@ export function unwrapApiResult(result) {
|
|
|
19
19
|
return result.data;
|
|
20
20
|
}
|
|
21
21
|
if (result.response) {
|
|
22
|
-
|
|
23
|
-
? result.error.error
|
|
24
|
-
: typeof result.error === 'string'
|
|
25
|
-
? result.error
|
|
26
|
-
: result.response.statusText;
|
|
27
|
-
throw new ApiError(details, result.response.status, details);
|
|
22
|
+
throw ApiError.fromResponse(result.error, result.response);
|
|
28
23
|
}
|
|
29
24
|
throw result.error;
|
|
30
25
|
}
|
|
@@ -35,7 +35,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
37
|
import { apiError } from '../../logging/errors';
|
|
38
|
-
import { ApiError } from '
|
|
38
|
+
import { ApiError } from '@generaltranslation/api';
|
|
39
39
|
export function validateResponse(response) {
|
|
40
40
|
return __awaiter(this, void 0, void 0, function () {
|
|
41
41
|
var errorMsg, text, errorJson, _a, errorMessage, error;
|
|
@@ -529,4 +529,4 @@ type TranslateConfig = Omit<TranslationRequestConfig, 'projectId'> & {
|
|
|
529
529
|
};
|
|
530
530
|
//#endregion
|
|
531
531
|
export { DownloadFileOptions as $, InjectionType as A, GTParsingFlags as At, JobStatus as B, StringContent as C, FileQueryResult as Ct, TranslationRequestConfig as D, GTConfig as Dt, TranslateConfig as E, JsonValue as Et, SubmitUserEditDiffsPayload as F, TranslateManyEntry as Ft, FileDataQuery as G, MoveResult as H, AwaitJobsOptions$1 as I, TranslateOptions as It, BranchDataResult as J, FileDataResult as K, AwaitJobsResult as L, TransformationPrefix as M, ActionType as Mt, VariableTransformationSuffix as N, EntryMetadata as Nt, Variable as O, GTFilesConfig as Ot, SubmitUserEditDiff as P, RuntimeTranslateManyOptions as Pt, TranslationResultReference as Q, JobResult as R, RuntimeFileFormat$1 as S, FileQuery as St, StringMessage$1 as T, JsonPrimitive as Tt, ProcessMovesOptions as U, MoveMapping as V, ProcessMovesResponse as W, TranslationError as X, TranslateManyResult as Y, TranslationResult as Z, JsxChildren$1 as _, FileToUpload as _t, CustomRegionMapping$1 as a, SetupProjectFileReference as at, Metadata as b, Updates as bt, FormatVariables$1 as c, EnqueueFilesOptions as ct, HTML_CONTENT_PROPS as d, DownloadFileBatchResult as dt, PublishFileEntry as et, HtmlContentPropKeysRecord as f, DownloadedFile as ft, JsxChild as g, FileReferenceIds as gt, IcuMessage$1 as h, FileReference as ht, CustomMapping$1 as i, UploadFilesResponse as it, Transformation as j, HashMetadata as jt, VariableType as k, GTOutputFileConfig as kt, GTProp as l, DownloadFileBatchOptions as lt, I18nextMessage$1 as m, FileFormat as mt, CreateTagOptions as n, FileUpload as nt, CutoffFormatOptions$1 as o, SetupProjectOptions as ot, HtmlContentPropValuesRecord as p, BINARY_FILE_FORMATS as pt, BranchQuery as q, CreateTagResult as r, UploadFilesOptions as rt, DataFormat$1 as s, SetupProjectResult as st, Content as t, PublishFilesResult as tt, GetOrphanedFilesResult as u, DownloadFileBatchRequest as ut, JsxElement as v, isBinaryFileFormat as vt, StringFormat$1 as w, JsonObject as wt, OrphanedFile as x, CheckFileTranslationsOptions as xt, LocaleProperties$1 as y, EnqueueFilesResult as yt, CheckJobStatusResult as z };
|
|
532
|
-
//# sourceMappingURL=types-
|
|
532
|
+
//# sourceMappingURL=types-CEsh60Yt.d.mts.map
|
package/dist/types.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_file = require("./file-
|
|
2
|
+
const require_file = require("./file-DNWSAhTC.cjs");
|
|
3
3
|
let _generaltranslation_format_types = require("@generaltranslation/format/types");
|
|
4
4
|
exports.BINARY_FILE_FORMATS = require_file.BINARY_FILE_FORMATS;
|
|
5
5
|
Object.defineProperty(exports, "HTML_CONTENT_PROPS", {
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-
|
|
1
|
+
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-CEsh60Yt.mjs";
|
|
2
2
|
export { AwaitJobsOptions, AwaitJobsResult, BINARY_FILE_FORMATS, BranchDataResult, BranchQuery, CheckFileTranslationsOptions, CheckJobStatusResult, Content, CreateTagOptions, CreateTagResult, CustomMapping, CustomRegionMapping, CutoffFormatOptions, DataFormat, DownloadFileBatchOptions, DownloadFileBatchResult, DownloadFileOptions, DownloadedFile, EnqueueFilesOptions, EnqueueFilesResult, ActionType as EntryActionType, EntryMetadata, FileDataQuery, FileDataResult, FileFormat, FileReference, FileToUpload, FileUpload, FormatVariables, GTConfig, GTFilesConfig, GTOutputFileConfig, GTParsingFlags, GTProp, GetOrphanedFilesResult, HTML_CONTENT_PROPS, HashMetadata, HtmlContentPropKeysRecord, HtmlContentPropValuesRecord, I18nextMessage, IcuMessage, InjectionType, JobResult, JobStatus, JsonObject, JsonPrimitive, JsonValue, JsxChild, JsxChildren, JsxElement, LocaleProperties, Metadata, MoveMapping, MoveResult, OrphanedFile, ProcessMovesOptions, ProcessMovesResponse, PublishFileEntry, PublishFilesResult, RuntimeFileFormat, SetupProjectFileReference, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateConfig, TranslateManyEntry, TranslateManyResult, TranslateOptions, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType, isBinaryFileFormat };
|
package/dist/types.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as isBinaryFileFormat, t as BINARY_FILE_FORMATS } from "./file-
|
|
1
|
+
import { n as isBinaryFileFormat, t as BINARY_FILE_FORMATS } from "./file-BZmC4OTj.mjs";
|
|
2
2
|
import { HTML_CONTENT_PROPS } from "@generaltranslation/format/types";
|
|
3
3
|
export { BINARY_FILE_FORMATS, HTML_CONTENT_PROPS, isBinaryFileFormat };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "generaltranslation",
|
|
3
|
-
"version": "9.5.
|
|
3
|
+
"version": "9.5.2",
|
|
4
4
|
"description": "A language toolkit for AI developers",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@noble/hashes": "^2.2.0",
|
|
43
|
-
"@generaltranslation/api": "0.
|
|
43
|
+
"@generaltranslation/api": "0.5.0",
|
|
44
44
|
"@generaltranslation/icu": "0.1.2",
|
|
45
45
|
"@generaltranslation/format": "0.1.9"
|
|
46
46
|
},
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
//#region src/errors/ApiError.ts
|
|
2
|
-
var ApiError = class extends Error {
|
|
3
|
-
constructor(error, code, message) {
|
|
4
|
-
super(error);
|
|
5
|
-
this.name = "ApiError";
|
|
6
|
-
this.code = code;
|
|
7
|
-
this.message = message;
|
|
8
|
-
}
|
|
9
|
-
};
|
|
10
|
-
//#endregion
|
|
11
|
-
Object.defineProperty(exports, "ApiError", {
|
|
12
|
-
enumerable: true,
|
|
13
|
-
get: function() {
|
|
14
|
-
return ApiError;
|
|
15
|
-
}
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
//# sourceMappingURL=ApiError-BCjEo_CM.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ApiError-BCjEo_CM.cjs","names":[],"sources":["../src/errors/ApiError.ts"],"sourcesContent":["export class ApiError extends Error {\n public code: number;\n public message: string;\n\n constructor(error: string, code: number, message: string) {\n super(error);\n this.name = 'ApiError';\n this.code = code;\n this.message = message;\n }\n}\n"],"mappings":";AAAA,IAAa,WAAb,cAA8B,MAAM;CAIlC,YAAY,OAAe,MAAc,SAAiB;AACxD,QAAM,MAAM;AACZ,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,UAAU"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
//#region src/errors/ApiError.ts
|
|
2
|
-
var ApiError = class extends Error {
|
|
3
|
-
constructor(error, code, message) {
|
|
4
|
-
super(error);
|
|
5
|
-
this.name = "ApiError";
|
|
6
|
-
this.code = code;
|
|
7
|
-
this.message = message;
|
|
8
|
-
}
|
|
9
|
-
};
|
|
10
|
-
//#endregion
|
|
11
|
-
export { ApiError as t };
|
|
12
|
-
|
|
13
|
-
//# sourceMappingURL=ApiError-DxWKM0Xt.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ApiError-DxWKM0Xt.mjs","names":[],"sources":["../src/errors/ApiError.ts"],"sourcesContent":["export class ApiError extends Error {\n public code: number;\n public message: string;\n\n constructor(error: string, code: number, message: string) {\n super(error);\n this.name = 'ApiError';\n this.code = code;\n this.message = message;\n }\n}\n"],"mappings":";AAAA,IAAa,WAAb,cAA8B,MAAM;CAIlC,YAAY,OAAe,MAAc,SAAiB;AACxD,QAAM,MAAM;AACZ,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,UAAU"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"derive-Cv5_y8Tf.mjs","names":["translateWithConfig","translateMany","translateManyWithConfig"],"sources":["../src/utils/base64.ts","../src/utils/isSupportedFileFormatTransform.ts","../src/translate/utils/validateFileFormatTransform.ts","../src/adapter/createGtApi.ts","../src/derive/utils/traverseIcu.ts","../src/derive/utils/constants.ts","../src/derive/utils/regex.ts","../src/derive/utils/traverseHelpers.ts","../src/derive/decodeVars.ts","../src/derive/utils/sanitizeVar.ts","../src/derive/declareVar.ts","../src/derive/derive.ts"],"sourcesContent":["import { isBinaryFileFormat, type FileFormat } from '../types-dir/api/file';\n\n// Encode a string to base64\nexport function encode(data: string): string {\n if (typeof Buffer !== 'undefined') {\n // Node.js path.\n return Buffer.from(data, 'utf8').toString('base64');\n }\n // Browser path.\n const bytes = new TextEncoder().encode(data);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n// Decode a base64 string to a string\nexport function decode(base64: string): string {\n if (typeof Buffer !== 'undefined') {\n // Node.js path.\n return Buffer.from(base64, 'base64').toString('utf8');\n }\n // Browser path.\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n\nexport function encodeFileContent(\n content: string,\n fileFormat: FileFormat\n): string {\n return isBinaryFileFormat(fileFormat) ? content : encode(content);\n}\n\nexport function decodeFileContent(\n content: string,\n fileFormat: FileFormat\n): string {\n return isBinaryFileFormat(fileFormat) ? content : decode(content);\n}\n","import type { FileFormat } from '../types-dir/api/file';\n\nconst SUPPORTED_TRANSFORMATIONS = {\n GTJSON: ['GTJSON'],\n JSON: ['JSON'],\n PO: ['PO'],\n // POT templates can produce translated PO catalog files.\n POT: ['POT', 'PO'],\n YAML: ['YAML'],\n MDX: ['MDX'],\n MD: ['MD'],\n TS: ['TS'],\n JS: ['JS'],\n HTML: ['HTML'],\n TXT: ['TXT'],\n TWILIO_CONTENT_JSON: ['TWILIO_CONTENT_JSON'],\n LOTTIE: ['LOTTIE'],\n SVG: ['SVG'],\n DOT_STRINGS: ['DOT_STRINGS'],\n DOT_STRINGSDICT: ['DOT_STRINGSDICT'],\n ANDROID_STRINGS: ['ANDROID_STRINGS'],\n XCSTRINGS: ['XCSTRINGS'],\n} as const satisfies Record<FileFormat, FileFormat[]>;\n\n/**\n * This function checks if a file format transformation is supported during translation\n * @param from - The source file format.\n * @param to - The target file format.\n * @returns True if the transformation is supported, false otherwise\n */\nexport function isSupportedFileFormatTransform(\n from: FileFormat,\n to: FileFormat\n): boolean {\n const toFormats: FileFormat[] | undefined = SUPPORTED_TRANSFORMATIONS[from];\n return toFormats?.includes(to) ?? false;\n}\n","import type { FileFormat } from '../../types-dir/api/file';\nimport { isSupportedFileFormatTransform } from '../../utils/isSupportedFileFormatTransform';\n\nexport type FileFormatTransformInput = {\n fileFormat?: FileFormat;\n transformFormat?: FileFormat;\n fileName?: string;\n fileId?: string;\n};\n\n/**\n * Returns a user-facing validation error when a requested file format transform\n * is missing source format context or is not currently supported.\n */\nexport function getFileFormatTransformError(\n file: FileFormatTransformInput\n): string | undefined {\n if (!file.transformFormat) return undefined;\n const fileLabel = file.fileName ?? file.fileId ?? 'unknown file';\n if (!file.fileFormat) {\n return `fileFormat is required when transformFormat is provided for ${fileLabel}`;\n }\n if (!isSupportedFileFormatTransform(file.fileFormat, file.transformFormat)) {\n return `Unsupported file format transform: ${file.fileFormat} -> ${file.transformFormat}`;\n }\n return undefined;\n}\n\n/**\n * Validates file format transforms before sending upload/enqueue requests.\n */\nexport function validateFileFormatTransforms(\n files: FileFormatTransformInput[]\n): void {\n for (const file of files) {\n const error = getFileFormatTransformError(file);\n if (error) throw new Error(error);\n }\n}\n","import {\n createApiClient,\n createBranch,\n createProject,\n createProjectApiKey,\n createTag,\n DEFAULT_BATCH_SIZE,\n downloadFiles,\n enqueueFileTranslations,\n generateProjectContext,\n getBranchInfo,\n getFileInfo,\n getOrphanedFiles,\n getProjectInfo,\n getTranslationJobInfo,\n getTranslationStatus,\n listOrgs,\n listProjects,\n pollJobs,\n processBatches,\n processFileMoves,\n publishFiles,\n submitUserEditDiffs,\n uploadAssets,\n uploadSourceFiles,\n uploadTranslations,\n type ApiClientConfig,\n type AwaitJobsOptions,\n type CreateBranchData,\n type CreateProjectApiKeyData,\n type CreateProjectData,\n type CreateTagData,\n type DownloadFilesData,\n type EnqueueFileTranslationsData,\n type GenerateProjectContextData,\n type GetBranchInfoData,\n type GetFileInfoData,\n type GetTranslationJobInfoResponse,\n type GetTranslationStatusData,\n type ProcessFileMovesData,\n type PublishFilesData,\n type SubmitUserEditDiffsData,\n type UploadAssetsData,\n type UploadSourceFilesData,\n type UploadTranslationsData,\n} from '@generaltranslation/api';\nimport {\n resolveAliasLocale,\n resolveCanonicalLocale,\n standardizeLocale,\n} from '@generaltranslation/format';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { DownloadedFile } from '../types-dir/api/downloadFileBatch';\nimport type {\n TranslateManyEntry,\n TranslateOptions,\n} from '../types-dir/api/entry';\nimport type { TranslateManyResult, TranslationResult } from '../types';\nimport { createDiagnosticMessage } from '../logging/diagnostics';\nimport {\n translate as translateWithConfig,\n translateMany as translateManyWithConfig,\n} from '../translate/runtimeTranslate';\nimport { decodeFileContent, encodeFileContent } from '../utils/base64';\nimport { unwrapApiResult } from '../translate/utils/unwrapApiResult';\nimport { validateFileFormatTransforms } from '../translate/utils/validateFileFormatTransform';\nimport { isModelProvider, supportedModelProviders } from './modelProvider';\n\n// Follows nextCursor until the service reports the last page.\nasync function collectPages<T>(\n loadPage: (\n cursor: string | undefined\n ) => Promise<{ items: T[]; nextCursor: string | null }>\n): Promise<T[]> {\n const items: T[] = [];\n let cursor: string | undefined;\n do {\n const page = await loadPage(cursor);\n items.push(...page.items);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return items;\n}\n\nfunction normalizeJobStatus(job: GetTranslationJobInfoResponse[number]): {\n jobId: string;\n status: GetTranslationJobInfoResponse[number]['status'];\n error?: { message: string };\n} {\n return {\n jobId: job.jobId,\n status: job.status,\n ...(job.status === 'failed'\n ? { error: { message: job.error.message ?? '' } }\n : {}),\n };\n}\n\nexport type GtApiAdapterConfig = ApiClientConfig & {\n customMapping?: CustomMapping;\n};\n\nexport function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig) {\n let client: ReturnType<typeof createApiClient> | undefined;\n let config: GtApiAdapterConfig | undefined;\n\n // Mapping resolves aliases; standardization also canonicalizes configured\n // spellings such as en-us before they cross the service boundary.\n function resolveServiceLocale(locale: string): string {\n return standardizeLocale(\n resolveCanonicalLocale(locale, config?.customMapping)\n );\n }\n\n // Upload responses echo the canonical locale; callers key lockfile entries\n // by the configured alias, so map it back before it leaves the adapter.\n function aliasUploadedFileLocale<T extends { locale?: string }>(file: T): T {\n return file.locale\n ? {\n ...file,\n locale: resolveAliasLocale(file.locale, config?.customMapping),\n }\n : file;\n }\n\n function getConfig(): GtApiAdapterConfig {\n if (!config) {\n throw new Error(\n 'API client not configured — call configureApiClient first'\n );\n }\n return config;\n }\n\n function getClient(timeoutMs?: number): ReturnType<typeof createApiClient> {\n if (timeoutMs === undefined && client) return client;\n return createApiClient({ ...getConfig(), timeoutMs });\n }\n\n function configure(nextConfig: GtApiAdapterConfig): void {\n client = createApiClient(nextConfig);\n config = { ...nextConfig };\n }\n\n async function translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n timeoutMs?: number | false\n ) {\n return translateWithConfig(source, options, {\n ...getConfig(),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n }\n\n function translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n timeoutMs?: number | false\n ): Promise<TranslateManyResult>;\n function translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeoutMs?: number | false\n ): Promise<Record<string, TranslationResult>>;\n async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeoutMs?: number | false\n ): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n return translateManyWithConfig(sources, options, {\n ...getConfig(),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n }\n\n if (defaultConfig) configure(defaultConfig);\n\n // Raw service responses; the normalized adapter methods build on these and\n // compatibility facades (CLI) expose them unchanged.\n async function loadJobStatuses(\n jobIds: readonly string[],\n options: { signal?: AbortSignal; timeoutMs?: number } = {}\n ): Promise<GetTranslationJobInfoResponse> {\n return unwrapApiResult(\n await getTranslationJobInfo({\n body: { jobIds: [...jobIds] },\n client: getClient(options.timeoutMs),\n signal: options.signal,\n })\n );\n }\n\n async function loadProjectInfo(projectId?: string, timeoutMs?: number) {\n const resolvedProjectId = projectId ?? getConfig().projectId;\n if (!resolvedProjectId) {\n throw new Error('Project ID is required to fetch project information');\n }\n return unwrapApiResult(\n await getProjectInfo({\n client: getClient(timeoutMs),\n path: { projectId: resolvedProjectId },\n })\n );\n }\n\n return {\n configure,\n getClient,\n\n resolveAliasLocale(locale: string) {\n return resolveAliasLocale(locale, config?.customMapping);\n },\n\n resolveCanonicalLocale(locale: string) {\n return resolveServiceLocale(locale);\n },\n\n translate,\n translateMany,\n\n async queryBranchData(body: GetBranchInfoData['body']) {\n return unwrapApiResult(\n await getBranchInfo({ body, client: getClient() })\n );\n },\n\n async createBranch(body: CreateBranchData['body']) {\n return unwrapApiResult(await createBranch({ body, client: getClient() }));\n },\n\n async processFileMoves(\n moves: ProcessFileMovesData['body']['moves'],\n options: Pick<ProcessFileMovesData['body'], 'branchId'> & {\n timeout?: number;\n } = {}\n ) {\n const results = await processBatches(moves, async (batch) => {\n const response = unwrapApiResult(\n await processFileMoves({\n body: { branchId: options.branchId, moves: batch },\n client: getClient(options.timeout),\n })\n );\n return response.results;\n });\n const succeeded = results.filter(({ success }) => success).length;\n return {\n results,\n summary: {\n total: moves.length,\n succeeded,\n failed: results.length - succeeded,\n },\n };\n },\n\n async getOrphanedFiles(\n branchId: string,\n fileIds: string[],\n options: { timeout?: number } = {}\n ) {\n const request = async (batch: string[]) =>\n unwrapApiResult(\n await getOrphanedFiles({\n body: { branchId, fileIds: batch },\n client: getClient(options.timeout),\n })\n );\n\n if (fileIds.length === 0) return request([]);\n\n const results = await processBatches(fileIds, async (batch) => [\n await request(batch),\n ]);\n const orphanedFiles = new Map(\n results[0].orphanedFiles.map((file) => [file.fileId, file])\n );\n for (const result of results.slice(1)) {\n const batchFileIds = new Set(\n result.orphanedFiles.map((file) => file.fileId)\n );\n for (const fileId of Array.from(orphanedFiles.keys())) {\n if (!batchFileIds.has(fileId)) orphanedFiles.delete(fileId);\n }\n }\n return { orphanedFiles: Array.from(orphanedFiles.values()) };\n },\n\n async setupProject(\n files: GenerateProjectContextData['body']['files'],\n options: Omit<GenerateProjectContextData['body'], 'files'> & {\n timeoutMs?: number;\n } = {}\n ) {\n return unwrapApiResult(\n await generateProjectContext({\n body: {\n files: files.map(({ branchId, fileId, versionId }) => ({\n branchId,\n fileId,\n versionId,\n })),\n locales: options.locales?.map((locale) =>\n resolveServiceLocale(locale)\n ),\n force: options.force,\n },\n client: getClient(options.timeoutMs),\n })\n );\n },\n\n loadJobStatuses,\n\n async checkJobStatus(jobIds: string[], timeoutMs?: number) {\n const statuses = await loadJobStatuses(jobIds, { timeoutMs });\n return statuses.map(normalizeJobStatus);\n },\n\n async awaitJobs(jobIds: readonly string[], options?: AwaitJobsOptions) {\n const result = await pollJobs(\n jobIds,\n (pendingJobIds, signal) => loadJobStatuses(pendingJobIds, { signal }),\n options\n );\n return {\n ...result,\n jobs: result.jobs.map(normalizeJobStatus),\n };\n },\n\n async enqueueFiles(\n files: EnqueueFileTranslationsData['body']['files'],\n options: {\n sourceLocale?: string;\n targetLocales: string[];\n modelProvider?: string;\n force?: boolean;\n timeout?: number;\n }\n ) {\n validateFileFormatTransforms(files);\n const modelProvider = options.modelProvider;\n if (modelProvider !== undefined && !isModelProvider(modelProvider)) {\n throw new Error(\n createDiagnosticMessage({\n source: 'generaltranslation',\n severity: 'Error',\n whatHappened: `Unsupported model provider \\`${modelProvider}\\``,\n fix: `Use one of: ${supportedModelProviders.join(', ')}`,\n })\n );\n }\n const targetLocales = options.targetLocales.map((locale) =>\n resolveServiceLocale(locale)\n );\n const result = await processBatches(files, async (batch) => {\n const response = unwrapApiResult(\n await enqueueFileTranslations({\n body: {\n files: batch.map(\n ({\n branchId,\n fileId,\n versionId,\n fileName,\n transformFormat,\n }) => ({\n branchId,\n fileId,\n versionId,\n fileName,\n transformFormat,\n })\n ),\n targetLocales,\n sourceLocale: options.sourceLocale\n ? resolveServiceLocale(options.sourceLocale)\n : undefined,\n modelProvider,\n force: options.force,\n },\n client: getClient(options.timeout),\n })\n );\n const jobData =\n 'jobData' in response ? response.jobData : response.data;\n return Object.entries(jobData);\n });\n\n return {\n jobData: Object.fromEntries(result),\n locales: targetLocales,\n message: `Successfully enqueued ${result.length} file translation jobs in ${Math.ceil(files.length / DEFAULT_BATCH_SIZE)} batch(es)`,\n };\n },\n\n async createTag(body: CreateTagData['body']) {\n return unwrapApiResult(await createTag({ body, client: getClient() }));\n },\n\n async publishFiles(files: PublishFilesData['body']['files']) {\n // Compatibility callers pass entries carrying fileName; map only the\n // contract fields so nothing outside the generated body reaches the wire.\n return unwrapApiResult(\n await publishFiles({\n body: {\n files: files.map(({ fileId, versionId, branchId, publish }) => ({\n fileId,\n versionId,\n branchId,\n publish,\n })),\n },\n client: getClient(),\n })\n );\n },\n\n async submitUserEditDiffs(\n body: SubmitUserEditDiffsData['body'],\n options: { timeout?: number } = {}\n ) {\n return processBatches(body.diffs, async (diffs) => [\n unwrapApiResult(\n await submitUserEditDiffs({\n body: {\n projectId: body.projectId,\n diffs: diffs.map(\n ({\n diff,\n branchId,\n versionId,\n fileId,\n localContent,\n locale,\n }) => ({\n diff,\n branchId,\n versionId,\n fileId,\n localContent,\n locale: resolveServiceLocale(locale),\n })\n ),\n },\n client: getClient(options.timeout),\n })\n ),\n ]);\n },\n\n async createProject(\n orgId: CreateProjectData['path']['orgId'],\n body: CreateProjectData['body']\n ) {\n return unwrapApiResult(\n await createProject({\n path: { orgId },\n body: {\n ...body,\n defaultLocale: resolveServiceLocale(body.defaultLocale),\n },\n client: getClient(),\n })\n );\n },\n\n /** Every project the configured credentials can read. */\n async listProjects() {\n return collectPages(async (cursor) => {\n const { projects, nextCursor } = unwrapApiResult(\n await listProjects({\n query: cursor ? { cursor } : undefined,\n client: getClient(),\n })\n );\n return { items: projects, nextCursor };\n });\n },\n\n /** Organizations where the signed-in user can create projects; user tokens only. */\n async listOrgs() {\n return collectPages(async (cursor) => {\n const { orgs, nextCursor } = unwrapApiResult(\n await listOrgs({\n query: cursor ? { cursor } : undefined,\n client: getClient(),\n })\n );\n return { items: orgs, nextCursor };\n });\n },\n\n async createProjectApiKey(\n projectId: CreateProjectApiKeyData['path']['projectId'],\n body: CreateProjectApiKeyData['body']\n ) {\n return unwrapApiResult(\n await createProjectApiKey({\n path: { projectId },\n body,\n client: getClient(),\n })\n );\n },\n\n loadProjectInfo,\n\n async getProjectInfo(projectId?: string, timeoutMs?: number) {\n const result = await loadProjectInfo(projectId, timeoutMs);\n return {\n ...result,\n defaultLocale: resolveAliasLocale(\n result.defaultLocale,\n config?.customMapping\n ),\n currentLocales: result.currentLocales.map((locale) =>\n resolveAliasLocale(locale, config?.customMapping)\n ),\n };\n },\n\n async queryFileData(body: GetFileInfoData['body'], timeoutMs?: number) {\n const result = unwrapApiResult(\n await getFileInfo({\n body: {\n ...body,\n translatedFiles: body.translatedFiles?.map((file) => ({\n ...file,\n locale: resolveServiceLocale(file.locale),\n })),\n },\n client: getClient(timeoutMs),\n })\n );\n return {\n ...result,\n translatedFiles: result.translatedFiles.map((file) => ({\n ...file,\n locale: resolveAliasLocale(file.locale, config?.customMapping),\n })),\n sourceFiles: result.sourceFiles.map((file) => ({\n ...file,\n sourceLocale: resolveAliasLocale(\n file.sourceLocale,\n config?.customMapping\n ),\n locales: file.locales.map((locale) =>\n resolveAliasLocale(locale, config?.customMapping)\n ),\n })),\n };\n },\n\n async querySourceFile(\n path: GetTranslationStatusData['path'],\n query: GetTranslationStatusData['query'] = {},\n timeoutMs?: number\n ) {\n const result = unwrapApiResult(\n await getTranslationStatus({\n path,\n query,\n client: getClient(timeoutMs),\n })\n );\n return {\n ...result,\n translations: result.translations.map((translation) => ({\n ...translation,\n locale: resolveAliasLocale(translation.locale, config?.customMapping),\n })),\n sourceFile: {\n ...result.sourceFile,\n sourceLocale: resolveAliasLocale(\n result.sourceFile.sourceLocale,\n config?.customMapping\n ),\n locales: result.sourceFile.locales.map((locale) =>\n resolveAliasLocale(locale, config?.customMapping)\n ),\n },\n };\n },\n\n async downloadFileBatch(\n files: DownloadFilesData['body'],\n options: { timeout?: number } = {}\n ) {\n const request = async (batch: DownloadFilesData['body']) =>\n unwrapApiResult(\n await downloadFiles({\n body: batch.map((file) => ({\n ...file,\n locale: file.locale\n ? resolveServiceLocale(file.locale)\n : undefined,\n })),\n client: getClient(options.timeout),\n })\n );\n const responses = await processBatches(files, async (batch) => [\n await request(batch),\n ]);\n return {\n files: responses.flatMap((response) =>\n response.files.map(\n (file): DownloadedFile => ({\n ...file,\n ...(file.locale && {\n locale: resolveAliasLocale(file.locale, config?.customMapping),\n }),\n data: decodeFileContent(file.data, file.fileFormat),\n metadata: file.metadata,\n })\n )\n ),\n count: responses.reduce((count, response) => count + response.count, 0),\n pending: responses.flatMap((response) =>\n (response.pending ?? []).map((file) => ({\n ...file,\n locale: resolveAliasLocale(file.locale, config?.customMapping),\n }))\n ),\n };\n },\n\n async uploadSourceFiles(\n files: Array<{\n source: UploadSourceFilesData['body']['data'][number]['source'];\n }>,\n options: { sourceLocale: string; timeout?: number }\n ) {\n const sourceLocale = resolveServiceLocale(options.sourceLocale);\n const result = await processBatches(files, async (batch) => {\n const response = unwrapApiResult(\n await uploadSourceFiles({\n body: {\n data: batch.map(({ source }) => ({\n source: {\n ...source,\n content: encodeFileContent(source.content, source.fileFormat),\n locale: resolveServiceLocale(source.locale),\n },\n })),\n sourceLocale,\n },\n client: getClient(options.timeout),\n })\n );\n return response.uploadedFiles.map(aliasUploadedFileLocale);\n });\n\n return { uploadedFiles: result };\n },\n\n async uploadFonts(\n fonts: UploadAssetsData['body']['assets'],\n options: { timeout?: number } = {}\n ) {\n const assets = await processBatches(\n fonts,\n async (batch) => {\n const result = unwrapApiResult(\n await uploadAssets({\n body: { assets: batch },\n client: getClient(options.timeout),\n })\n );\n return result.assets;\n },\n { batchSize: 50 }\n );\n return { assets, count: assets.length };\n },\n\n async uploadTranslations(\n files: UploadTranslationsData['body']['data'],\n options: { sourceLocale: string; timeout?: number }\n ) {\n validateFileFormatTransforms(files.map(({ source }) => source));\n const result = await processBatches(files, async (batch) => {\n const response = unwrapApiResult(\n await uploadTranslations({\n body: {\n data: batch.map(({ source, translations }) => ({\n source: {\n ...source,\n content: encodeFileContent(source.content, source.fileFormat),\n locale: resolveServiceLocale(source.locale),\n },\n translations: translations.map((translation) => ({\n ...translation,\n locale: resolveServiceLocale(translation.locale),\n content: encodeFileContent(\n translation.content,\n translation.fileFormat\n ),\n })),\n })),\n sourceLocale: resolveServiceLocale(options.sourceLocale),\n },\n client: getClient(options.timeout),\n })\n );\n return response.uploadedFiles.map(aliasUploadedFileLocale);\n });\n\n return { uploadedFiles: result };\n },\n };\n}\n\nexport type GtApiAdapter = ReturnType<typeof createGtApiAdapter>;\n","import {\n parse,\n TYPE,\n type MessageFormatElement,\n type ParserOptions,\n} from '@generaltranslation/icu';\n\ntype TraverseIcuOptions = ParserOptions & {\n recurseIntoVisited?: boolean;\n};\n\n/**\n * Given an ICU string, traverse the AST and call the visitor function for each element that matches the type T\n * @param icu - The ICU string to traverse\n * @param shouldVisit - A function that returns true if the element should be visited\n * @param visitor - A function that is called for each element that matches the type T\n * @returns The modified AST of the ICU string.\n *\n * @note This function is a heavy operation, use sparingly\n */\nexport function traverseIcu<T extends MessageFormatElement>({\n icuString,\n shouldVisit,\n visitor,\n options: { recurseIntoVisited = true, ...otherOptions },\n}: {\n icuString: string;\n shouldVisit: (element: MessageFormatElement) => element is T;\n visitor: (element: T) => void;\n options: TraverseIcuOptions;\n}): MessageFormatElement[] {\n const ast = parse(icuString, otherOptions);\n handleChildren(ast);\n return ast;\n\n function handleChildren(children: MessageFormatElement[]): void {\n children.map(handleChild);\n }\n\n function handleChild(child: MessageFormatElement) {\n // handle select var\n let visited = false;\n if (shouldVisit(child)) {\n visitor(child);\n visited = true;\n }\n // recurse on children\n if (!visited || recurseIntoVisited) {\n if (child.type === TYPE.select || child.type === TYPE.plural) {\n Object.values(child.options)\n .map((option) => option.value)\n .map(handleChildren);\n } else if (child.type === TYPE.tag) {\n handleChildren(child.children);\n }\n }\n }\n}\n","export const VAR_IDENTIFIER = '_gt_';\nexport const VAR_NAME_IDENTIFIER = '_gt_var_name';\n","import { VAR_IDENTIFIER } from './constants';\n\n// Regex for _gt_# select\nexport const GT_INDEXED_IDENTIFIER_REGEX = new RegExp(\n `^${VAR_IDENTIFIER}\\\\d+$`\n);\n\nexport const GT_UNINDEXED_IDENTIFIER_REGEX = new RegExp(`^${VAR_IDENTIFIER}$`);\n","import {\n GT_INDEXED_IDENTIFIER_REGEX,\n GT_UNINDEXED_IDENTIFIER_REGEX,\n} from './regex';\nimport { GTIndexedSelectElement, GTUnindexedSelectElement } from './types';\nimport { TYPE, type MessageFormatElement } from '@generaltranslation/icu';\n\n// Visit any _gt_# select\nexport function isGTIndexedSelectElement(\n child: MessageFormatElement\n): child is GTIndexedSelectElement {\n return (\n child.type === TYPE.select &&\n GT_INDEXED_IDENTIFIER_REGEX.test(child.value) &&\n !!child.options.other &&\n (child.options.other.value.length === 0 ||\n (child.options.other.value.length > 0 &&\n child.options.other.value[0]?.type === TYPE.literal))\n );\n}\n\n// Visit any _gt_ select\nexport function isGTUnindexedSelectElement(\n child: MessageFormatElement\n): child is GTUnindexedSelectElement {\n return (\n child.type === TYPE.select &&\n GT_UNINDEXED_IDENTIFIER_REGEX.test(child.value) &&\n !!child.options.other &&\n (child.options.other.value.length === 0 ||\n (child.options.other.value.length > 0 &&\n child.options.other.value[0]?.type === TYPE.literal))\n );\n}\n","import { traverseIcu } from './utils/traverseIcu';\nimport { VAR_IDENTIFIER } from './utils/constants';\nimport { GTUnindexedSelectElement } from './utils/types';\nimport { isGTUnindexedSelectElement } from './utils/traverseHelpers';\n\ntype Location = {\n start: number;\n end: number;\n value: string;\n};\n\n/**\n * Given an encoded ICU string, interpolate only _gt_ variables that have been marked with declareVar()\n * @example\n * const encodedIcu = \"Hi\" + declareVar(\"Brian\") + \", my name is {name}\"\n * // 'Hi {_gt_, select, other {Brian}}, my name is {name}'\n * decodeVars(encodedIcu)\n * // 'Hi Brian, my name is {name}'\n */\nexport function decodeVars(icuString: string): string {\n // Check if the string contains _gt_\n if (!icuString.includes(VAR_IDENTIFIER)) {\n return icuString;\n }\n\n // Record the location of the variable\n const variableLocations: Location[] = [];\n function visitor(child: GTUnindexedSelectElement): void {\n variableLocations.push({\n start: child.location?.start.offset ?? 0,\n end: child.location?.end.offset ?? 0,\n value:\n child.options.other.value.length > 0\n ? child.options.other.value[0].value\n : '',\n });\n }\n\n // Find all variable identifiers.\n traverseIcu({\n icuString,\n shouldVisit: isGTUnindexedSelectElement,\n visitor,\n options: {\n recurseIntoVisited: false,\n captureLocation: true,\n },\n });\n\n // Construct output string\n let previousIndex = 0;\n const outputList = [];\n for (let i = 0; i < variableLocations.length; i++) {\n outputList.push(icuString.slice(previousIndex, variableLocations[i].start));\n outputList.push(variableLocations[i].value);\n previousIndex = variableLocations[i].end;\n }\n if (previousIndex < icuString.length) {\n outputList.push(icuString.slice(previousIndex));\n }\n const outputString = outputList.join('');\n\n return outputString;\n}\n","/**\n * Sanitizes string by escaping ICU syntax\n *\n * Sanitize arbitrary string so it does not break the following ICU message syntax:\n * {_gt_, select, other {string_here}}\n *\n * Escapes ICU special characters by:\n * 1. Doubling all single quotes (U+0027 ')\n * 2. Adding a single quote before the first special character ({}<>)\n * 3. Adding a single quote after the last special character ({}<>)\n */\nexport function sanitizeVar(string: string): string {\n // First, double all single quotes (both ASCII and Unicode).\n let result = string.replace(/'/g, \"''\");\n\n // Find first and last positions of special characters\n const specialChars = /[{}<>]/;\n const firstSpecialIndex = result.search(specialChars);\n\n if (firstSpecialIndex === -1) {\n // No special characters; return with just doubled quotes.\n return result;\n }\n\n // Find last special character position\n let lastSpecialIndex = -1;\n for (let i = result.length - 1; i >= 0; i--) {\n if (specialChars.test(result[i])) {\n lastSpecialIndex = i;\n break;\n }\n }\n\n // Insert quotes around the special character region.\n result =\n result.slice(0, firstSpecialIndex) +\n \"'\" +\n result.slice(firstSpecialIndex, lastSpecialIndex + 1) +\n \"'\" +\n result.slice(lastSpecialIndex + 1);\n\n return result;\n}\n","import { VAR_IDENTIFIER, VAR_NAME_IDENTIFIER } from './utils/constants';\nimport { sanitizeVar } from './utils/sanitizeVar';\n\n/**\n * Mark as a non-translatable string. Use within a derive() call to mark content as not derivable (e.g., not possible to statically analyze).\n *\n * @example\n * function nonDerivableFunction() {\n * return Math.random();\n * }\n *\n * function derivableFunction() {\n * if (condition) {\n * return declareVar(nonDerivableFunction())\n * }\n * return 'John Doe';\n * }\n *\n * const gt = useGT();\n * gt(`My name is ${derive(derivableFunction())}`);\n *\n * @param {string | number | boolean | null | undefined} variable - The variable to sanitize.\n * @param {Object} [options] - The options for the sanitization.\n * @param {string} [options.$name] - The name of the variable.\n * @returns {string} The sanitized value.\n */\nexport function declareVar(\n variable: string | number | boolean | null | undefined,\n options?: { $name?: string }\n): string {\n // Variable section.\n const sanitizedVariable = sanitizeVar(String(variable ?? ''));\n const variableSection = ` other {${sanitizedVariable}}`;\n\n // Name section.\n let nameSection = '';\n if (options?.$name) {\n const sanitizedName = sanitizeVar(options.$name);\n nameSection = ` ${VAR_NAME_IDENTIFIER} {${sanitizedName}}`;\n }\n\n // interpolate\n return `{${VAR_IDENTIFIER}, select,${variableSection}${nameSection}}`;\n}\n","/**\n * Marks content as derivable by the GT compiler and CLI.\n *\n * Use `derive()` when a translation string or context needs content that is\n * computed from source code, but should still be discovered during extraction\n * instead of treated as a runtime interpolation variable. The CLI attempts to\n * resolve the derivable expression into every possible static value and\n * includes those values in the source content that gets translated.\n *\n * `derive()` returns its argument unchanged at runtime.\n *\n * Run `gt validate` after adding or changing `derive()` calls to verify that\n * each derivable expression can be resolved by the CLI before translating or\n * building.\n *\n * @example\n * ```jsx\n * function getSubject() {\n * return (Math.random() > 0.5) ? \"Alice\" : \"Brian\";\n * }\n * ...\n * gt(`My name is ${derive(getSubject())}`);\n * ```\n *\n * @param {T extends string | boolean | number | null | undefined} content - Content to derive for translation extraction.\n * @returns {T} The same content, unchanged at runtime.\n */\nexport function derive<T extends string | boolean | number | null | undefined>(\n content: T\n): T {\n return content;\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,OAAO,MAAsB;AAC3C,KAAI,OAAO,WAAW,YAEpB,QAAO,OAAO,KAAK,MAAM,OAAO,CAAC,SAAS,SAAS;CAGrD,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK;CAC5C,IAAI,SAAS;AACb,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,WAAU,OAAO,aAAa,MAAM,GAAG;AAEzC,QAAO,KAAK,OAAO;;AAIrB,SAAgB,OAAO,QAAwB;AAC7C,KAAI,OAAO,WAAW,YAEpB,QAAO,OAAO,KAAK,QAAQ,SAAS,CAAC,SAAS,OAAO;CAGvD,MAAM,SAAS,KAAK,OAAO;CAC3B,MAAM,QAAQ,IAAI,W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