generaltranslation 9.0.0 → 9.0.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/id/hashSource.d.ts +2 -1
  3. package/dist/id/hashSource.js +2 -1
  4. package/dist/id/types.d.ts +5 -0
  5. package/dist/{id-CGtkkWBE.mjs → id-CJxNTGtQ.mjs} +3 -2
  6. package/dist/id-CJxNTGtQ.mjs.map +1 -0
  7. package/dist/{id-DTcNToOd.cjs → id-CkTE9OaC.cjs} +3 -2
  8. package/dist/{id-DTcNToOd.cjs.map → id-CkTE9OaC.cjs.map} +1 -1
  9. package/dist/id.cjs +1 -1
  10. package/dist/id.d.cts +3 -2
  11. package/dist/id.d.mts +3 -2
  12. package/dist/id.mjs +1 -1
  13. package/dist/index.cjs +4 -5
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +4 -19
  16. package/dist/index.d.mts +4 -19
  17. package/dist/index.d.ts +5 -7
  18. package/dist/index.js +3 -4
  19. package/dist/index.mjs +4 -5
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/internal.d.cts +1 -1
  22. package/dist/internal.d.mts +1 -1
  23. package/dist/{runtime-vpAQMY2e.mjs → runtime-WSpZppgm.mjs} +2 -2
  24. package/dist/{runtime-vpAQMY2e.mjs.map → runtime-WSpZppgm.mjs.map} +1 -1
  25. package/dist/{runtime-DVD9hQXj.cjs → runtime-wK7jzE9f.cjs} +2 -2
  26. package/dist/{runtime-DVD9hQXj.cjs.map → runtime-wK7jzE9f.cjs.map} +1 -1
  27. package/dist/runtime.cjs +1 -1
  28. package/dist/runtime.d.cts +1 -1
  29. package/dist/runtime.d.mts +1 -1
  30. package/dist/runtime.mjs +1 -1
  31. package/dist/translate/setupProject.d.ts +2 -0
  32. package/dist/{types-CHNhO-Lt.d.mts → types-CzFzXgUO.d.mts} +21 -2
  33. package/dist/{types-DboOaYN_.d.cts → types-iLf0drw8.d.cts} +21 -2
  34. package/dist/types.d.cts +2 -2
  35. package/dist/types.d.mts +2 -2
  36. package/dist/types.d.ts +1 -0
  37. package/package.json +1 -1
  38. package/dist/id-CGtkkWBE.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-DVD9hQXj.cjs","names":["createDiagnosticMessage","defaultTimeout","ApiError","API_VERSION","hashSource","LocaleConfig"],"sources":["../src/logging/errors.ts","../src/logging/logger.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/validateResponse.ts","../src/translate/utils/handleFetchError.ts","../src/translate/utils/generateRequestHeaders.ts","../src/translate/utils/apiRequest.ts","../src/translate/translateMany.ts","../src/runtime.ts"],"sourcesContent":["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 invalidAuthError = createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Authentication failed',\n fix: 'Check that your API key and project ID are correct',\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.\nexport const defaultLogger = 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 = defaultLogger.child('fetch');\nexport const gtInstanceLogger = defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps the fetch function with a timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeout - The timeout in milliseconds.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeout?: number\n) {\n const controller = new AbortController();\n const signal = controller.signal;\n\n timeout = timeout ? timeout : defaultTimeout;\n const timeoutId = timeout\n ? setTimeout(() => controller.abort(), timeout)\n : null;\n\n try {\n const response = await fetch(url, { ...options, signal });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw translationTimeoutError(timeout);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { apiError } from '../../logging/errors';\nimport { ApiError } from '../../errors/ApiError';\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 { fetchLogger } from '../../logging/logger';\nimport {\n translationRequestFailedError,\n translationTimeoutError,\n} from '../../logging/errors';\n\nexport function handleFetchError(error: unknown, timeout: number): never {\n if (error instanceof Error && error.name === 'AbortError') {\n const errorMessage = translationTimeoutError(timeout);\n fetchLogger.error(errorMessage);\n throw new Error(errorMessage);\n }\n const errorMessage = translationRequestFailedError(\n error instanceof Error ? error.message : String(error)\n );\n fetchLogger.error(errorMessage);\n throw error;\n}\n","import { TranslationRequestConfig } from '../../types';\nimport { API_VERSION } from '../api';\n\nexport function generateRequestHeaders(\n config: TranslationRequestConfig,\n excludeContentType = false\n) {\n const authHeaders: Record<string, string> = {\n ...(!excludeContentType && { 'Content-Type': 'application/json' }),\n 'gt-project-id': config.projectId,\n };\n\n if (config.apiKey) {\n authHeaders['Authorization'] = `Bearer ${config.apiKey}`;\n }\n\n authHeaders['gt-api-version'] = API_VERSION;\n\n return authHeaders;\n}\n","import { TranslationRequestConfig } from '../../types';\nimport { defaultBaseUrl } from '../../settings/settingsUrls';\nimport { defaultTimeout } from '../../settings/settings';\nimport { fetchWithTimeout } from './fetchWithTimeout';\nimport { validateResponse } from './validateResponse';\nimport { handleFetchError } from './handleFetchError';\nimport { generateRequestHeaders } from './generateRequestHeaders';\n\nconst MAX_RETRIES = 3;\nconst INITIAL_DELAY_MS = 500;\nconst RATE_LIMIT_RETRY_DELAY_MS = 60_000;\nconst MS_PER_SECOND = 1000;\n\ntype RetryPolicy = 'exponential' | 'linear' | 'none';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction getRetryDelay(policy: RetryPolicy, attempt: number): number {\n switch (policy) {\n case 'linear':\n return INITIAL_DELAY_MS * (attempt + 1);\n case 'exponential':\n return INITIAL_DELAY_MS * 2 ** attempt;\n default:\n return 0;\n }\n}\n\nfunction parseDelayMs(value: string | null): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const seconds = Number(value.split(',')[0].split(';')[0].trim());\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return seconds * MS_PER_SECOND;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n const delayMs = parseDelayMs(value);\n if (delayMs !== undefined) {\n return delayMs;\n }\n\n if (!value) {\n return undefined;\n }\n\n const retryDate = Date.parse(value);\n if (Number.isNaN(retryDate)) {\n return undefined;\n }\n\n return Math.max(retryDate - Date.now(), 0);\n}\n\nfunction getRateLimitRetryDelay(response: Response): number {\n return (\n parseRetryAfter(response.headers.get('Retry-After')) ??\n parseDelayMs(response.headers.get('RateLimit-Reset')) ??\n RATE_LIMIT_RETRY_DELAY_MS\n );\n}\n\nfunction getResponseRetryDelay(\n response: Response,\n policy: RetryPolicy,\n attempt: number\n): number {\n if (response.status === 429) {\n return getRateLimitRetryDelay(response);\n }\n\n return getRetryDelay(policy, attempt);\n}\n\n/**\n * @internal\n *\n * Makes an API request with automatic retry for 429 and 5XX errors.\n *\n * Encapsulates URL construction, fetch with timeout, error handling,\n * response validation, and JSON parsing.\n *\n * @param config - The configuration for the API call.\n * @param endpoint - The API endpoint path (e.g. '/v2/project/jobs/info')\n * @param options - Optional request options.\n * @returns The parsed JSON response.\n */\nexport async function apiRequest<T>(\n config: TranslationRequestConfig,\n endpoint: string,\n options?: {\n body?: unknown;\n timeout?: number;\n method?: 'GET' | 'POST';\n retryPolicy?: RetryPolicy;\n }\n): Promise<T> {\n const timeout = options?.timeout ?? defaultTimeout;\n const url = `${config.baseUrl || defaultBaseUrl}${endpoint}`;\n const method = options?.method ?? 'POST';\n const retryPolicy = options?.retryPolicy ?? 'exponential';\n const maxRetries = retryPolicy === 'none' ? 0 : MAX_RETRIES;\n\n const requestInit: RequestInit = {\n method,\n headers: generateRequestHeaders(config),\n };\n if (options?.body !== undefined) {\n requestInit.body = JSON.stringify(options.body);\n }\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n let response: Response;\n try {\n response = await fetchWithTimeout(url, requestInit, timeout);\n } catch (error) {\n if (attempt < maxRetries) {\n await sleep(getRetryDelay(retryPolicy, attempt));\n continue;\n }\n handleFetchError(error, timeout);\n }\n\n // Retry on rate limits and 5XX server errors.\n if (\n (response!.status === 429 || response!.status >= 500) &&\n attempt < maxRetries\n ) {\n await sleep(getResponseRetryDelay(response!, retryPolicy, attempt));\n continue;\n }\n\n await validateResponse(response!);\n return (await response!.json()) as T;\n }\n\n throw new Error('Max retries exceeded');\n}\n","import {\n TranslationRequestConfig,\n TranslateManyResult,\n TranslationResult,\n} from '../types';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n TranslateManyEntry,\n TranslateOptions,\n EntryMetadata,\n} from '../types-dir/api/entry';\nimport { apiRequest } from './utils/apiRequest';\nimport type { Content } from '@generaltranslation/format/types';\nimport { hashSource } from '../id';\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.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nexport async function _translateMany<\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 timeout?: number\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nexport async function _translateMany(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig,\n timeout?: number\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 dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n const response = await apiRequest<Record<string, TranslationResult>>(\n { ...config, baseUrl: config.baseUrl || defaultRuntimeApiUrl },\n `/v2/translate`,\n {\n body: {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: globalMetadata,\n },\n timeout: timeout,\n retryPolicy: 'none',\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","// `generaltranslation` language toolkit\n// © 2026, General Translation, Inc.\n\n// ----- IMPORTS ----- //\n\nimport {\n LocaleConfig,\n determineLocale as _determineLocale,\n getRegionProperties as _getRegionProperties,\n isValidLocale as _isValidLocale,\n requiresTranslation as _requiresTranslation,\n resolveAliasLocale as _resolveAliasLocale,\n resolveCanonicalLocale as _resolveCanonicalLocale,\n standardizeLocale as _standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n CustomMapping,\n CustomRegionMapping,\n CutoffFormatOptions,\n FormatVariables,\n LocaleProperties,\n StringFormat,\n} from '@generaltranslation/format/types';\nimport {\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n TranslateManyEntry,\n} from './types';\nimport { libraryDefaultLocale } from './settings/settings';\nimport {\n noSourceLocaleProvidedError,\n noTargetLocaleProvidedError,\n invalidLocaleError,\n invalidLocalesError,\n noProjectIdProvidedError,\n noApiKeyProvidedError,\n} from './logging/errors';\nimport { gtInstanceLogger } from './logging/logger';\nimport { _translateMany } from './translate/translateMany';\nimport { TranslateOptions } from './types-dir/api/entry';\n\n// ============================================================ //\n// Runtime Class //\n// ============================================================ //\n/**\n * Type representing the constructor parameters for the GT and GTRuntime classes.\n * @typedef {Object} GTConstructorParams\n * @property {string} [apiKey] - The API key for accessing the translation service\n * @property {string} [devApiKey] - The development API key for accessing the translation service\n * @property {string} [sourceLocale] - The default source locale for translations\n * @property {string} [targetLocale] - The default target locale for translations\n * @property {string[]} [locales] - Array of supported locales\n * @property {string} [projectId] - The project ID for the translation service\n * @property {string} [baseUrl] - The base URL for the translation service\n * @property {CustomMapping} [customMapping] - Custom mapping of locale codes to their names\n */\nexport type GTConstructorParams = {\n apiKey?: string;\n devApiKey?: string;\n sourceLocale?: string;\n targetLocale?: string;\n locales?: string[];\n projectId?: string;\n baseUrl?: string;\n customMapping?: CustomMapping;\n};\n\n/**\n * GTRuntime is the runtime core of the GT driver: locale management,\n * formatting, and runtime translation requests.\n *\n * Browser-facing SDK code constructs this class (via `generaltranslation/runtime`)\n * so production bundles do not ship the project/file management API client\n * that lives on the GT class exported from the main entry.\n *\n * @example\n * const gt = new GTRuntime({\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\nexport class GTRuntime {\n /** Base URL for the translation service API */\n baseUrl?: string;\n\n /** Project ID for the translation service */\n projectId?: string;\n\n /** API key for accessing the translation service */\n apiKey?: string;\n\n /** Development API key for accessing the translation service */\n devApiKey?: string;\n\n /** Source locale for translations */\n sourceLocale?: string;\n\n /** Target locale for translations */\n targetLocale?: string;\n\n /** Array of supported locales */\n locales?: string[];\n\n /** Custom mapping for locale codes to their names */\n customMapping?: CustomMapping;\n\n /** Lazily derived reverse custom mapping for alias locales */\n reverseCustomMapping?: Record<string, string>;\n\n /** Lazily derived custom mapping for regions */\n customRegionMapping?: CustomRegionMapping;\n\n /** Runtime-safe locale and formatting helpers (backing field) */\n private _localeConfig!: LocaleConfig;\n\n /** Runtime-safe locale and formatting helpers */\n get localeConfig() {\n return this._localeConfig;\n }\n\n /**\n * Constructs an instance of the GTRuntime class.\n *\n * @param {GTConstructorParams} [params] - The parameters for initializing the GTRuntime instance\n * @throws {Error} If an invalid locale is provided\n * @throws {Error} If any of the provided locales are invalid\n *\n * @example\n * const gt = new GTRuntime({\n * apiKey: 'your-api-key',\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\n constructor(params: GTConstructorParams = {}) {\n // Read environment\n if (typeof process !== 'undefined') {\n this.apiKey ||= process.env?.GT_API_KEY;\n this.devApiKey ||= process.env?.GT_DEV_API_KEY;\n this.projectId ||= process.env?.GT_PROJECT_ID;\n }\n // Set up config\n this.setConfig(params);\n }\n\n setConfig({\n apiKey,\n devApiKey,\n sourceLocale,\n targetLocale,\n locales,\n projectId,\n customMapping,\n baseUrl,\n }: GTConstructorParams) {\n // ----- Environment properties ----- //\n if (apiKey) this.apiKey = apiKey;\n if (devApiKey) this.devApiKey = devApiKey;\n if (projectId) this.projectId = projectId;\n\n // ----- Standardize locales ----- //\n\n // source locale\n if (sourceLocale) {\n this.sourceLocale = _standardizeLocale(sourceLocale);\n if (!_isValidLocale(this.sourceLocale, customMapping))\n throw new Error(invalidLocaleError(this.sourceLocale));\n }\n\n // target locale\n if (targetLocale) {\n this.targetLocale = _standardizeLocale(targetLocale);\n if (!_isValidLocale(this.targetLocale, customMapping))\n throw new Error(invalidLocaleError(this.targetLocale));\n }\n\n // locales\n if (locales) {\n const result: string[] = [];\n const invalidLocales: string[] = [];\n locales.forEach((locale) => {\n const standardizedLocale = _standardizeLocale(locale);\n if (_isValidLocale(standardizedLocale)) {\n result.push(standardizedLocale);\n } else {\n invalidLocales.push(locale);\n }\n });\n if (invalidLocales.length > 0) {\n throw new Error(invalidLocalesError(invalidLocales));\n }\n this.locales = result;\n }\n\n // ----- Other properties ----- //\n if (baseUrl) this.baseUrl = baseUrl;\n if (customMapping) {\n this.customMapping = customMapping;\n this.reverseCustomMapping = Object.fromEntries(\n Object.entries(customMapping)\n .filter(\n ([, value]) => value && typeof value === 'object' && 'code' in value\n )\n .map(([key, value]) => [(value as { code: string }).code, key])\n );\n }\n this._localeConfig = new LocaleConfig({\n defaultLocale: this.sourceLocale,\n locales: this.locales ?? [],\n customMapping: this.customMapping,\n });\n }\n\n // -------------- Private Methods -------------- //\n\n protected _getTranslationConfig(): TranslationRequestConfig {\n return {\n baseUrl: this.baseUrl,\n apiKey: this.apiKey || this.devApiKey,\n projectId: this.projectId || '',\n };\n }\n\n protected _validateAuth(functionName: string) {\n const errors: string[] = [];\n if (!this.apiKey && !this.devApiKey) {\n const error = noApiKeyProvidedError(functionName);\n errors.push(error);\n }\n if (!this.projectId) {\n const error = noProjectIdProvidedError(functionName);\n errors.push(error);\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n }\n\n /**\n * Translates a single source string to the target locale.\n * Routes through {@link translateMany} under the hood.\n *\n * @param {string} source - The source string to translate.\n * @param {object} options - Translation options including targetLocale and optional entry metadata.\n * @returns {Promise<TranslationResult | TranslationError>} The translated content.\n *\n * @example\n * const result = await gt.translate('Hello, world!', { targetLocale: 'es' });\n *\n * @example\n * const result = await gt.translate('Hello, world!', {\n * targetLocale: 'es',\n * dataFormat: 'ICU',\n * context: 'A formal greeting',\n * });\n */\n async translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslationResult | TranslationError> {\n // Normalize string shorthand to options object\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n // Validation\n this._validateAuth('translate');\n\n // Require target locale\n let targetLocale = options?.targetLocale || this.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError('translate');\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n // Replace target locale with canonical locale\n targetLocale = this.resolveCanonicalLocale(targetLocale);\n\n const sourceLocale = this.resolveCanonicalLocale(\n options?.sourceLocale || this.sourceLocale || libraryDefaultLocale\n );\n\n // Request the translation.\n const results = await _translateMany(\n [source],\n {\n ...options,\n targetLocale,\n sourceLocale,\n },\n this._getTranslationConfig(),\n timeout\n );\n return results[0];\n }\n\n /**\n * Translates multiple source strings to the target locale.\n * Each entry can be a plain string or an object with source and metadata fields.\n *\n * @param {TranslateManyEntry[] | Record<string, TranslateManyEntry>} sources - The source entries to translate. Can be an array or a record keyed by hash.\n * @param {object} options - Translation options including targetLocale.\n * @returns {Promise<TranslateManyResult | Record<string, TranslationResult>>} The translated contents. An array if sources was an array, a record if sources was a record.\n *\n * @example\n * const result = await gt.translateMany(\n * ['Hello, world!', 'Goodbye, world!'],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * [{ source: 'Hello, world!', dataFormat: 'ICU' }],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * { 'my-hash': 'Hello, world!' },\n * { targetLocale: 'es' }\n * );\n */\n async translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult>;\n async translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<Record<string, TranslationResult>>;\n async translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n // Normalize string shorthand to options object\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n // Validation\n this._validateAuth('translateMany');\n\n // Require target locale\n let targetLocale = options?.targetLocale || this.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError('translateMany');\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n // Replace target locale with canonical locale\n targetLocale = this.resolveCanonicalLocale(targetLocale);\n\n const sourceLocale = this.resolveCanonicalLocale(\n options?.sourceLocale || this.sourceLocale || libraryDefaultLocale\n );\n\n // Request the translation.\n return await _translateMany(\n sources,\n {\n ...options,\n targetLocale,\n sourceLocale,\n },\n this._getTranslationConfig(),\n timeout\n );\n }\n\n // -------------- Formatting -------------- //\n\n /**\n * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.\n *\n * This method uses the GT instance's rendering locales by default for locale-specific terminator selection,\n * but can be overridden with custom locales in the options.\n *\n * @param {string} value - The string value to format with cutoff behavior.\n * @param {Object} [options] - Configuration options for cutoff formatting.\n * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.\n * @param {number} [options.maxChars] - The maximum number of characters to display.\n * - Undefined values are treated as no cutoff.\n * - Negative values follow .slice() behavior and terminator will be added before the value.\n * - 0 will result in an empty string.\n * - If cutoff results in an empty string, no terminator is added.\n * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.\n * @param {string} [options.terminator] - Optional override the terminator to use.\n * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.\n * - If no terminator is provided, then separator is ignored.\n * @returns {string} The formatted string with terminator applied if cutoff occurs.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.formatCutoff('Hello, world!', { maxChars: 8 });\n * // Returns: 'Hello, w...'\n *\n * @example\n * gt.formatCutoff('Hello, world!', { maxChars: -3 });\n * // Returns: '...ld!'\n */\n formatCutoff(\n value: string,\n options?: {\n locales?: string | string[];\n } & CutoffFormatOptions\n ): string {\n return this.localeConfig.formatCutoff(value, this.targetLocale, options);\n }\n\n /**\n * Formats a message according to the specified locales and options.\n *\n * @param {string} message - The message to format.\n * @param {string | string[]} [locales='en'] - The locales to use for formatting.\n * @param {FormatVariables} [variables={}] - The variables to use for formatting.\n * @param {StringFormat} [dataFormat='ICU'] - The format of the message.\n * @returns {string} The formatted message.\n *\n * @example\n * gt.formatMessage('Hello {name}', { name: 'John' });\n * // Returns: \"Hello John\"\n *\n * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });\n * // Returns: \"Bonjour John\"\n */\n formatMessage(\n message: string,\n options?: {\n locales?: string | string[];\n variables?: FormatVariables;\n dataFormat?: StringFormat;\n }\n ): string {\n return this.localeConfig.formatMessage(message, this.targetLocale, options);\n }\n /**\n * Formats a number according to the specified locales and options.\n *\n * @param {number} number - The number to format.\n * @param {Object} [options] - Additional options for number formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted number.\n *\n * @example\n * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });\n * // Returns: \"$1,234.56\"\n */\n formatNum(\n number: number,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatNum(number, this.targetLocale, options);\n }\n\n /**\n * Formats a date according to the specified locales and options.\n *\n * @param {Date} date - The date to format.\n * @param {Object} [options] - Additional options for date formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options.\n * @returns {string} The formatted date.\n *\n * @example\n * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });\n * // Returns: \"Thursday, March 14, 2024 at 2:30:45 PM GMT-7\"\n */\n formatDateTime(\n date: Date,\n options?: {\n locales?: string | string[];\n } & Intl.DateTimeFormatOptions\n ): string {\n return this.localeConfig.formatDateTime(date, this.targetLocale, options);\n }\n\n /**\n * Formats a currency value according to the specified locales and options.\n *\n * @param {number} value - The currency value to format.\n * @param {string} currency - The currency code (e.g., 'USD', 'EUR')\n * @param {Object} [options] - Additional options for currency formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted currency value.\n *\n * @example\n * gt.formatCurrency(1234.56, 'USD', { style: 'currency' });\n * // Returns: \"$1,234.56\"\n */\n formatCurrency(\n value: number,\n currency: string,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatCurrency(\n value,\n currency,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n *\n * @param {Array<string | number>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {string} The formatted list.\n *\n * @example\n * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });\n * // Returns: \"apple, banana, and orange\"\n */\n formatList(\n array: Array<string | number>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ) {\n return this.localeConfig.formatList(array, this.targetLocale, options);\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n * @param {Array<T>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {Array<T | string>} The formatted list parts.\n *\n * @example\n * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });\n * // Returns: ['apple', ', ', 42, ' and ', '{ foo: \"bar\" }']\n */\n formatListToParts<T>(\n array: Array<T>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ): Array<T | string> {\n return this.localeConfig.formatListToParts<T>(\n array,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time value according to the specified locales and options.\n *\n * @param {number} value - The relative time value to format.\n * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')\n * @param {Object} options - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.\n * @returns {string} The formatted relative time string.\n *\n * @example\n * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });\n * // Returns: \"yesterday\"\n */\n formatRelativeTime(\n value: number,\n unit: Intl.RelativeTimeFormatUnit,\n options?: {\n locales?: string | string[];\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTime(\n value,\n unit,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time string from a Date, automatically selecting the best unit.\n *\n * @param {Date} date - The date to format relative to now.\n * @param {Object} [options] - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @returns {string} The formatted relative time string (e.g., \"2 hours ago\", \"in 3 days\")\n *\n * @example\n * gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));\n * // Returns: \"1 hour ago\"\n */\n formatRelativeTimeFromDate(\n date: Date,\n options?: {\n locales?: string | string[];\n baseDate?: Date;\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTimeFromDate(\n date,\n this.targetLocale,\n options\n );\n }\n\n // -------------- Locale Properties -------------- //\n\n /**\n * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {string} The display name corresponding to the code.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleName('es-ES');\n * // Returns: \"Spanish (Spain)\"\n */\n getLocaleName(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleName'));\n return this.localeConfig.getLocaleName(locale);\n }\n\n /**\n * Retrieves an emoji based on a given locale code.\n * Uses the locale's region (if present) to select an emoji or falls back on default emojis.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')\n * @returns {string} The emoji representing the locale or its region.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleEmoji('es-ES');\n * // Returns: \"🇪🇸\"\n */\n getLocaleEmoji(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleEmoji'));\n return this.localeConfig.getLocaleEmoji(locale);\n }\n\n /**\n * Generates linguistic details for a given locale code.\n *\n * This function returns information about the locale,\n * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).\n * The function provides these names in both your default language and native forms, and an associated emoji.\n *\n * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., \"de-AT\").\n * @returns {LocaleProperties} - An object containing detailed information about the locale.\n *\n * @property {string} code - The full locale code, e.g., \"de-AT\".\n * @property {string} name - Language name in the default display language, e.g., \"Austrian German\".\n * @property {string} nativeName - Language name in the locale's native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} languageCode - The base language code, e.g., \"de\".\n * @property {string} languageName - The language name in the default display language, e.g., \"German\".\n * @property {string} nativeLanguageName - The language name in the native language, e.g., \"Deutsch\".\n * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., \"German (AT)\".\n * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., \"Deutsch (AT)\".\n * @property {string} regionCode - The region code from maximization, e.g., \"AT\".\n * @property {string} regionName - The region name in the default display language, e.g., \"Austria\".\n * @property {string} nativeRegionName - The region name in the native language, e.g., \"Österreich\".\n * @property {string} scriptCode - The script code from maximization, e.g., \"Latn\".\n * @property {string} scriptName - The script name in the default display language, e.g., \"Latin\".\n * @property {string} nativeScriptName - The script name in the native language, e.g., \"Lateinisch\".\n * @property {string} maximizedCode - The maximized locale code, e.g., \"de-Latn-AT\".\n * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., \"Austrian German (Latin)\".\n * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., \"Österreichisches Deutsch (Lateinisch)\".\n * @property {string} minimizedCode - Minimized locale code, e.g., \"de-AT\" (or \"de\" for \"de-DE\").\n * @property {string} minimizedName - Minimized language name in the default language, e.g., \"Austrian German\".\n * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} emoji - The emoji associated with the locale's region, if applicable.\n */\n getLocaleProperties(locale = this.targetLocale): LocaleProperties {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleProperties'));\n return this.localeConfig.getLocaleProperties(locale);\n }\n\n /**\n * Retrieves multiple properties for a given region code, including:\n * - `code`: the original region code\n * - `name`: the localized display name\n * - `emoji`: the associated flag or symbol\n *\n * Behavior:\n * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `\"US\"`, `\"FR\"`, `\"419\"`).\n * - Uses the instance's `targetLocale` to localize the region name for the user.\n * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.\n * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.\n * - Falls back to the region code as `name` if display name resolution fails.\n * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.\n *\n * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `\"US\"`, `\"GB\"`, `\"DE\"`).\n * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.\n * @returns {{ code: string, name: string, emoji: string }} An object containing:\n * - `code`: the input region code\n * - `name`: the localized or custom region name\n * - `emoji`: the matching emoji flag or symbol\n *\n * @throws {Error} If no target locale is available to determine region properties.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'fr-FR' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }\n *\n * @example\n * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });\n * // => { code: 'US', name: 'USA', emoji: '🗽' }\n */\n getRegionProperties(\n region = this.getLocaleProperties().regionCode,\n customMapping?: CustomRegionMapping\n ): { code: string; name: string; emoji: string } {\n if (!customMapping) {\n if (this.customMapping && !this.customRegionMapping) {\n // Lazy derive custom region mapping from customMapping\n const customRegionMapping: CustomRegionMapping = {};\n for (const [locale, lp] of Object.entries(this.customMapping)) {\n if (\n lp &&\n typeof lp === 'object' &&\n lp.regionCode &&\n !customRegionMapping[lp.regionCode]\n ) {\n const { regionName: name, emoji } = lp;\n customRegionMapping[lp.regionCode] = {\n locale,\n ...(name && { name }),\n ...(emoji && { emoji }),\n };\n }\n }\n this.customRegionMapping = customRegionMapping;\n }\n customMapping = this.customRegionMapping;\n }\n return _getRegionProperties(\n region,\n this.targetLocale, // this.targetLocale because we want it in the user's language\n customMapping\n );\n }\n\n /**\n * Determines whether a translation is required based on the source and target locales.\n *\n * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content.\n * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into.\n * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales.\n * @returns {boolean} True if translation is required, false otherwise\n * @throws {Error} If no source locale is provided.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.requiresTranslation('en-US', 'es-ES');\n * // Returns: true\n */\n requiresTranslation(\n sourceLocale = this.sourceLocale,\n targetLocale = this.targetLocale,\n approvedLocales: string[] | undefined = this.locales,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!sourceLocale)\n throw new Error(noSourceLocaleProvidedError('requiresTranslation'));\n if (!targetLocale)\n throw new Error(noTargetLocaleProvidedError('requiresTranslation'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.requiresTranslation(\n targetLocale,\n sourceLocale,\n approvedLocales\n );\n }\n return _requiresTranslation(\n sourceLocale,\n targetLocale,\n approvedLocales,\n customMapping\n );\n }\n\n /**\n * Determines the best matching locale from the provided approved locales list.\n *\n * @param {string | string[]} locales - A single locale or array of locales in preference order.\n * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order.\n * @returns {string | undefined} The best matching locale, or undefined if no match is found.\n *\n * @example\n * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);\n * // Returns: \"fr-FR\"\n */\n determineLocale(\n locales: string | string[],\n approvedLocales: string[] | undefined = this.locales || [],\n customMapping: CustomMapping | undefined = this.customMapping\n ): string | undefined {\n if (customMapping === this.customMapping) {\n return this.localeConfig.determineLocale(locales, approvedLocales ?? []);\n }\n return _determineLocale(locales, approvedLocales, customMapping);\n }\n\n /**\n * Gets the text direction for a given locale code.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left; otherwise 'ltr'.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleDirection('ar-SA');\n * // Returns: \"rtl\"\n */\n getLocaleDirection(locale = this.targetLocale): 'ltr' | 'rtl' {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleDirection'));\n return this.localeConfig.getLocaleDirection(locale);\n }\n\n /**\n * Checks if a given BCP 47 locale code is valid.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate.\n * @param {CustomMapping} [customMapping=this.customMapping] - The custom mapping to use for validation.\n * @returns {boolean} True if the locale code is valid, false otherwise\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.isValidLocale('en-US');\n * // Returns: true\n */\n isValidLocale(\n locale = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!locale) throw new Error(noTargetLocaleProvidedError('isValidLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.isValidLocale(locale);\n }\n return _isValidLocale(locale, customMapping);\n }\n\n /**\n * Resolves the canonical locale for a given locale.\n * @param locale - The locale to resolve the canonical locale for\n * @param customMapping - The custom mapping to use for resolving the canonical locale\n * @returns The canonical locale, or the input locale when no canonical mapping exists.\n */\n resolveCanonicalLocale(\n locale: string | undefined = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveCanonicalLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveCanonicalLocale(locale);\n }\n return _resolveCanonicalLocale(locale, customMapping);\n }\n\n /**\n * Resolves the alias locale for a given locale.\n * @param locale - The locale to resolve the alias locale for\n * @param customMapping - The custom mapping to use for resolving the alias locale\n * @returns The configured alias for a canonical locale, or the input locale when already an alias or no alias mapping exists.\n */\n resolveAliasLocale(\n locale: string,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveAliasLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveAliasLocale(locale);\n }\n return _resolveAliasLocale(locale, customMapping);\n }\n\n /**\n * Standardizes a BCP 47 locale code to ensure correct formatting.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize.\n * @returns {string} The standardized locale code, or the input string if it cannot be standardized.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.standardizeLocale('en_us');\n * // Returns: \"en-US\"\n */\n standardizeLocale(locale = this.targetLocale): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('standardizeLocale'));\n return this.localeConfig.standardizeLocale(locale);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same dialect.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same dialect, false otherwise\n *\n * @example\n * gt.isSameDialect('en-US', 'en-GB');\n * // Returns: false\n *\n * gt.isSameDialect('en', 'en-US');\n * // Returns: true\n */\n isSameDialect(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameDialect(...locales);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same language.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same language, false otherwise\n *\n * @example\n * gt.isSameLanguage('en-US', 'en-GB');\n * // Returns: true\n */\n isSameLanguage(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameLanguage(...locales);\n }\n\n /**\n * Checks if a locale is a superset of another locale.\n *\n * @param {string} superLocale - The locale to check if it is a superset\n * @param {string} subLocale - The locale to check if it is a subset\n * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise\n *\n * @example\n * gt.isSupersetLocale('en', 'en-US');\n * // Returns: true\n *\n * gt.isSupersetLocale('en-US', 'en');\n * // Returns: false\n */\n isSupersetLocale(superLocale: string, subLocale: string): boolean {\n return this.localeConfig.isSupersetLocale(superLocale, subLocale);\n }\n}\n"],"mappings":";;;;;AAEA,MAAM,YAAY;AAElB,MAAa,2BAA2B,YACtCA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,uCAAuC,QAAQ;CAC7D,KAAK;CACN,CAAC;AAEJ,MAAa,iCAAiC,UAC5CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS;CACV,CAAC;AAEJ,MAAa,YAAY,QAAgB,YAAoB,UAC3DA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,gCAAgC,OAAO,GAAG;CACxD,KAAK;CACL,SAAS;CACV,CAAC;AAE4BA,YAAAA,wBAAwB;CACtD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,+BAA+B,iBAC1CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,+BAA+B,iBAC1CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,4BAA4B,iBACvCA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,0BAA0B,aAAa;CAC7C,CAAC;AAEJ,MAAa,yBAAyB,iBACpCA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,wBAAwB,aAAa;CAC3C,CAAC;AAEJ,MAAa,sBAAsB,WACjCA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,WAAW,OAAO;C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AAI,kBAAkB,KAAK,cACzB,QAAO,KAAK,aAAa,mBAAmB,OAAO;AAErD,UAAA,GAAA,2BAAA,oBAA2B,QAAQ,cAAc;;;;;;;;;;;;;CAcnD,kBAAkB,SAAS,KAAK,cAAsB;AACpD,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,oBAAoB,CAAC;AACnE,SAAO,KAAK,aAAa,kBAAkB,OAAO;;;;;;;;;;;;;;;CAgBpD,cAAc,GAAG,SAAyC;AACxD,SAAO,KAAK,aAAa,cAAc,GAAG,QAAQ;;;;;;;;;;;;CAapD,eAAe,GAAG,SAAyC;AACzD,SAAO,KAAK,aAAa,eAAe,GAAG,QAAQ;;;;;;;;;;;;;;;;CAiBrD,iBAAiB,aAAqB,WAA4B;AAChE,SAAO,KAAK,aAAa,iBAAiB,aAAa,UAAU"}
