UNPKG

generaltranslation

Version:

A language toolkit for AI developers

1,263 lines (1,238 loc) 62.3 kB
type CustomMapping = Record<string, string | Partial<LocaleProperties>>; type LocaleProperties = { code: string; name: string; nativeName: string; languageCode: string; languageName: string; nativeLanguageName: string; nameWithRegionCode: string; nativeNameWithRegionCode: string; regionCode: string; regionName: string; nativeRegionName: string; scriptCode: string; scriptName: string; nativeScriptName: string; maximizedCode: string; maximizedName: string; nativeMaximizedName: string; minimizedCode: string; minimizedName: string; nativeMinimizedName: string; emoji: string; }; type VariableType = 'v' | 'n' | 'd' | 'c'; /** * Variables are used to store the variable name and type. */ type Variable = { k: string; i?: number; v?: VariableType; }; /** * Map of data-_gt properties to their corresponding React props */ declare const HTML_CONTENT_PROPS: { readonly pl: "placeholder"; readonly ti: "title"; readonly alt: "alt"; readonly arl: "aria-label"; readonly arb: "aria-labelledby"; readonly ard: "aria-describedby"; }; type HtmlContentPropKeysRecord = Partial<Record<keyof typeof HTML_CONTENT_PROPS, string>>; /** * GTProp is an internal property used to contain data for translating and rendering elements. * note, transformations are only read on the server side if they are 'plural' or 'branch' */ type GTProp = { b?: Record<string, JsxChildren>; t?: 'p' | 'b'; } & HtmlContentPropKeysRecord; type JsxElement = { t?: string; i?: number; d?: GTProp; c?: JsxChildren; }; type JsxChild = string | JsxElement | Variable; /** * The format of the content */ type DataFormat = 'JSX' | 'ICU' | 'I18NEXT'; /** * A content type representing JSX, ICU, and I18next messages */ type Content = JsxChildren | IcuMessage | I18nextMessage; /** * A content type representing JSX elements */ type JsxChildren = JsxChild | JsxChild[]; /** * A content type representing ICU messages */ type IcuMessage = string; /** * A content type representing I18next messages */ type I18nextMessage = string; /** * ActionType is the type of action to perform on the request. * * @param standard - The standard action type (standard model). * @param fast - The fast action type (mini model). * @param string - Other model */ type ActionType = 'standard' | 'fast' | string; /** * EntryMetadata is the metadata for a GTRequest. * * @param context - The context of the request. * @param id - The id of the request. * @param maxChars - The maxChars of the request. * @param hash - The hash of the request. */ type EntryMetadata = { context?: string; id?: string; maxChars?: number; hash?: string; dataFormat?: DataFormat; sourceLocale?: string; actionType?: ActionType; timeout?: number; regionCode?: string; scriptCode?: string; }; /** * GTRequest is a translation request object for {@link JsxChildren} | {@link IcuMessage} | {@link I18nextMessage} * * @param source - The source content to translate. * @param targetLocale - The target locale to translate to. * @param metadata - The metadata for the request. */ type Entry = { source: Content; targetLocale?: string; metadata?: EntryMetadata; }; type CheckFileTranslationsOptions = { timeout?: number; }; type FileQuery = { fileId: string; branchId?: string; versionId?: string; }; type FileQueryResult = { sourceFile: { id: string; fileId: string; versionId: string; sourceLocale: string; fileName: string; fileFormat: string; dataFormat: string | null; createdAt: string; updatedAt: string; approvalRequiredAt: string | null; locales: string[]; }; translations: { locale: string; completedAt: string | null; approvedAt: string | null; publishedAt: string | null; createdAt: string | null; updatedAt: string | null; }[]; }; type FileFormat = 'GTJSON' | 'JSON' | 'YAML' | 'MDX' | 'MD' | 'TS' | 'JS' | 'HTML' | 'TXT'; /** * File object structure for referencing files * @param fileId - The ID of the file * @param versionId - The ID of the version of the file * @param branchId - The ID of the branch of the file * @param locale - The locale of the file () */ type FileReference = { fileId: string; versionId: string; branchId: string; fileName: string; fileFormat: FileFormat; dataFormat?: DataFormat; }; type DownloadFileBatchRequest = { fileId: string; branchId?: string; versionId?: string; locale?: string; }[]; type DownloadFileBatchOptions = { timeout?: number; }; type DownloadedFile = { id: string; branchId: string; fileId: string; versionId: string; locale?: string; fileName?: string; data: string; metadata: Record<string, any>; fileFormat: FileFormat; }; type DownloadFileBatchResult = { files: DownloadedFile[]; count: number; }; type EnqueueFilesResult = { jobData: { [jobId: string]: { sourceFileId: string; fileId: string; versionId: string; branchId: string; targetLocale: string; projectId: string; force: boolean; modelProvider?: string; }; }; locales: string[]; message: string; }; /** * Metadata stored alongside GTJSON file entries. * Keys correspond to the entry id/hash in the GTJSON body. */ type GTJsonFormatMetadata = Record<string, { context?: string; id?: string; domain?: string; maxChars?: number; dataFormat?: 'JSX' | 'ICU'; requestVersion?: number; approved_at?: string | null; approved_by?: string | null; hash?: string; filePaths?: string[]; }>; type FileUpload = { branchId?: string; incomingBranchId?: string; checkedOutBranchId?: string; content: string; fileName: string; fileFormat: FileFormat; dataFormat?: DataFormat; locale: string; formatMetadata?: GTJsonFormatMetadata; versionId?: string; fileId?: string; }; type UploadFilesOptions = { sourceLocale: string; modelProvider?: string; timeout?: number; }; type UploadFilesResponse = { uploadedFiles: FileReference[]; count: number; message: string; }; type DownloadFileOptions = { timeout?: number; }; /** * TranslationResultReference is used to store the reference for a translation result. */ type TranslationResultReference = { id?: string; hash: string; }; /** * TypedResult is a union type that represents the different types of translations that can be returned. */ type TypedResult = { translation: JsxChildren; dataFormat: 'JSX'; } | { translation: I18nextMessage | IcuMessage; dataFormat: 'ICU' | 'I18NEXT'; }; /** * RequestError is a type that represents an error that occurred during a translation request. */ type TranslationError = { error: string; code: number; reference?: TranslationResultReference; }; /** * RequestSuccess is a type that represents a successful translation request. */ type RequestSuccess = TypedResult & { locale: string; reference: TranslationResultReference; }; type TranslationResult = RequestSuccess | TranslationError; /** * BatchTranslationResult is the result of a batch translation request. */ type TranslateManyResult = Array<TranslationResult>; type BranchDataResult = { branches: { id: string; name: string; }[]; defaultBranch: { id: string; name: string; } | null; }; type BranchQuery = { branchNames: string[]; }; type FileDataQuery = { sourceFiles?: { fileId: string; versionId: string; branchId: string; }[]; translatedFiles?: { fileId: string; versionId: string; branchId: string; locale: string; }[]; }; type FileDataResult = { sourceFiles?: { branchId: string; fileId: string; versionId: string; fileName: string; fileFormat: string; dataFormat: string | null; createdAt: string; updatedAt: string; approvalRequiredAt: string | null; publishedAt: string | null; locales: string[]; sourceLocale: string; }[]; translatedFiles?: { branchId: string; fileId: string; versionId: string; fileFormat: string; dataFormat: string | null; createdAt: string; updatedAt: string; approvedAt: string | null; publishedAt: string | null; completedAt: string | null; locale: string; }[]; }; type JobStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'unknown'; type CheckJobStatusResult = { jobId: string; status: JobStatus; error?: { message: string; }; }[]; type SubmitUserEditDiff = { fileName: string; locale: string; diff: string; branchId: string; versionId: string; fileId: string; localContent: string; }; type SubmitUserEditDiffsPayload = { diffs: SubmitUserEditDiff[]; }; type FormatVariables = Record<string, string | number | boolean | null | undefined | Date>; type SetupProjectResult = { setupJobId: string; status: 'queued'; } | { status: 'completed'; }; type SetupProjectOptions = { force?: boolean; locales?: string[]; timeoutMs?: number; }; type EnqueueOptions = { sourceLocale: string; targetLocales: string[]; publish?: boolean; requireApproval?: boolean; modelProvider?: string; force?: boolean; timeout?: number; }; type CustomRegionMapping = { [region: string]: { name?: string; emoji?: string; locale?: string; }; }; type ProjectData = { id: string; name: string; orgId: string; defaultLocale: string; currentLocales: string[]; }; type CreateBranchQuery = { branchName: string; defaultBranch: boolean; }; type CreateBranchResult = { branch: { id: string; name: string; }; }; /** Type of terminator */ type CutoffFormatStyle = 'none' | 'ellipsis'; /** Terminator options */ interface TerminatorOptions { /** The terminator to use */ terminator?: string; /** An optional separator between the terminator and the value */ separator?: string; } /** Input formatting options (for constructor) */ interface CutoffFormatOptions extends TerminatorOptions { /** Cutoff length */ maxChars?: number; /** Type of terminator */ style?: CutoffFormatStyle; } /** * Type representing the constructor parameters for the GT class. * @typedef {Object} GTConstructorParams * @property {string} [apiKey] - The API key for accessing the translation service * @property {string} [devApiKey] - The development API key for accessing the translation service * @property {string} [sourceLocale] - The default source locale for translations * @property {string} [targetLocale] - The default target locale for translations * @property {string[]} [locales] - Array of supported locales * @property {string} [projectId] - The project ID for the translation service * @property {string} [baseUrl] - The base URL for the translation service * @property {CustomMapping} [customMapping] - Custom mapping of locale codes to their names */ type GTConstructorParams = { apiKey?: string; devApiKey?: string; sourceLocale?: string; targetLocale?: string; locales?: string[]; projectId?: string; baseUrl?: string; customMapping?: CustomMapping; }; /** * GT is the core driver for the General Translation library. * This class provides functionality for locale management, formatting, and translation operations. * * @class GT * @description A comprehensive toolkit for handling internationalization and localization. * * @example * const gt = new GT({ * sourceLocale: 'en-US', * targetLocale: 'es-ES', * locales: ['en-US', 'es-ES', 'fr-FR'] * }); */ declare class GT { /** Base URL for the translation service API */ baseUrl?: string; /** Project ID for the translation service */ projectId?: string; /** API key for accessing the translation service */ apiKey?: string; /** Development API key for accessing the translation service */ devApiKey?: string; /** Source locale for translations */ sourceLocale?: string; /** Target locale for translations */ targetLocale?: string; /** Array of supported locales */ locales?: string[]; /** Array of locales used for rendering variables */ _renderingLocales: string[]; /** Custom mapping for locale codes to their names */ customMapping?: CustomMapping; /** Lazily derived reverse custom mapping for alias locales */ reverseCustomMapping?: Record<string, string>; /** Lazily derived custom mapping for regions */ customRegionMapping?: CustomRegionMapping; /** * Constructs an instance of the GT class. * * @param {GTConstructorParams} [params] - The parameters for initializing the GT instance * @throws {Error} If an invalid locale is provided * @throws {Error} If any of the provided locales are invalid * * @example * const gt = new GT({ * apiKey: 'your-api-key', * sourceLocale: 'en-US', * targetLocale: 'es-ES', * locales: ['en-US', 'es-ES', 'fr-FR'] * }); */ constructor(params?: GTConstructorParams); setConfig({ apiKey, devApiKey, sourceLocale, targetLocale, locales, projectId, customMapping, baseUrl, }: GTConstructorParams): void; private _getTranslationConfig; private _validateAuth; /** * Queries branch information from the API. * * @param {BranchQuery} query - Object mapping the current branch and incoming branches * @returns {Promise<BranchDataResult>} The branch information */ queryBranchData(query: BranchQuery): Promise<BranchDataResult>; /** * Creates a new branch in the API. If the branch already exists, it will be returned. * * @param {CreateBranchQuery} query - Object mapping the branch name and default branch flag * @returns {Promise<CreateBranchResult>} The created branch information */ createBranch(query: CreateBranchQuery): Promise<CreateBranchResult>; /** * Enqueues project setup job using the specified file references * * This method creates setup jobs that will process source file references * and generate a project setup. The files parameter contains references (IDs) to source * files that have already been uploaded via uploadSourceFiles. The setup jobs are queued * for processing and will generate a project setup based on the source files. * * @param {FileReference[]} files - Array of file references containing IDs of previously uploaded source files * @param {SetupProjectOptions} [options] - Optional settings for target locales and timeout * @returns {Promise<SetupProjectResult>} Object containing the jobId and status */ setupProject(files: FileReference[], options?: SetupProjectOptions): Promise<SetupProjectResult>; /** * Checks the current status of one or more project jobs by their unique identifiers. * * This method polls the API to determine whether one or more jobs are still running, * have completed successfully, or have failed. Jobs are created after calling either enqueueFiles or setupProject. * * @param {string[]} jobIds - The unique identifiers of the jobs to check * @param {number} [timeoutMs] - Optional timeout in milliseconds for the API request * @returns {Promise<CheckJobStatusResult>} Object containing the job status * * @example * const result = await gt.checkJobStatus([ * 'job-123', * 'job-456', * ], { * timeout: 10000, * }); */ checkJobStatus(jobIds: string[], timeoutMs?: number): Promise<CheckJobStatusResult>; /** * Enqueues translation jobs for previously uploaded source files. * * This method creates translation jobs that will process existing source files * and generate translations in the specified target languages. The files parameter * contains references (IDs) to source files that have already been uploaded via * uploadSourceFiles. The translation jobs are queued for processing and will * generate translated content based on the source files and target locales provided. * * @param {FileReference[]} files - Array of file references containing IDs of previously uploaded source files * @param {EnqueueOptions} options - Configuration options including source locale, target locales, and job settings * @returns {Promise<EnqueueFilesResult>} Result containing job IDs, queue status, and processing information */ enqueueFiles(files: FileReference[], options: EnqueueOptions): Promise<EnqueueFilesResult>; /** * Submits user edit diffs for existing translations so future generations preserve user intent. * * @param {SubmitUserEditDiffsPayload} payload - Project-scoped diff payload. * @returns {Promise<void>} Resolves when submission succeeds. */ submitUserEditDiffs(payload: SubmitUserEditDiffsPayload): Promise<void>; /** * Queries data about one or more source or translation files. * * @param {FileDataQuery} data - Object mapping source and translation file information. * @param {CheckFileTranslationsOptions} options - Options for the API call. * @returns {Promise<FileDataResult>} The source and translation file data information. * * @example * const result = await gt.queryFileData({ * sourceFiles: [ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890' }, * ], * translatedFiles: [ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890', locale: 'es-ES' }, * ], * }, { * timeout: 10000, * }); * */ queryFileData(data: FileDataQuery, options?: CheckFileTranslationsOptions): Promise<FileDataResult>; /** * Gets source and translation information for a given file ID and version ID. * * @param {FileQuery} data - File query containing file ID and version ID. * @param {CheckFileTranslationsOptions} options - Options for getting source and translation information. * @returns {Promise<FileQueryResult>} The source file and translation information. * * @example * const result = await gt.querySourceFile( * { fileId: '1234567890', versionId: '1234567890' }, * { timeout: 10000 } * ); * */ querySourceFile(data: FileQuery, options?: CheckFileTranslationsOptions): Promise<FileQueryResult>; /** * Get project data for a given project ID. * * @param {string} projectId - The ID of the project to get the data for. * @returns {Promise<ProjectData>} The project data. * * @example * const result = await gt.getProjectData( * '1234567890' * ); * */ getProjectData(projectId: string, options?: { timeout?: number; }): Promise<ProjectData>; /** * Downloads a single file. * * @param file - The file query object. * @param {string} file.fileId - The ID of the file to download. * @param {string} [file.branchId] - The ID of the branch to download the file from. If not provided, the default branch will be used. * @param {string} [file.locale] - The locale to download the file for. If not provided, the source file will be downloaded. * @param {string} [file.versionId] - The version ID to download the file from. If not provided, the latest version will be used. * @param {DownloadFileOptions} options - Options for downloading the file. * @returns {Promise<string>} The downloaded file content. * * @example * const result = await gt.downloadFile({ * fileId: '1234567890', * branchId: '1234567890', * locale: 'es-ES', * versionId: '1234567890', * }, { * timeout: 10000, * }); */ downloadFile(file: { fileId: string; branchId?: string; locale?: string; versionId?: string; }, options?: DownloadFileOptions): Promise<string>; /** * Downloads multiple files in a batch. * * @param {DownloadFileBatchRequest} requests - Array of file query objects to download. * @param {DownloadFileBatchOptions} options - Options for the batch download. * @returns {Promise<DownloadFileBatchResult>} The batch download results. * * @example * const result = await gt.downloadFileBatch([{ * fileId: '1234567890', * locale: 'es-ES', * versionId: '1234567890', * }], { * timeout: 10000, * }); */ downloadFileBatch(requests: DownloadFileBatchRequest, options?: DownloadFileBatchOptions): Promise<DownloadFileBatchResult>; /** * Translates the source content to the target locale. * @deprecated Use the {@link translate} method instead. */ _translate(source: JsxChildren, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'JSX'; }): Promise<TranslationResult | TranslationError>; /** * Translates the source content to the target locale. * @deprecated Use the {@link translate} method instead. */ _translate(source: IcuMessage, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'ICU'; }): Promise<TranslationResult | TranslationError>; /** * Translates the source content to the target locale. * @deprecated Use the {@link translate} method instead. */ _translate(source: I18nextMessage, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'I18NEXT'; }): Promise<TranslationResult | TranslationError>; /** * Translates the source content to the target locale. * * @param {Content} source - {@link JsxChildren} | {@link IcuMessage} | {@link I18nextMessage} The source content to translate. * @param {string} targetLocale - string The target locale to translate to. * @param {EntryMetadata} metadata - {@link EntryMetadata} The metadata for the translation. * @returns {Promise<TranslationResult | TranslationError>} The translated content. * * @example * const gt = new GT({ * sourceLocale: 'en-US', * targetLocale: 'es-ES', * locales: ['en-US', 'es-ES', 'fr-FR'] * }); * * const result = await gt.translate('Hello, world!', 'es-ES'); * * @example * const gt = new GT({ * sourceLocale: 'en-US', * targetLocale: 'es-ES', * locales: ['en-US', 'es-ES', 'fr-FR'] * }); * * const result = await gt.translate('Hello, world!', 'es-ES', { context: 'A formal greeting'}); */ translate(source: JsxChildren, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'JSX'; }): Promise<TranslationResult | TranslationError>; translate(source: IcuMessage, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'ICU'; }): Promise<TranslationResult | TranslationError>; translate(source: I18nextMessage, targetLocale: string, metadata?: Omit<EntryMetadata, 'dataFormat'> & { dataFormat?: 'I18NEXT'; }): Promise<TranslationResult | TranslationError>; /** * Translates multiple source contents to the target locale. * Override global metadata by supplying a metadata object for each request. * * @param {Entry[]} sources - The source contents to translate. * @param {EntryMetadata} globalMetadata - {@link EntryMetadata} The metadata for the translation. * @returns {Promise<TranslateManyResult>} The translated contents. * * @example * const gt = new GT({ * sourceLocale: 'en-US', * targetLocale: 'es-ES', * locales: ['en-US', 'es-ES', 'fr-FR'] * }); * * const result = await gt.translateMany([ * { source: 'Hello, world!' }, * { source: 'Goodbye, world!' }, * ], { targetLocale: 'es-ES' }); */ translateMany(sources: Entry[], globalMetadata?: { targetLocale: string; } & EntryMetadata): Promise<TranslateManyResult>; /** * Uploads source files to the translation service without any translation content. * * This method creates or replaces source file entries in your project. Each uploaded * file becomes a source that can later be translated into target languages. The files * are processed and stored as base entries that serve as the foundation for generating * translations through the translation workflow. * * @param {Array<{source: FileUpload}>} files - Array of objects containing source file data to upload * @param {UploadFilesOptions} options - Configuration options including source locale and other upload settings * @returns {Promise<UploadFilesResponse>} Upload result containing file IDs, version information, and upload status */ uploadSourceFiles(files: { source: FileUpload; }[], options: UploadFilesOptions): Promise<UploadFilesResponse>; /** * Uploads translation files that correspond to previously uploaded source files. * * This method allows you to provide translated content for existing source files in your project. * Each translation must reference an existing source file and include the translated content * along with the target locale information. This is used when you have pre-existing translations * that you want to upload directly rather than generating them through the translation service. * * @param {Array<{source: FileUpload, translations: FileUpload[]}>} files - Array of file objects where: * - `source`: Reference to the existing source file (contains IDs but no content) * - `translations`: Array of translated files, each containing content, locale, and reference IDs * @param {UploadFilesOptions} options - Configuration options including source locale and upload settings * @returns {Promise<UploadFilesResponse>} Upload result containing translation IDs, status, and processing information */ uploadTranslations(files: { source: FileUpload; translations: FileUpload[]; }[], options: UploadFilesOptions): Promise<UploadFilesResponse>; /** * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit. * * This method uses the GT instance's rendering locales by default for locale-specific terminator selection, * but can be overridden with custom locales in the options. * * @param {string} value - The string value to format with cutoff behavior. * @param {Object} [options] - Configuration options for cutoff formatting. * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales. * @param {number} [options.maxChars] - The maximum number of characters to display. * - Undefined values are treated as no cutoff. * - Negative values follow .slice() behavior and terminator will be added before the value. * - 0 will result in an empty string. * - If cutoff results in an empty string, no terminator is added. * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator. * @param {string} [options.terminator] - Optional override the terminator to use. * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value. * - If no terminator is provided, then separator is ignored. * @returns {string} The formatted string with terminator applied if cutoff occurs. * * @example * const gt = new GT({ targetLocale: 'en-US' }); * gt.formatCutoff('Hello, world!', { maxChars: 8 }); * // Returns: 'Hello, w...' * * @example * gt.formatCutoff('Hello, world!', { maxChars: -3 }); * // Returns: '...ld!' */ formatCutoff(value: string, options?: { locales?: string | string[]; } & CutoffFormatOptions): string; /** * Formats a message according to the specified locales and options. * * @param {string} message - The message to format. * @param {string | string[]} [locales='en'] - The locales to use for formatting. * @param {FormatVariables} [variables={}] - The variables to use for formatting. * @returns {string} The formatted message. * * @example * gt.formatMessage('Hello {name}', { name: 'John' }); * // Returns: "Hello John" * * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] }); * // Returns: "Bonjour John" */ formatMessage(message: string, options?: { locales?: string | string[]; variables?: FormatVariables; }): string; /** * Formats a number according to the specified locales and options. * * @param {number} number - The number to format * @param {Object} [options] - Additional options for number formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options * @returns {string} The formatted number * * @example * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' }); * // Returns: "$1,234.56" */ formatNum(number: number, options?: { locales?: string | string[]; } & Intl.NumberFormatOptions): string; /** * Formats a date according to the specified locales and options. * * @param {Date} date - The date to format * @param {Object} [options] - Additional options for date formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options * @returns {string} The formatted date * * @example * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' }); * // Returns: "Thursday, March 14, 2024 at 2:30:45 PM GMT-7" */ formatDateTime(date: Date, options?: { locales?: string | string[]; } & Intl.DateTimeFormatOptions): string; /** * Formats a currency value according to the specified locales and options. * * @param {number} value - The currency value to format * @param {string} currency - The currency code (e.g., 'USD', 'EUR') * @param {Object} [options] - Additional options for currency formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options * @returns {string} The formatted currency value * * @example * gt.formatCurrency(1234.56, 'USD', { style: 'currency' }); * // Returns: "$1,234.56" */ formatCurrency(value: number, currency: string, options?: { locales?: string | string[]; } & Intl.NumberFormatOptions): string; /** * Formats a list of items according to the specified locales and options. * * @param {Array<string | number>} array - The list of items to format * @param {Object} [options] - Additional options for list formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options * @returns {string} The formatted list * * @example * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' }); * // Returns: "apple, banana, and orange" */ formatList(array: Array<string | number>, options?: { locales?: string | string[]; } & Intl.ListFormatOptions): string; /** * Formats a list of items according to the specified locales and options. * @param {Array<T>} array - The list of items to format * @param {Object} [options] - Additional options for list formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options * @returns {Array<T | string>} The formatted list parts * * @example * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] }); * // Returns: ['apple', ', ', 42, ' and ', '{ foo: "bar" }'] */ formatListToParts<T>(array: Array<T>, options?: { locales?: string | string[]; } & Intl.ListFormatOptions): Array<T | string>; /** * Formats a relative time value according to the specified locales and options. * * @param {number} value - The relative time value to format * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year') * @param {Object} options - Additional options for relative time formatting * @param {string | string[]} [options.locales] - The locales to use for formatting * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options * @returns {string} The formatted relative time string * * @example * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' }); * // Returns: "yesterday" */ formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, options?: { locales?: string | string[]; } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>): string; /** * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found. * * @param {string} [locale=this.targetLocale] - A BCP-47 locale code * @returns {string} The display name corresponding to the code * @throws {Error} If no target locale is provided * * @example * gt.getLocaleName('es-ES'); * // Returns: "Spanish (Spain)" */ getLocaleName(locale?: string | undefined): string; /** * Retrieves an emoji based on a given locale code. * Uses the locale's region (if present) to select an emoji or falls back on default emojis. * * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA') * @returns {string} The emoji representing the locale or its region * @throws {Error} If no target locale is provided * * @example * gt.getLocaleEmoji('es-ES'); * // Returns: "🇪🇸" */ getLocaleEmoji(locale?: string | undefined): string; /** * Generates linguistic details for a given locale code. * * This function returns information about the locale, * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region). * The function provides these names in both your default language and native forms, and an associated emoji. * * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., "de-AT"). * @returns {LocaleProperties} - An object containing detailed information about the locale. * * @property {string} code - The full locale code, e.g., "de-AT". * @property {string} name - Language name in the default display language, e.g., "Austrian German". * @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch". * @property {string} languageCode - The base language code, e.g., "de". * @property {string} languageName - The language name in the default display language, e.g., "German". * @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch". * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)". * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)". * @property {string} regionCode - The region code from maximization, e.g., "AT". * @property {string} regionName - The region name in the default display language, e.g., "Austria". * @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich". * @property {string} scriptCode - The script code from maximization, e.g., "Latn". * @property {string} scriptName - The script name in the default display language, e.g., "Latin". * @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch". * @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT". * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)". * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)". * @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE"). * @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German". * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch". * @property {string} emoji - The emoji associated with the locale's region, if applicable. */ getLocaleProperties(locale?: string | undefined): LocaleProperties; /** * Retrieves multiple properties for a given region code, including: * - `code`: the original region code * - `name`: the localized display name * - `emoji`: the associated flag or symbol * * Behavior: * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`). * - Uses the instance's `targetLocale` to localize the region name for the user. * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values. * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`. * - Falls back to the region code as `name` if display name resolution fails. * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`. * * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`). * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis. * @returns {{ code: string, name: string, emoji: string }} An object containing: * - `code`: the input region code * - `name`: the localized or custom region name * - `emoji`: the matching emoji flag or symbol * * @throws {Error} If no target locale is available to determine region properties. * * @example * const gt = new GT({ targetLocale: 'en-US' }); * gt.getRegionProperties('US'); * // => { code: 'US', name: 'United States', emoji: '🇺🇸' } * * @example * const gt = new GT({ targetLocale: 'fr-FR' }); * gt.getRegionProperties('US'); * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' } * * @example * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } }); * // => { code: 'US', name: 'USA', emoji: '🗽' } */ getRegionProperties(region?: string, customMapping?: CustomRegionMapping): { code: string; name: string; emoji: string; }; /** * Determines whether a translation is required based on the source and target locales. * * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales * @returns {boolean} True if translation is required, false otherwise * @throws {Error} If no source locale is provided * @throws {Error} If no target locale is provided * * @example * gt.requiresTranslation('en-US', 'es-ES'); * // Returns: true */ requiresTranslation(sourceLocale?: string | undefined, targetLocale?: string | undefined, approvedLocales?: string[] | undefined, customMapping?: CustomMapping | undefined): boolean; /** * Determines the best matching locale from the provided approved locales list. * * @param {string | string[]} locales - A single locale or array of locales in preference order * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order * @returns {string | undefined} The best matching locale or undefined if no match is found * * @example * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']); * // Returns: "fr-FR" */ determineLocale(locales: string | string[], approvedLocales?: string[] | undefined, customMapping?: CustomMapping | undefined): string | undefined; /** * Gets the text direction for a given locale code. * * @param {string} [locale=this.targetLocale] - A BCP-47 locale code * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left, otherwise 'ltr' * @throws {Error} If no target locale is provided * * @example * gt.getLocaleDirection('ar-SA'); * // Returns: "rtl" */ getLocaleDirection(locale?: string | undefined): 'ltr' | 'rtl'; /** * Checks if a given BCP 47 locale code is valid. * * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate * @param {customMapping} [customMapping=this.customMapping] - The custom mapping to use for validation * @returns {boolean} True if the locale code is valid, false otherwise * @throws {Error} If no target locale is provided * * @example * gt.isValidLocale('en-US'); * // Returns: true */ isValidLocale(locale?: string | undefined, customMapping?: CustomMapping | undefined): boolean; /** * Resolves the canonical locale for a given locale. * @param locale - The locale to resolve the canonical locale for * @param customMapping - The custom mapping to use for resolving the canonical locale * @returns The canonical locale */ resolveCanonicalLocale(locale?: string | undefined, customMapping?: CustomMapping | undefined): string; /** * Resolves the alias locale for a given locale. * @param locale - The locale to resolve the alias locale for * @param customMapping - The custom mapping to use for resolving the alias locale * @returns The alias locale */ resolveAliasLocale(locale: string, customMapping?: CustomMapping | undefined): string; /** * Standardizes a BCP 47 locale code to ensure correct formatting. * * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize * @returns {string} The standardized locale code or empty string if invalid * @throws {Error} If no target locale is provided * * @example * gt.standardizeLocale('en_us'); * // Returns: "en-US" */ standardizeLocale(locale?: string | undefined): string; /** * Checks if multiple BCP 47 locale codes represent the same dialect. * * @param {...(string | string[])} locales - The BCP 47 locale codes to compare * @returns {boolean} True if all codes represent the same dialect, false otherwise * * @example * gt.isSameDialect('en-US', 'en-GB'); * // Returns: false * * gt.isSameDialect('en', 'en-US'); * // Returns: true */ isSameDialect(...locales: (string | string[])[]): boolean; /** * Checks if multiple BCP 47 locale codes represent the same language. * * @param {...(string | string[])} locales - The BCP 47 locale codes to compare * @returns {boolean} True if all codes represent the same language, false otherwise * * @example * gt.isSameLanguage('en-US', 'en-GB'); * // Returns: true */ isSameLanguage(...locales: (string | string[])[]): boolean; /** * Checks if a locale is a superset of another locale. * * @param {string} superLocale - The locale to check if it is a superset * @param {string} subLocale - The locale to check if it is a subset * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise * * @example * gt.isSupersetLocale('en', 'en-US'); * // Returns: true * * gt.isSupersetLocale('en-US', 'en'); * // Returns: false */ isSupersetLocale(superLocale: string, subLocale: string): boolean; } /** * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit. * * This standalone function provides cutoff formatting functionality without requiring a GT instance. * The locales parameter is required for proper terminator selection based on the target language. * * @param {string} value - The string value to format with cutoff behavior. * @param {Object} [options] - Configuration options for cutoff formatting. * @param {string | string[]} [options.locales] - The locales to use for terminator selection. * @param {number} [options.maxChars] - The maximum number of characters to display. * - Undefined values are treated as no cutoff. * - Negative values follow .slice() behavior and terminator will be added before the value. * - 0 will result in an empty string. * - If cutoff results in an empty string, no terminator is added. * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator. * @param {string} [options.terminator] - Optional override the terminator to use. * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value. * - If no terminator is provided, then separator is ignored. * @returns {string} The formatted string with terminator applied if cutoff occurs. * * @example * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: 8 }); * // Returns: 'Hello, w...' * * @example * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: -3 }); * // Returns: '...ld!' * * @example * formatCutoff('Very long text that needs cutting', { * locales: 'en-US', * maxChars: 15, * style: 'ellipsis', * separator: ' ' * }); * // Returns: 'Very long text ...' */ declare function formatCutoff(value: string, options?: { locales?: string | string[]; } & CutoffFormatOptions): string; /** * Formats a message according to the specified locales and options. * * @param {string} message - The message to format. * @param {string | string[]} [locales='en'] - The locales to use for formatting. * @param {FormatVariables} [variables={}] - The variables to use for formatting. * @returns {string} The formatted message. * * @example * formatMessage('Hello {name}', { name: 'John' }); * // Returns: "Hello John" * * formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] }); * // Returns: "Bonjour John" */ declare function formatMessage(message: string, options?: { locales?: string | string[]; variables?: FormatVariables; }): string; /** * Formats a number according to the specified locales and options. * @param {Object} params - The parameters for the number formatting. * @param {number} params.value - The number to format. * @param {Intl.NumberFormatOptions} [params.options] - Additional options for number formatting. * @param {string | string[]} [params.options.locales] - The locales to use for formatting. * @returns {string} The formatted number. */ declare function formatNum(number: number, options: { locales: string | string[]; } & Intl.NumberFormatOptions): string; /** * Formats a date according to the specified languages and options. * @param {Object} params - The parameters for the date formatting. * @param {Date} params.value - The date to format. * @param {Intl.DateTimeFormatOptions} [params.options] - Additional options for date formatting. * @param {string | string[]} [params.options.locales] - The languages to use for formatting. * @returns {string} The formatted date. */ declare function formatDateTime(date: Date, options?: { locales?: string | string[]; } & Intl.DateTimeFormatOptions): string; /** * Formats a currency value according to the specified languages, currency, and options. * @param {Object} params - The parameters for the currency formatting. * @param {number} params.value - The currency value to format. * @param {string} params.currency - The currency code (e.g., 'USD'). * @param {Intl.NumberFormatOptions} [params.options={}] - Additional options for currency formatting. * @param {string | string[]} [params.options.locales] - The locale codes to use for formatting. * @returns {string} The formatted currency value. */ declare function formatCurrency(value: number, currency: string, options: { locales: string | string[]; } & Intl.NumberFormatOptions): string; /** * Formats a list of items according to the specified locales and options. * @param {Object} params - The parameters for the list formatting. * @param {Array<s