1
+ {"version":3,"file":"runtime-wK7jzE9f.cjs","names":["createDiagnosticMessage","defaultTimeout","ApiError","API_VERSION","hashSource","LocaleConfig"],"sources":["../src/logging/errors.ts","../src/logging/logger.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/validateResponse.ts","../src/translate/utils/handleFetchError.ts","../src/translate/utils/generateRequestHeaders.ts","../src/translate/utils/apiRequest.ts","../src/translate/translateMany.ts","../src/runtime.ts"],"sourcesContent":["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 invalidAuthError = createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Authentication failed',\n fix: 'Check that your API key and project ID are correct',\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.\nexport const defaultLogger = 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 = defaultLogger.child('fetch');\nexport const gtInstanceLogger = defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps the fetch function with a timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeout - The timeout in milliseconds.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeout?: number\n) {\n const controller = new AbortController();\n const signal = controller.signal;\n\n timeout = timeout ? timeout : defaultTimeout;\n const timeoutId = timeout\n ? setTimeout(() => controller.abort(), timeout)\n : null;\n\n try {\n const response = await fetch(url, { ...options, signal });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw translationTimeoutError(timeout);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { apiError } from '../../logging/errors';\nimport { ApiError } from '../../errors/ApiError';\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 { fetchLogger } from '../../logging/logger';\nimport {\n translationRequestFailedError,\n translationTimeoutError,\n} from '../../logging/errors';\n\nexport function handleFetchError(error: unknown, timeout: number): never {\n if (error instanceof Error && error.name === 'AbortError') {\n const errorMessage = translationTimeoutError(timeout);\n fetchLogger.error(errorMessage);\n throw new Error(errorMessage);\n }\n const errorMessage = translationRequestFailedError(\n error instanceof Error ? error.message : String(error)\n );\n fetchLogger.error(errorMessage);\n throw error;\n}\n","import { TranslationRequestConfig } from '../../types';\nimport { API_VERSION } from '../api';\n\nexport function generateRequestHeaders(\n config: TranslationRequestConfig,\n excludeContentType = false\n) {\n const authHeaders: Record<string, string> = {\n ...(!excludeContentType && { 'Content-Type': 'application/json' }),\n 'gt-project-id': config.projectId,\n };\n\n if (config.apiKey) {\n authHeaders['Authorization'] = `Bearer ${config.apiKey}`;\n }\n\n authHeaders['gt-api-version'] = API_VERSION;\n\n return authHeaders;\n}\n","import { TranslationRequestConfig } from '../../types';\nimport { defaultBaseUrl } from '../../settings/settingsUrls';\nimport { defaultTimeout } from '../../settings/settings';\nimport { fetchWithTimeout } from './fetchWithTimeout';\nimport { validateResponse } from './validateResponse';\nimport { handleFetchError } from './handleFetchError';\nimport { generateRequestHeaders } from './generateRequestHeaders';\n\nconst MAX_RETRIES = 3;\nconst INITIAL_DELAY_MS = 500;\nconst RATE_LIMIT_RETRY_DELAY_MS = 60_000;\nconst MS_PER_SECOND = 1000;\n\ntype RetryPolicy = 'exponential' | 'linear' | 'none';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction getRetryDelay(policy: RetryPolicy, attempt: number): number {\n switch (policy) {\n case 'linear':\n return INITIAL_DELAY_MS * (attempt + 1);\n case 'exponential':\n return INITIAL_DELAY_MS * 2 ** attempt;\n default:\n return 0;\n }\n}\n\nfunction parseDelayMs(value: string | null): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const seconds = Number(value.split(',')[0].split(';')[0].trim());\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return seconds * MS_PER_SECOND;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n const delayMs = parseDelayMs(value);\n if (delayMs !== undefined) {\n return delayMs;\n }\n\n if (!value) {\n return undefined;\n }\n\n const retryDate = Date.parse(value);\n if (Number.isNaN(retryDate)) {\n return undefined;\n }\n\n return Math.max(retryDate - Date.now(), 0);\n}\n\nfunction getRateLimitRetryDelay(response: Response): number {\n return (\n parseRetryAfter(response.headers.get('Retry-After')) ??\n parseDelayMs(response.headers.get('RateLimit-Reset')) ??\n RATE_LIMIT_RETRY_DELAY_MS\n );\n}\n\nfunction getResponseRetryDelay(\n response: Response,\n policy: RetryPolicy,\n attempt: number\n): number {\n if (response.status === 429) {\n return getRateLimitRetryDelay(response);\n }\n\n return getRetryDelay(policy, attempt);\n}\n\n/**\n * @internal\n *\n * Makes an API request with automatic retry for 429 and 5XX errors.\n *\n * Encapsulates URL construction, fetch with timeout, error handling,\n * response validation, and JSON parsing.\n *\n * @param config - The configuration for the API call.\n * @param endpoint - The API endpoint path (e.g. '/v2/project/jobs/info')\n * @param options - Optional request options.\n * @returns The parsed JSON response.\n */\nexport async function apiRequest<T>(\n config: TranslationRequestConfig,\n endpoint: string,\n options?: {\n body?: unknown;\n timeout?: number;\n method?: 'GET' | 'POST';\n retryPolicy?: RetryPolicy;\n }\n): Promise<T> {\n const timeout = options?.timeout ?? defaultTimeout;\n const url = `${config.baseUrl || defaultBaseUrl}${endpoint}`;\n const method = options?.method ?? 'POST';\n const retryPolicy = options?.retryPolicy ?? 'exponential';\n const maxRetries = retryPolicy === 'none' ? 0 : MAX_RETRIES;\n\n const requestInit: RequestInit = {\n method,\n headers: generateRequestHeaders(config),\n };\n if (options?.body !== undefined) {\n requestInit.body = JSON.stringify(options.body);\n }\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n let response: Response;\n try {\n response = await fetchWithTimeout(url, requestInit, timeout);\n } catch (error) {\n if (attempt < maxRetries) {\n await sleep(getRetryDelay(retryPolicy, attempt));\n continue;\n }\n handleFetchError(error, timeout);\n }\n\n // Retry on rate limits and 5XX server errors.\n if (\n (response!.status === 429 || response!.status >= 500) &&\n attempt < maxRetries\n ) {\n await sleep(getResponseRetryDelay(response!, retryPolicy, attempt));\n continue;\n }\n\n await validateResponse(response!);\n return (await response!.json()) as T;\n }\n\n throw new Error('Max retries exceeded');\n}\n","import {\n TranslationRequestConfig,\n TranslateManyResult,\n TranslationResult,\n} from '../types';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n TranslateManyEntry,\n TranslateOptions,\n EntryMetadata,\n} from '../types-dir/api/entry';\nimport { apiRequest } from './utils/apiRequest';\nimport type { Content } from '@generaltranslation/format/types';\nimport { hashSource } from '../id';\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.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nexport async function _translateMany<\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 timeout?: number\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nexport async function _translateMany(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig,\n timeout?: number\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 dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n const response = await apiRequest<Record<string, TranslationResult>>(\n { ...config, baseUrl: config.baseUrl || defaultRuntimeApiUrl },\n `/v2/translate`,\n {\n body: {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: globalMetadata,\n },\n timeout: timeout,\n retryPolicy: 'none',\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","// `generaltranslation` language toolkit\n// © 2026, General Translation, Inc.\n\n// ----- IMPORTS ----- //\n\nimport {\n LocaleConfig,\n determineLocale as _determineLocale,\n getRegionProperties as _getRegionProperties,\n isValidLocale as _isValidLocale,\n requiresTranslation as _requiresTranslation,\n resolveAliasLocale as _resolveAliasLocale,\n resolveCanonicalLocale as _resolveCanonicalLocale,\n standardizeLocale as _standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n CustomMapping,\n CustomRegionMapping,\n CutoffFormatOptions,\n FormatVariables,\n LocaleProperties,\n StringFormat,\n} from '@generaltranslation/format/types';\nimport {\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n TranslateManyEntry,\n} from './types';\nimport { libraryDefaultLocale } from './settings/settings';\nimport {\n noSourceLocaleProvidedError,\n noTargetLocaleProvidedError,\n invalidLocaleError,\n invalidLocalesError,\n noProjectIdProvidedError,\n noApiKeyProvidedError,\n} from './logging/errors';\nimport { gtInstanceLogger } from './logging/logger';\nimport { _translateMany } from './translate/translateMany';\nimport { TranslateOptions } from './types-dir/api/entry';\n\n// ============================================================ //\n// Runtime Class //\n// ============================================================ //\n/**\n * Type representing the constructor parameters for the GT and GTRuntime classes.\n * @typedef {Object} GTConstructorParams\n * @property {string} [apiKey] - The API key for accessing the translation service\n * @property {string} [devApiKey] - The development API key for accessing the translation service\n * @property {string} [sourceLocale] - The default source locale for translations\n * @property {string} [targetLocale] - The default target locale for translations\n * @property {string[]} [locales] - Array of supported locales\n * @property {string} [projectId] - The project ID for the translation service\n * @property {string} [baseUrl] - The base URL for the translation service\n * @property {CustomMapping} [customMapping] - Custom mapping of locale codes to their names\n */\nexport type GTConstructorParams = {\n apiKey?: string;\n devApiKey?: string;\n sourceLocale?: string;\n targetLocale?: string;\n locales?: string[];\n projectId?: string;\n baseUrl?: string;\n customMapping?: CustomMapping;\n};\n\n/**\n * GTRuntime is the runtime core of the GT driver: locale management,\n * formatting, and runtime translation requests.\n *\n * Browser-facing SDK code constructs this class (via `generaltranslation/runtime`)\n * so production bundles do not ship the project/file management API client\n * that lives on the GT class exported from the main entry.\n *\n * @example\n * const gt = new GTRuntime({\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\nexport class GTRuntime {\n /** Base URL for the translation service API */\n baseUrl?: string;\n\n /** Project ID for the translation service */\n projectId?: string;\n\n /** API key for accessing the translation service */\n apiKey?: string;\n\n /** Development API key for accessing the translation service */\n devApiKey?: string;\n\n /** Source locale for translations */\n sourceLocale?: string;\n\n /** Target locale for translations */\n targetLocale?: string;\n\n /** Array of supported locales */\n locales?: string[];\n\n /** Custom mapping for locale codes to their names */\n customMapping?: CustomMapping;\n\n /** Lazily derived reverse custom mapping for alias locales */\n reverseCustomMapping?: Record<string, string>;\n\n /** Lazily derived custom mapping for regions */\n customRegionMapping?: CustomRegionMapping;\n\n /** Runtime-safe locale and formatting helpers (backing field) */\n private _localeConfig!: LocaleConfig;\n\n /** Runtime-safe locale and formatting helpers */\n get localeConfig() {\n return this._localeConfig;\n }\n\n /**\n * Constructs an instance of the GTRuntime class.\n *\n * @param {GTConstructorParams} [params] - The parameters for initializing the GTRuntime instance\n * @throws {Error} If an invalid locale is provided\n * @throws {Error} If any of the provided locales are invalid\n *\n * @example\n * const gt = new GTRuntime({\n * apiKey: 'your-api-key',\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\n constructor(params: GTConstructorParams = {}) {\n // Read environment\n if (typeof process !== 'undefined') {\n this.apiKey ||= process.env?.GT_API_KEY;\n this.devApiKey ||= process.env?.GT_DEV_API_KEY;\n this.projectId ||= process.env?.GT_PROJECT_ID;\n }\n // Set up config\n this.setConfig(params);\n }\n\n setConfig({\n apiKey,\n devApiKey,\n sourceLocale,\n targetLocale,\n locales,\n projectId,\n customMapping,\n baseUrl,\n }: GTConstructorParams) {\n // ----- Environment properties ----- //\n if (apiKey) this.apiKey = apiKey;\n if (devApiKey) this.devApiKey = devApiKey;\n if (projectId) this.projectId = projectId;\n\n // ----- Standardize locales ----- //\n\n // source locale\n if (sourceLocale) {\n this.sourceLocale = _standardizeLocale(sourceLocale);\n if (!_isValidLocale(this.sourceLocale, customMapping))\n throw new Error(invalidLocaleError(this.sourceLocale));\n }\n\n // target locale\n if (targetLocale) {\n this.targetLocale = _standardizeLocale(targetLocale);\n if (!_isValidLocale(this.targetLocale, customMapping))\n throw new Error(invalidLocaleError(this.targetLocale));\n }\n\n // locales\n if (locales) {\n const result: string[] = [];\n const invalidLocales: string[] = [];\n locales.forEach((locale) => {\n const standardizedLocale = _standardizeLocale(locale);\n if (_isValidLocale(standardizedLocale)) {\n result.push(standardizedLocale);\n } else {\n invalidLocales.push(locale);\n }\n });\n if (invalidLocales.length > 0) {\n throw new Error(invalidLocalesError(invalidLocales));\n }\n this.locales = result;\n }\n\n // ----- Other properties ----- //\n if (baseUrl) this.baseUrl = baseUrl;\n if (customMapping) {\n this.customMapping = customMapping;\n this.reverseCustomMapping = Object.fromEntries(\n Object.entries(customMapping)\n .filter(\n ([, value]) => value && typeof value === 'object' && 'code' in value\n )\n .map(([key, value]) => [(value as { code: string }).code, key])\n );\n }\n this._localeConfig = new LocaleConfig({\n defaultLocale: this.sourceLocale,\n locales: this.locales ?? [],\n customMapping: this.customMapping,\n });\n }\n\n // -------------- Private Methods -------------- //\n\n protected _getTranslationConfig(): TranslationRequestConfig {\n return {\n baseUrl: this.baseUrl,\n apiKey: this.apiKey || this.devApiKey,\n projectId: this.projectId || '',\n };\n }\n\n protected _validateAuth(functionName: string) {\n const errors: string[] = [];\n if (!this.apiKey && !this.devApiKey) {\n const error = noApiKeyProvidedError(functionName);\n errors.push(error);\n }\n if (!this.projectId) {\n const error = noProjectIdProvidedError(functionName);\n errors.push(error);\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n }\n\n /**\n * Translates a single source string to the target locale.\n * Routes through {@link translateMany} under the hood.\n *\n * @param {string} source - The source string to translate.\n * @param {object} options - Translation options including targetLocale and optional entry metadata.\n * @returns {Promise<TranslationResult | TranslationError>} The translated content.\n *\n * @example\n * const result = await gt.translate('Hello, world!', { targetLocale: 'es' });\n *\n * @example\n * const result = await gt.translate('Hello, world!', {\n * targetLocale: 'es',\n * dataFormat: 'ICU',\n * context: 'A formal greeting',\n * });\n */\n async translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslationResult | TranslationError> {\n // Normalize string shorthand to options object\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n // Validation\n this._validateAuth('translate');\n\n // Require target locale\n let targetLocale = options?.targetLocale || this.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError('translate');\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n // Replace target locale with canonical locale\n targetLocale = this.resolveCanonicalLocale(targetLocale);\n\n const sourceLocale = this.resolveCanonicalLocale(\n options?.sourceLocale || this.sourceLocale || libraryDefaultLocale\n );\n\n // Request the translation.\n const results = await _translateMany(\n [source],\n {\n ...options,\n targetLocale,\n sourceLocale,\n },\n this._getTranslationConfig(),\n timeout\n );\n return results[0];\n }\n\n /**\n * Translates multiple source strings to the target locale.\n * Each entry can be a plain string or an object with source and metadata fields.\n *\n * @param {TranslateManyEntry[] | Record<string, TranslateManyEntry>} sources - The source entries to translate. Can be an array or a record keyed by hash.\n * @param {object} options - Translation options including targetLocale.\n * @returns {Promise<TranslateManyResult | Record<string, TranslationResult>>} The translated contents. An array if sources was an array, a record if sources was a record.\n *\n * @example\n * const result = await gt.translateMany(\n * ['Hello, world!', 'Goodbye, world!'],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * [{ source: 'Hello, world!', dataFormat: 'ICU' }],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * { 'my-hash': 'Hello, world!' },\n * { targetLocale: 'es' }\n * );\n */\n async translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult>;\n async translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<Record<string, TranslationResult>>;\n async translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n // Normalize string shorthand to options object\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n // Validation\n this._validateAuth('translateMany');\n\n // Require target locale\n let targetLocale = options?.targetLocale || this.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError('translateMany');\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n // Replace target locale with canonical locale\n targetLocale = this.resolveCanonicalLocale(targetLocale);\n\n const sourceLocale = this.resolveCanonicalLocale(\n options?.sourceLocale || this.sourceLocale || libraryDefaultLocale\n );\n\n // Request the translation.\n return await _translateMany(\n sources,\n {\n ...options,\n targetLocale,\n sourceLocale,\n },\n this._getTranslationConfig(),\n timeout\n );\n }\n\n // -------------- Formatting -------------- //\n\n /**\n * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.\n *\n * This method uses the GT instance's rendering locales by default for locale-specific terminator selection,\n * but can be overridden with custom locales in the options.\n *\n * @param {string} value - The string value to format with cutoff behavior.\n * @param {Object} [options] - Configuration options for cutoff formatting.\n * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.\n * @param {number} [options.maxChars] - The maximum number of characters to display.\n * - Undefined values are treated as no cutoff.\n * - Negative values follow .slice() behavior and terminator will be added before the value.\n * - 0 will result in an empty string.\n * - If cutoff results in an empty string, no terminator is added.\n * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.\n * @param {string} [options.terminator] - Optional override the terminator to use.\n * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.\n * - If no terminator is provided, then separator is ignored.\n * @returns {string} The formatted string with terminator applied if cutoff occurs.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.formatCutoff('Hello, world!', { maxChars: 8 });\n * // Returns: 'Hello, w...'\n *\n * @example\n * gt.formatCutoff('Hello, world!', { maxChars: -3 });\n * // Returns: '...ld!'\n */\n formatCutoff(\n value: string,\n options?: {\n locales?: string | string[];\n } & CutoffFormatOptions\n ): string {\n return this.localeConfig.formatCutoff(value, this.targetLocale, options);\n }\n\n /**\n * Formats a message according to the specified locales and options.\n *\n * @param {string} message - The message to format.\n * @param {string | string[]} [locales='en'] - The locales to use for formatting.\n * @param {FormatVariables} [variables={}] - The variables to use for formatting.\n * @param {StringFormat} [dataFormat='ICU'] - The format of the message.\n * @returns {string} The formatted message.\n *\n * @example\n * gt.formatMessage('Hello {name}', { name: 'John' });\n * // Returns: \"Hello John\"\n *\n * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });\n * // Returns: \"Bonjour John\"\n */\n formatMessage(\n message: string,\n options?: {\n locales?: string | string[];\n variables?: FormatVariables;\n dataFormat?: StringFormat;\n }\n ): string {\n return this.localeConfig.formatMessage(message, this.targetLocale, options);\n }\n /**\n * Formats a number according to the specified locales and options.\n *\n * @param {number} number - The number to format.\n * @param {Object} [options] - Additional options for number formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted number.\n *\n * @example\n * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });\n * // Returns: \"$1,234.56\"\n */\n formatNum(\n number: number,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatNum(number, this.targetLocale, options);\n }\n\n /**\n * Formats a date according to the specified locales and options.\n *\n * @param {Date} date - The date to format.\n * @param {Object} [options] - Additional options for date formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options.\n * @returns {string} The formatted date.\n *\n * @example\n * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });\n * // Returns: \"Thursday, March 14, 2024 at 2:30:45 PM GMT-7\"\n */\n formatDateTime(\n date: Date,\n options?: {\n locales?: string | string[];\n } & Intl.DateTimeFormatOptions\n ): string {\n return this.localeConfig.formatDateTime(date, this.targetLocale, options);\n }\n\n /**\n * Formats a currency value according to the specified locales and options.\n *\n * @param {number} value - The currency value to format.\n * @param {string} currency - The currency code (e.g., 'USD', 'EUR')\n * @param {Object} [options] - Additional options for currency formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted currency value.\n *\n * @example\n * gt.formatCurrency(1234.56, 'USD', { style: 'currency' });\n * // Returns: \"$1,234.56\"\n */\n formatCurrency(\n value: number,\n currency: string,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatCurrency(\n value,\n currency,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n *\n * @param {Array<string | number>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {string} The formatted list.\n *\n * @example\n * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });\n * // Returns: \"apple, banana, and orange\"\n */\n formatList(\n array: Array<string | number>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ) {\n return this.localeConfig.formatList(array, this.targetLocale, options);\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n * @param {Array<T>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {Array<T | string>} The formatted list parts.\n *\n * @example\n * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });\n * // Returns: ['apple', ', ', 42, ' and ', '{ foo: \"bar\" }']\n */\n formatListToParts<T>(\n array: Array<T>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ): Array<T | string> {\n return this.localeConfig.formatListToParts<T>(\n array,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time value according to the specified locales and options.\n *\n * @param {number} value - The relative time value to format.\n * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')\n * @param {Object} options - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.\n * @returns {string} The formatted relative time string.\n *\n * @example\n * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });\n * // Returns: \"yesterday\"\n */\n formatRelativeTime(\n value: number,\n unit: Intl.RelativeTimeFormatUnit,\n options?: {\n locales?: string | string[];\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTime(\n value,\n unit,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time string from a Date, automatically selecting the best unit.\n *\n * @param {Date} date - The date to format relative to now.\n * @param {Object} [options] - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @returns {string} The formatted relative time string (e.g., \"2 hours ago\", \"in 3 days\")\n *\n * @example\n * gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));\n * // Returns: \"1 hour ago\"\n */\n formatRelativeTimeFromDate(\n date: Date,\n options?: {\n locales?: string | string[];\n baseDate?: Date;\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTimeFromDate(\n date,\n this.targetLocale,\n options\n );\n }\n\n // -------------- Locale Properties -------------- //\n\n /**\n * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {string} The display name corresponding to the code.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleName('es-ES');\n * // Returns: \"Spanish (Spain)\"\n */\n getLocaleName(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleName'));\n return this.localeConfig.getLocaleName(locale);\n }\n\n /**\n * Retrieves an emoji based on a given locale code.\n * Uses the locale's region (if present) to select an emoji or falls back on default emojis.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')\n * @returns {string} The emoji representing the locale or its region.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleEmoji('es-ES');\n * // Returns: \"🇪🇸\"\n */\n getLocaleEmoji(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleEmoji'));\n return this.localeConfig.getLocaleEmoji(locale);\n }\n\n /**\n * Generates linguistic details for a given locale code.\n *\n * This function returns information about the locale,\n * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).\n * The function provides these names in both your default language and native forms, and an associated emoji.\n *\n * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., \"de-AT\").\n * @returns {LocaleProperties} - An object containing detailed information about the locale.\n *\n * @property {string} code - The full locale code, e.g., \"de-AT\".\n * @property {string} name - Language name in the default display language, e.g., \"Austrian German\".\n * @property {string} nativeName - Language name in the locale's native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} languageCode - The base language code, e.g., \"de\".\n * @property {string} languageName - The language name in the default display language, e.g., \"German\".\n * @property {string} nativeLanguageName - The language name in the native language, e.g., \"Deutsch\".\n * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., \"German (AT)\".\n * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., \"Deutsch (AT)\".\n * @property {string} regionCode - The region code from maximization, e.g., \"AT\".\n * @property {string} regionName - The region name in the default display language, e.g., \"Austria\".\n * @property {string} nativeRegionName - The region name in the native language, e.g., \"Österreich\".\n * @property {string} scriptCode - The script code from maximization, e.g., \"Latn\".\n * @property {string} scriptName - The script name in the default display language, e.g., \"Latin\".\n * @property {string} nativeScriptName - The script name in the native language, e.g., \"Lateinisch\".\n * @property {string} maximizedCode - The maximized locale code, e.g., \"de-Latn-AT\".\n * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., \"Austrian German (Latin)\".\n * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., \"Österreichisches Deutsch (Lateinisch)\".\n * @property {string} minimizedCode - Minimized locale code, e.g., \"de-AT\" (or \"de\" for \"de-DE\").\n * @property {string} minimizedName - Minimized language name in the default language, e.g., \"Austrian German\".\n * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} emoji - The emoji associated with the locale's region, if applicable.\n */\n getLocaleProperties(locale = this.targetLocale): LocaleProperties {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleProperties'));\n return this.localeConfig.getLocaleProperties(locale);\n }\n\n /**\n * Retrieves multiple properties for a given region code, including:\n * - `code`: the original region code\n * - `name`: the localized display name\n * - `emoji`: the associated flag or symbol\n *\n * Behavior:\n * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `\"US\"`, `\"FR\"`, `\"419\"`).\n * - Uses the instance's `targetLocale` to localize the region name for the user.\n * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.\n * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.\n * - Falls back to the region code as `name` if display name resolution fails.\n * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.\n *\n * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `\"US\"`, `\"GB\"`, `\"DE\"`).\n * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.\n * @returns {{ code: string, name: string, emoji: string }} An object containing:\n * - `code`: the input region code\n * - `name`: the localized or custom region name\n * - `emoji`: the matching emoji flag or symbol\n *\n * @throws {Error} If no target locale is available to determine region properties.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'fr-FR' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }\n *\n * @example\n * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });\n * // => { code: 'US', name: 'USA', emoji: '🗽' }\n */\n getRegionProperties(\n region = this.getLocaleProperties().regionCode,\n customMapping?: CustomRegionMapping\n ): { code: string; name: string; emoji: string } {\n if (!customMapping) {\n if (this.customMapping && !this.customRegionMapping) {\n // Lazy derive custom region mapping from customMapping\n const customRegionMapping: CustomRegionMapping = {};\n for (const [locale, lp] of Object.entries(this.customMapping)) {\n if (\n lp &&\n typeof lp === 'object' &&\n lp.regionCode &&\n !customRegionMapping[lp.regionCode]\n ) {\n const { regionName: name, emoji } = lp;\n customRegionMapping[lp.regionCode] = {\n locale,\n ...(name && { name }),\n ...(emoji && { emoji }),\n };\n }\n }\n this.customRegionMapping = customRegionMapping;\n }\n customMapping = this.customRegionMapping;\n }\n return _getRegionProperties(\n region,\n this.targetLocale, // this.targetLocale because we want it in the user's language\n customMapping\n );\n }\n\n /**\n * Determines whether a translation is required based on the source and target locales.\n *\n * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content.\n * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into.\n * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales.\n * @returns {boolean} True if translation is required, false otherwise\n * @throws {Error} If no source locale is provided.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.requiresTranslation('en-US', 'es-ES');\n * // Returns: true\n */\n requiresTranslation(\n sourceLocale = this.sourceLocale,\n targetLocale = this.targetLocale,\n approvedLocales: string[] | undefined = this.locales,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!sourceLocale)\n throw new Error(noSourceLocaleProvidedError('requiresTranslation'));\n if (!targetLocale)\n throw new Error(noTargetLocaleProvidedError('requiresTranslation'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.requiresTranslation(\n targetLocale,\n sourceLocale,\n approvedLocales\n );\n }\n return _requiresTranslation(\n sourceLocale,\n targetLocale,\n approvedLocales,\n customMapping\n );\n }\n\n /**\n * Determines the best matching locale from the provided approved locales list.\n *\n * @param {string | string[]} locales - A single locale or array of locales in preference order.\n * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order.\n * @returns {string | undefined} The best matching locale, or undefined if no match is found.\n *\n * @example\n * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);\n * // Returns: \"fr-FR\"\n */\n determineLocale(\n locales: string | string[],\n approvedLocales: string[] | undefined = this.locales || [],\n customMapping: CustomMapping | undefined = this.customMapping\n ): string | undefined {\n if (customMapping === this.customMapping) {\n return this.localeConfig.determineLocale(locales, approvedLocales ?? []);\n }\n return _determineLocale(locales, approvedLocales, customMapping);\n }\n\n /**\n * Gets the text direction for a given locale code.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left; otherwise 'ltr'.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleDirection('ar-SA');\n * // Returns: \"rtl\"\n */\n getLocaleDirection(locale = this.targetLocale): 'ltr' | 'rtl' {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleDirection'));\n return this.localeConfig.getLocaleDirection(locale);\n }\n\n /**\n * Checks if a given BCP 47 locale code is valid.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate.\n * @param {CustomMapping} [customMapping=this.customMapping] - The custom mapping to use for validation.\n * @returns {boolean} True if the locale code is valid, false otherwise\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.isValidLocale('en-US');\n * // Returns: true\n */\n isValidLocale(\n locale = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!locale) throw new Error(noTargetLocaleProvidedError('isValidLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.isValidLocale(locale);\n }\n return _isValidLocale(locale, customMapping);\n }\n\n /**\n * Resolves the canonical locale for a given locale.\n * @param locale - The locale to resolve the canonical locale for\n * @param customMapping - The custom mapping to use for resolving the canonical locale\n * @returns The canonical locale, or the input locale when no canonical mapping exists.\n */\n resolveCanonicalLocale(\n locale: string | undefined = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveCanonicalLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveCanonicalLocale(locale);\n }\n return _resolveCanonicalLocale(locale, customMapping);\n }\n\n /**\n * Resolves the alias locale for a given locale.\n * @param locale - The locale to resolve the alias locale for\n * @param customMapping - The custom mapping to use for resolving the alias locale\n * @returns The configured alias for a canonical locale, or the input locale when already an alias or no alias mapping exists.\n */\n resolveAliasLocale(\n locale: string,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveAliasLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveAliasLocale(locale);\n }\n return _resolveAliasLocale(locale, customMapping);\n }\n\n /**\n * Standardizes a BCP 47 locale code to ensure correct formatting.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize.\n * @returns {string} The standardized locale code, or the input string if it cannot be standardized.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.standardizeLocale('en_us');\n * // Returns: \"en-US\"\n */\n standardizeLocale(locale = this.targetLocale): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('standardizeLocale'));\n return this.localeConfig.standardizeLocale(locale);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same dialect.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same dialect, false otherwise\n *\n * @example\n * gt.isSameDialect('en-US', 'en-GB');\n * // Returns: false\n *\n * gt.isSameDialect('en', 'en-US');\n * // Returns: true\n */\n isSameDialect(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameDialect(...locales);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same language.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same language, false otherwise\n *\n * @example\n * gt.isSameLanguage('en-US', 'en-GB');\n * // Returns: true\n */\n isSameLanguage(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameLanguage(...locales);\n }\n\n /**\n * Checks if a locale is a superset of another locale.\n *\n * @param {string} superLocale - The locale to check if it is a superset\n * @param {string} subLocale - The locale to check if it is a subset\n * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise\n *\n * @example\n * gt.isSupersetLocale('en', 'en-US');\n * // Returns: true\n *\n * gt.isSupersetLocale('en-US', 'en');\n * // Returns: false\n */\n isSupersetLocale(superLocale: string, subLocale: string): boolean {\n return this.localeConfig.isSupersetLocale(superLocale, subLocale);\n }\n}\n"],"mappings":";;;;;AAEA,MAAM,YAAY;AAElB,MAAa,2BAA2B,YACtCA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,uCAAuC,QAAQ;CAC7D,KAAK;CACN,CAAC;AAEJ,MAAa,iCAAiC,UAC5CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS;CACV,CAAC;AAEJ,MAAa,YAAY,QAAgB,YAAoB,UAC3DA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,gCAAgC,OAAO,GAAG;CACxD,KAAK;CACL,SAAS;CACV,CAAC;AAE4BA,YAAAA,wBAAwB;CACtD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,+BAA+B,iBAC1CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,+BAA+B,iBAC1CA,YAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAE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,cAAc;;;;;;;;CAS9C,uBACE,SAA6B,KAAK,cAClC,gBAA2C,KAAK,eACxC;AACR,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,yBAAyB,CAAC;AACxE,MAAI,kBAAkB,KAAK,cACzB,QAAO,KAAK,aAAa,uBAAuB,OAAO;AAEzD,UAAA,GAAA,2BAAA,wBAA+B,QAAQ,cAAc;;;;;;;;CASvD,mBACE,QACA,gBAA2C,KAAK,eACxC;AACR,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,qBAAqB,CAAC;AACpE,MAAI,kBAAkB,KAAK,cACzB,QAAO,KAAK,aAAa,mBAAmB,OAAO;AAErD,UAAA,GAAA,2BAAA,oBAA2B,QAAQ,cAAc;;;;;;;;;;;;;CAcnD,kBAAkB,SAAS,KAAK,cAAsB;AACpD,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,oBAAoB,CAAC;AACnE,SAAO,KAAK,aAAa,kBAAkB,OAAO;;;;;;;;;;;;;;;CAgBpD,cAAc,GAAG,SAAyC;AACxD,SAAO,KAAK,aAAa,cAAc,GAAG,QAAQ;;;;;;;;;;;;CAapD,eAAe,GAAG,SAAyC;AACzD,SAAO,KAAK,aAAa,eAAe,GAAG,QAAQ;;;;;;;;;;;;;;;;CAiBrD,iBAAiB,aAAqB,WAA4B;AAChE,SAAO,KAAK,aAAa,iBAAiB,aAAa,UAAU"}
package/dist/runtime.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_runtime = require("./runtime-DVD9hQXj.cjs");
2
+ const require_runtime = require("./runtime-wK7jzE9f.cjs");
3
3
  exports.GTRuntime = require_runtime.GTRuntime;
@@ -1,4 +1,4 @@
1
- import { G as TranslateManyResult, K as TranslationError, Tt as TranslateOptions, q as TranslationResult, wt as TranslateManyEntry, x as TranslationRequestConfig } from "./types-DboOaYN_.cjs";
1
+ import { Dt as TranslateManyEntry, G as TranslateManyResult, K as TranslationError, Ot as TranslateOptions, q as TranslationResult, x as TranslationRequestConfig } from "./types-iLf0drw8.cjs";
2
2
  import { CustomMapping, CustomRegionMapping, CutoffFormatOptions, FormatVariables, LocaleProperties, StringFormat } from "@generaltranslation/format/types";
3
3
  import { LocaleConfig } from "@generaltranslation/format";
4
4
 
@@ -1,4 +1,4 @@
1
- import { G as TranslateManyResult, K as TranslationError, Tt as TranslateOptions, q as TranslationResult, wt as TranslateManyEntry, x as TranslationRequestConfig } from "./types-CHNhO-Lt.mjs";
1
+ import { Dt as TranslateManyEntry, G as TranslateManyResult, K as TranslationError, Ot as TranslateOptions, q as TranslationResult, x as TranslationRequestConfig } from "./types-CzFzXgUO.mjs";
2
2
  import { LocaleConfig } from "@generaltranslation/format";
3
3
  import { CustomMapping, CustomRegionMapping, CutoffFormatOptions, FormatVariables, LocaleProperties, StringFormat } from "@generaltranslation/format/types";
4
4
 
package/dist/runtime.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as GTRuntime } from "./runtime-vpAQMY2e.mjs";
1
+ import { t as GTRuntime } from "./runtime-WSpZppgm.mjs";
2
2
  export { GTRuntime };
@@ -1,3 +1,5 @@
1
+ import type { FileReference } from '../types-dir/api/file';
2
+ export type SetupProjectFileReference = Pick<FileReference, 'branchId' | 'fileId' | 'versionId'>;
1
3
  export type SetupProjectResult = {
2
4
  setupJobId: string;
3
5
  status: 'queued';
@@ -43,6 +43,11 @@ type TranslateManyEntry = string | {
43
43
  //#region src/id/types.d.ts
44
44
  type HashMetadata = {
45
45
  context?: string;
46
+ /**
47
+ * @deprecated Custom IDs are not used by current translation tooling. This
48
+ * field will be removed in the next major version. Omit it to use the
49
+ * content-based hash.
50
+ */
46
51
  id?: string;
47
52
  maxChars?: number;
48
53
  requiresReview?: boolean;
@@ -250,6 +255,20 @@ type CreateTagResult = {
250
255
  };
251
256
  };
252
257
  //#endregion
258
+ //#region src/translate/setupProject.d.ts
259
+ type SetupProjectFileReference = Pick<FileReference, 'branchId' | 'fileId' | 'versionId'>;
260
+ type SetupProjectResult = {
261
+ setupJobId: string;
262
+ status: 'queued';
263
+ } | {
264
+ status: 'completed';
265
+ };
266
+ type SetupProjectOptions = {
267
+ force?: boolean;
268
+ locales?: string[];
269
+ timeoutMs?: number;
270
+ };
271
+ //#endregion
253
272
  //#region src/types-dir/api/uploadFiles.d.ts
254
273
  /**
255
274
  * Metadata stored alongside GTJSON file entries.
@@ -533,5 +552,5 @@ type TranslationRequestConfig = {
533
552
  apiKey?: string;
534
553
  };
535
554
  //#endregion
536
- export { UploadFilesOptions as $, AwaitJobsOptions as A, OrphanedFile as B, VariableType as C, RuntimeTranslateManyOptions as Ct, VariableTransformationSuffix as D, TransformationPrefix as E, MoveMapping as F, TranslateManyResult as G, FileDataResult as H, MoveResult as I, TranslationResultReference as J, TranslationError as K, ProcessMovesOptions as L, JobResult as M, CheckJobStatusResult as N, SubmitUserEditDiff as O, JobStatus as P, FileUpload as Q, ProcessMovesResponse as R, Variable as S, EntryMetadata as St, Transformation as T, TranslateOptions as Tt, BranchQuery as U, FileDataQuery as V, BranchDataResult as W, PublishFileEntry as X, DownloadFileOptions as Y, PublishFilesResult as Z, Metadata as _, JsonObject as _t, DataFormat$1 as a, DownloadFileBatchRequest as at, StringMessage$1 as b, HashMetadata as bt, HTML_CONTENT_PROPS as c, FileFormat as ct, I18nextMessage$1 as d, FileToUpload as dt, UploadFilesResponse as et, IcuMessage$1 as f, EnqueueFilesResult as ft, LocaleProperties$1 as g, FileQueryResult as gt, JsxElement as h, FileQuery as ht, CutoffFormatOptions$1 as i, DownloadFileBatchOptions as it, AwaitJobsResult as j, SubmitUserEditDiffsPayload as k, HtmlContentPropKeysRecord as l, FileReference as lt, JsxChildren$1 as m, CheckFileTranslationsOptions as mt, CustomMapping$1 as n, CreateTagResult as nt, FormatVariables$1 as o, DownloadFileBatchResult as ot, JsxChild as p, Updates as pt, TranslationResult as q, CustomRegionMapping$1 as r, EnqueueFilesOptions as rt, GTProp as s, DownloadedFile as st, Content as t, CreateTagOptions as tt, HtmlContentPropValuesRecord as u, FileReferenceIds as ut, StringContent as v, JsonPrimitive as vt, InjectionType as w, TranslateManyEntry as wt, TranslationRequestConfig as x, ActionType as xt, StringFormat$1 as y, JsonValue as yt, GetOrphanedFilesResult as z };
537
- //# sourceMappingURL=types-CHNhO-Lt.d.mts.map
555
+ export { UploadFilesOptions as $, AwaitJobsOptions as A, OrphanedFile as B, VariableType as C, HashMetadata as Ct, VariableTransformationSuffix as D, TranslateManyEntry as Dt, TransformationPrefix as E, RuntimeTranslateManyOptions as Et, MoveMapping as F, TranslateManyResult as G, FileDataResult as H, MoveResult as I, TranslationResultReference as J, TranslationError as K, ProcessMovesOptions as L, JobResult as M, CheckJobStatusResult as N, SubmitUserEditDiff as O, TranslateOptions as Ot, JobStatus as P, FileUpload as Q, ProcessMovesResponse as R, Variable as S, JsonValue as St, Transformation as T, EntryMetadata as Tt, BranchQuery as U, FileDataQuery as V, BranchDataResult as W, PublishFileEntry as X, DownloadFileOptions as Y, PublishFilesResult as Z, Metadata as _, CheckFileTranslationsOptions as _t, DataFormat$1 as a, CreateTagResult as at, StringMessage$1 as b, JsonObject as bt, HTML_CONTENT_PROPS as c, DownloadFileBatchRequest as ct, I18nextMessage$1 as d, FileFormat as dt, UploadFilesResponse as et, IcuMessage$1 as f, FileReference as ft, LocaleProperties$1 as g, Updates as gt, JsxElement as h, EnqueueFilesResult as ht, CutoffFormatOptions$1 as i, CreateTagOptions as it, AwaitJobsResult as j, SubmitUserEditDiffsPayload as k, HtmlContentPropKeysRecord as l, DownloadFileBatchResult as lt, JsxChildren$1 as m, FileToUpload as mt, CustomMapping$1 as n, SetupProjectOptions as nt, FormatVariables$1 as o, EnqueueFilesOptions as ot, JsxChild as p, FileReferenceIds as pt, TranslationResult as q, CustomRegionMapping$1 as r, SetupProjectResult as rt, GTProp as s, DownloadFileBatchOptions as st, Content as t, SetupProjectFileReference as tt, HtmlContentPropValuesRecord as u, DownloadedFile as ut, StringContent as v, FileQuery as vt, InjectionType as w, ActionType as wt, TranslationRequestConfig as x, JsonPrimitive as xt, StringFormat$1 as y, FileQueryResult as yt, GetOrphanedFilesResult as z };
556
+ //# sourceMappingURL=types-CzFzXgUO.d.mts.map
@@ -43,6 +43,11 @@ type TranslateManyEntry = string | {
43
43
  //#region src/id/types.d.ts
44
44
  type HashMetadata = {
45
45
  context?: string;
46
+ /**
47
+ * @deprecated Custom IDs are not used by current translation tooling. This
48
+ * field will be removed in the next major version. Omit it to use the
49
+ * content-based hash.
50
+ */
46
51
  id?: string;
47
52
  maxChars?: number;
48
53
  requiresReview?: boolean;
@@ -250,6 +255,20 @@ type CreateTagResult = {
250
255
  };
251
256
  };
252
257
  //#endregion
258
+ //#region src/translate/setupProject.d.ts
259
+ type SetupProjectFileReference = Pick<FileReference, 'branchId' | 'fileId' | 'versionId'>;
260
+ type SetupProjectResult = {
261
+ setupJobId: string;
262
+ status: 'queued';
263
+ } | {
264
+ status: 'completed';
265
+ };
266
+ type SetupProjectOptions = {
267
+ force?: boolean;
268
+ locales?: string[];
269
+ timeoutMs?: number;
270
+ };
271
+ //#endregion
253
272
  //#region src/types-dir/api/uploadFiles.d.ts
254
273
  /**
255
274
  * Metadata stored alongside GTJSON file entries.
@@ -533,5 +552,5 @@ type TranslationRequestConfig = {
533
552
  apiKey?: string;
534
553
  };
535
554
  //#endregion
536
- export { UploadFilesOptions as $, AwaitJobsOptions as A, OrphanedFile as B, VariableType as C, RuntimeTranslateManyOptions as Ct, VariableTransformationSuffix as D, TransformationPrefix as E, MoveMapping as F, TranslateManyResult as G, FileDataResult as H, MoveResult as I, TranslationResultReference as J, TranslationError as K, ProcessMovesOptions as L, JobResult as M, CheckJobStatusResult as N, SubmitUserEditDiff as O, JobStatus as P, FileUpload as Q, ProcessMovesResponse as R, Variable as S, EntryMetadata as St, Transformation as T, TranslateOptions as Tt, BranchQuery as U, FileDataQuery as V, BranchDataResult as W, PublishFileEntry as X, DownloadFileOptions as Y, PublishFilesResult as Z, Metadata as _, JsonObject as _t, DataFormat$1 as a, DownloadFileBatchRequest as at, StringMessage$1 as b, HashMetadata as bt, HTML_CONTENT_PROPS as c, FileFormat as ct, I18nextMessage$1 as d, FileToUpload as dt, UploadFilesResponse as et, IcuMessage$1 as f, EnqueueFilesResult as ft, LocaleProperties$1 as g, FileQueryResult as gt, JsxElement as h, FileQuery as ht, CutoffFormatOptions$1 as i, DownloadFileBatchOptions as it, AwaitJobsResult as j, SubmitUserEditDiffsPayload as k, HtmlContentPropKeysRecord as l, FileReference as lt, JsxChildren$1 as m, CheckFileTranslationsOptions as mt, CustomMapping$1 as n, CreateTagResult as nt, FormatVariables$1 as o, DownloadFileBatchResult as ot, JsxChild as p, Updates as pt, TranslationResult as q, CustomRegionMapping$1 as r, EnqueueFilesOptions as rt, GTProp as s, DownloadedFile as st, Content as t, CreateTagOptions as tt, HtmlContentPropValuesRecord as u, FileReferenceIds as ut, StringContent as v, JsonPrimitive as vt, InjectionType as w, TranslateManyEntry as wt, TranslationRequestConfig as x, ActionType as xt, StringFormat$1 as y, JsonValue as yt, GetOrphanedFilesResult as z };
537
- //# sourceMappingURL=types-DboOaYN_.d.cts.map
555
+ export { UploadFilesOptions as $, AwaitJobsOptions as A, OrphanedFile as B, VariableType as C, HashMetadata as Ct, VariableTransformationSuffix as D, TranslateManyEntry as Dt, TransformationPrefix as E, RuntimeTranslateManyOptions as Et, MoveMapping as F, TranslateManyResult as G, FileDataResult as H, MoveResult as I, TranslationResultReference as J, TranslationError as K, ProcessMovesOptions as L, JobResult as M, CheckJobStatusResult as N, SubmitUserEditDiff as O, TranslateOptions as Ot, JobStatus as P, FileUpload as Q, ProcessMovesResponse as R, Variable as S, JsonValue as St, Transformation as T, EntryMetadata as Tt, BranchQuery as U, FileDataQuery as V, BranchDataResult as W, PublishFileEntry as X, DownloadFileOptions as Y, PublishFilesResult as Z, Metadata as _, CheckFileTranslationsOptions as _t, DataFormat$1 as a, CreateTagResult as at, StringMessage$1 as b, JsonObject as bt, HTML_CONTENT_PROPS as c, DownloadFileBatchRequest as ct, I18nextMessage$1 as d, FileFormat as dt, UploadFilesResponse as et, IcuMessage$1 as f, FileReference as ft, LocaleProperties$1 as g, Updates as gt, JsxElement as h, EnqueueFilesResult as ht, CutoffFormatOptions$1 as i, CreateTagOptions as it, AwaitJobsResult as j, SubmitUserEditDiffsPayload as k, HtmlContentPropKeysRecord as l, DownloadFileBatchResult as lt, JsxChildren$1 as m, FileToUpload as mt, CustomMapping$1 as n, SetupProjectOptions as nt, FormatVariables$1 as o, EnqueueFilesOptions as ot, JsxChild as p, FileReferenceIds as pt, TranslationResult as q, CustomRegionMapping$1 as r, SetupProjectResult as rt, GTProp as s, DownloadFileBatchOptions as st, Content as t, SetupProjectFileReference as tt, HtmlContentPropValuesRecord as u, DownloadedFile as ut, StringContent as v, FileQuery as vt, InjectionType as w, ActionType as wt, TranslationRequestConfig as x, JsonPrimitive as xt, StringFormat$1 as y, FileQueryResult as yt, GetOrphanedFilesResult as z };
556
+ //# sourceMappingURL=types-iLf0drw8.d.cts.map
package/dist/types.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as AwaitJobsOptions, B as OrphanedFile, C as VariableType, D as VariableTransformationSuffix, E as TransformationPrefix, F as MoveMapping, G as TranslateManyResult, H as FileDataResult, I as MoveResult, J as TranslationResultReference, K as TranslationError, L as ProcessMovesOptions, M as JobResult, N as CheckJobStatusResult, O as SubmitUserEditDiff, P as JobStatus, Q as FileUpload, R as ProcessMovesResponse, S as Variable, St as EntryMetadata, T as Transformation, U as BranchQuery, V as FileDataQuery, W as BranchDataResult, X as PublishFileEntry, Y as DownloadFileOptions, Z as PublishFilesResult, _ as Metadata, _t as JsonObject, a as DataFormat, b as StringMessage, bt as HashMetadata, c as HTML_CONTENT_PROPS, ct as FileFormat, d as I18nextMessage, dt as FileToUpload, f as IcuMessage, ft as EnqueueFilesResult, g as LocaleProperties, h as JsxElement, i as CutoffFormatOptions, it as DownloadFileBatchOptions, j as AwaitJobsResult, k as SubmitUserEditDiffsPayload, l as HtmlContentPropKeysRecord, lt as FileReference, m as JsxChildren, mt as CheckFileTranslationsOptions, n as CustomMapping, nt as CreateTagResult, o as FormatVariables, ot as DownloadFileBatchResult, p as JsxChild, pt as Updates, q as TranslationResult, r as CustomRegionMapping, rt as EnqueueFilesOptions, s as GTProp, st as DownloadedFile, t as Content, tt as CreateTagOptions, u as HtmlContentPropValuesRecord, v as StringContent, vt as JsonPrimitive, w as InjectionType, wt as TranslateManyEntry, x as TranslationRequestConfig, xt as ActionType, y as StringFormat, yt as JsonValue, z as GetOrphanedFilesResult } from "./types-DboOaYN_.cjs";
2
- export { AwaitJobsOptions, AwaitJobsResult, 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, 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, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateManyEntry, TranslateManyResult, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType };
1
+ import { A as AwaitJobsOptions, B as OrphanedFile, C as VariableType, Ct as HashMetadata, D as VariableTransformationSuffix, Dt as TranslateManyEntry, E as TransformationPrefix, F as MoveMapping, G as TranslateManyResult, H as FileDataResult, I as MoveResult, J as TranslationResultReference, K as TranslationError, L as ProcessMovesOptions, M as JobResult, N as CheckJobStatusResult, O as SubmitUserEditDiff, P as JobStatus, Q as FileUpload, R as ProcessMovesResponse, S as Variable, St as JsonValue, T as Transformation, Tt as EntryMetadata, U as BranchQuery, V as FileDataQuery, W as BranchDataResult, X as PublishFileEntry, Y as DownloadFileOptions, Z as PublishFilesResult, _ as Metadata, _t as CheckFileTranslationsOptions, a as DataFormat, at as CreateTagResult, b as StringMessage, bt as JsonObject, c as HTML_CONTENT_PROPS, d as I18nextMessage, dt as FileFormat, f as IcuMessage, ft as FileReference, g as LocaleProperties, gt as Updates, h as JsxElement, ht as EnqueueFilesResult, i as CutoffFormatOptions, it as CreateTagOptions, j as AwaitJobsResult, k as SubmitUserEditDiffsPayload, l as HtmlContentPropKeysRecord, lt as DownloadFileBatchResult, m as JsxChildren, mt as FileToUpload, n as CustomMapping, o as FormatVariables, ot as EnqueueFilesOptions, p as JsxChild, q as TranslationResult, r as CustomRegionMapping, s as GTProp, st as DownloadFileBatchOptions, t as Content, tt as SetupProjectFileReference, u as HtmlContentPropValuesRecord, ut as DownloadedFile, v as StringContent, w as InjectionType, wt as ActionType, x as TranslationRequestConfig, xt as JsonPrimitive, y as StringFormat, z as GetOrphanedFilesResult } from "./types-iLf0drw8.cjs";
2
+ export { AwaitJobsOptions, AwaitJobsResult, 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, 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, SetupProjectFileReference, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateManyEntry, TranslateManyResult, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType };
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as AwaitJobsOptions, B as OrphanedFile, C as VariableType, D as VariableTransformationSuffix, E as TransformationPrefix, F as MoveMapping, G as TranslateManyResult, H as FileDataResult, I as MoveResult, J as TranslationResultReference, K as TranslationError, L as ProcessMovesOptions, M as JobResult, N as CheckJobStatusResult, O as SubmitUserEditDiff, P as JobStatus, Q as FileUpload, R as ProcessMovesResponse, S as Variable, St as EntryMetadata, T as Transformation, U as BranchQuery, V as FileDataQuery, W as BranchDataResult, X as PublishFileEntry, Y as DownloadFileOptions, Z as PublishFilesResult, _ as Metadata, _t as JsonObject, a as DataFormat, b as StringMessage, bt as HashMetadata, c as HTML_CONTENT_PROPS, ct as FileFormat, d as I18nextMessage, dt as FileToUpload, f as IcuMessage, ft as EnqueueFilesResult, g as LocaleProperties, h as JsxElement, i as CutoffFormatOptions, it as DownloadFileBatchOptions, j as AwaitJobsResult, k as SubmitUserEditDiffsPayload, l as HtmlContentPropKeysRecord, lt as FileReference, m as JsxChildren, mt as CheckFileTranslationsOptions, n as CustomMapping, nt as CreateTagResult, o as FormatVariables, ot as DownloadFileBatchResult, p as JsxChild, pt as Updates, q as TranslationResult, r as CustomRegionMapping, rt as EnqueueFilesOptions, s as GTProp, st as DownloadedFile, t as Content, tt as CreateTagOptions, u as HtmlContentPropValuesRecord, v as StringContent, vt as JsonPrimitive, w as InjectionType, wt as TranslateManyEntry, x as TranslationRequestConfig, xt as ActionType, y as StringFormat, yt as JsonValue, z as GetOrphanedFilesResult } from "./types-CHNhO-Lt.mjs";
2
- export { AwaitJobsOptions, AwaitJobsResult, 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, 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, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateManyEntry, TranslateManyResult, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType };
1
+ import { A as AwaitJobsOptions, B as OrphanedFile, C as VariableType, Ct as HashMetadata, D as VariableTransformationSuffix, Dt as TranslateManyEntry, E as TransformationPrefix, F as MoveMapping, G as TranslateManyResult, H as FileDataResult, I as MoveResult, J as TranslationResultReference, K as TranslationError, L as ProcessMovesOptions, M as JobResult, N as CheckJobStatusResult, O as SubmitUserEditDiff, P as JobStatus, Q as FileUpload, R as ProcessMovesResponse, S as Variable, St as JsonValue, T as Transformation, Tt as EntryMetadata, U as BranchQuery, V as FileDataQuery, W as BranchDataResult, X as PublishFileEntry, Y as DownloadFileOptions, Z as PublishFilesResult, _ as Metadata, _t as CheckFileTranslationsOptions, a as DataFormat, at as CreateTagResult, b as StringMessage, bt as JsonObject, c as HTML_CONTENT_PROPS, d as I18nextMessage, dt as FileFormat, f as IcuMessage, ft as FileReference, g as LocaleProperties, gt as Updates, h as JsxElement, ht as EnqueueFilesResult, i as CutoffFormatOptions, it as CreateTagOptions, j as AwaitJobsResult, k as SubmitUserEditDiffsPayload, l as HtmlContentPropKeysRecord, lt as DownloadFileBatchResult, m as JsxChildren, mt as FileToUpload, n as CustomMapping, o as FormatVariables, ot as EnqueueFilesOptions, p as JsxChild, q as TranslationResult, r as CustomRegionMapping, s as GTProp, st as DownloadFileBatchOptions, t as Content, tt as SetupProjectFileReference, u as HtmlContentPropValuesRecord, ut as DownloadedFile, v as StringContent, w as InjectionType, wt as ActionType, x as TranslationRequestConfig, xt as JsonPrimitive, y as StringFormat, z as GetOrphanedFilesResult } from "./types-CzFzXgUO.mjs";
2
+ export { AwaitJobsOptions, AwaitJobsResult, 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, 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, SetupProjectFileReference, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateManyEntry, TranslateManyResult, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType };
package/dist/types.d.ts CHANGED
@@ -9,6 +9,7 @@ export type { DownloadFileBatchOptions, DownloadFileBatchResult, } from './types
9
9
  export type { EnqueueFilesOptions } from './translate/enqueueFiles';
10
10
  export type { EnqueueFilesResult, Updates } from './types-dir/api/enqueueFiles';
11
11
  export type { CreateTagOptions, CreateTagResult } from './translate/createTag';
12
+ export type { SetupProjectFileReference } from './translate/setupProject';
12
13
  export type { FileToUpload } from './types-dir/api/file';
13
14
  export type { FileUpload } from './types-dir/api/uploadFiles';
14
15
  export type { FileReference } from './types-dir/api/file';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "generaltranslation",
3
- "version": "9.0.0",
3
+ "version": "9.0.2",
4
4
  "description": "A language toolkit for AI developers",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"id-CGtkkWBE.mjs","names":["stringify"],"sources":["../src/utils/stableStringify.ts","../src/id/hashSource.ts"],"sourcesContent":["/**\n * Deterministic JSON stringification with sorted object keys.\n * Drop-in replacement for `fast-json-stable-stringify` for plain\n * JSON-compatible data (no toJSON, no circular references).\n */\nfunction _stringify(node: unknown): string | undefined {\n if (node === undefined) return undefined;\n if (node === null) return 'null';\n if (typeof node === 'number') return isFinite(node) ? '' + node : 'null';\n if (typeof node !== 'object') return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n let out = '[';\n for (let i = 0; i < node.length; i++) {\n if (i) out += ',';\n out += _stringify(node[i]) || 'null';\n }\n return out + ']';\n }\n\n const keys = Object.keys(node as Record<string, unknown>).sort();\n let out = '';\n for (const key of keys) {\n const value = _stringify((node as Record<string, unknown>)[key]);\n if (!value) continue;\n if (out) out += ',';\n out += JSON.stringify(key) + ':' + value;\n }\n return '{' + out + '}';\n}\n\nexport function stableStringify(data: unknown): string {\n return _stringify(data) ?? '';\n}\n","// Functions provided to other GT libraries\n\nimport { JsxChild, JsxChildren, Variable } from '../types';\nimport { stableStringify as stringify } from '../utils/stableStringify';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { isVariable } from '../utils/isVariable';\nimport { HashMetadata } from './types';\n\n// ----- FUNCTIONS ----- //\n/**\n * Calculates a unique hash for a given string using SHA-256.\n *\n * First 16 characters of hash, hex encoded.\n *\n * @param {string} string - The string to be hashed.\n * @returns {string} The resulting hash as a hexadecimal string.\n */\nexport function hashString(string: string): string {\n return bytesToHex(sha256(utf8ToBytes(string))).slice(0, 16);\n}\n\n/**\n * Calculates a unique ID for the given children objects by hashing their sanitized JSON string representation.\n *\n * @param {any} childrenAsObjects - The children objects to be hashed.\n * @param {string} [context] - The context for the children.\n * @param {string} [id] - The ID for the JSX children object.\n * @param {number} [maxChars] - The maxChars limit for the JSX children object.\n * @param {string} [dataFormat] - The data format of the sources.\n * @param {function} [hashFunction] - Custom hash function.\n * @returns {string} - The unique hash of the children.\n */\nexport function hashSource(\n {\n source,\n context,\n id,\n maxChars,\n requiresReview,\n dataFormat,\n }: {\n source: JsxChildren | string;\n } & HashMetadata,\n hashFunction: (string: string) => string = hashString\n): string {\n let sanitizedSource: SanitizedChildren | string;\n if (dataFormat === 'JSX') {\n sanitizedSource = sanitizeJsxChildren(source);\n } else {\n sanitizedSource = source as string;\n }\n const sanitizedData: {\n source?: SanitizedChildren;\n } & HashMetadata = {\n source: sanitizedSource,\n ...(id && { id }),\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n // Only mixed in when true: false/absent must hash identically to\n // pre-requiresReview versions so existing projects keep their hashes\n ...(requiresReview === true && { requiresReview: true }),\n ...(dataFormat && { dataFormat }),\n };\n const stringifiedData = stringify(sanitizedData);\n return hashFunction(stringifiedData);\n}\n\ntype SanitizedVariable = Omit<Variable, 'i'>;\n\ntype SanitizedElement = {\n b?: {\n [k: string]: SanitizedChildren; // Branches\n };\n c?: SanitizedChildren; // Children\n t?: string; // Branch Transformation\n};\ntype SanitizedChild = SanitizedElement | SanitizedVariable | string;\ntype SanitizedChildren = SanitizedChild | SanitizedChild[];\n\n/**\n * Sanitizes a child object by removing the data-_gt attribute and its branches.\n *\n * @param child - The child object to sanitize.\n * @returns The sanitized child object.\n *\n */\nconst sanitizeChild = (child: JsxChild): SanitizedChild => {\n if (child && typeof child === 'object') {\n const newChild: SanitizedChild = {};\n if ('c' in child && child.c) {\n newChild.c = sanitizeJsxChildren(child.c);\n }\n if ('d' in child) {\n const generaltranslation = child?.d;\n if (generaltranslation?.b) {\n // The only thing that prevents sanitizeJsx from being stable is\n // the order of the keys in the branches object.\n // We don't sort them because stable-stringify sorts them anyways\n newChild.b = Object.fromEntries(\n Object.entries(generaltranslation.b).map(([key, value]) => [\n key,\n sanitizeJsxChildren(value as JsxChildren),\n ])\n );\n }\n if (generaltranslation?.t) {\n newChild.t = generaltranslation.t;\n }\n }\n if (isVariable(child)) {\n return {\n k: child.k,\n ...(child.v && {\n v: child.v,\n }),\n };\n }\n return newChild;\n }\n return child;\n};\n\nfunction sanitizeJsxChildren(\n childrenAsObjects: JsxChildren\n): SanitizedChildren {\n return Array.isArray(childrenAsObjects)\n ? childrenAsObjects.map(sanitizeChild)\n : sanitizeChild(childrenAsObjects);\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,WAAW,MAAmC;AACrD,KAAI,SAAS,KAAA,EAAW,QAAO,KAAA;AAC/B,KAAI,SAAS,KAAM,QAAO;AAC1B,KAAI,OAAO,SAAS,SAAU,QAAO,SAAS,KAAK,GAAG,KAAK,OAAO;AAClE,KAAI,OAAO,SAAS,SAAU,QAAO,KAAK,UAAU,KAAK;AAEzD,KAAI,MAAM,QAAQ,KAAK,EAAE;EACvB,IAAI,MAAM;AACV,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,OAAI,EAA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