UNPKG

@stacksjs/stx

Version:

A performant UI Framework. Powered by Bun.

255 lines 9.25 kB
import type { I18nConfig, StxOptions } from './types'; /** * Clear the translation cache * @param locale - Optional locale to clear. If not provided, clears all. */ export declare function clearTranslationCache(locale?: string): void; /** * Get translation cache statistics */ export declare function getTranslationCacheStats(): { size: number locales: string[] entries: Array<{ locale: string, loadedAt: Date, keyCount: number }> }; /** * Get the loading state for a locale * * @param locale - The locale to check * @returns The current loading state */ export declare function getLoadingState(locale: string): LoadingState; /** * Check if a locale is currently being loaded * * @param locale - The locale to check * @returns True if the locale is currently loading */ export declare function isLoading(locale: string): boolean; /** * Check if a locale has been loaded (cached) * * @param locale - The locale to check * @returns True if the locale is loaded and cached */ export declare function isLoaded(locale: string): boolean; /** * Preload translations for specified locales in the background. * This is non-blocking and returns immediately. * * @param config - Preload configuration * @param options - stx options with i18n configuration * @returns A promise that resolves when all preloading is complete * * @example * // Preload common locales in parallel * preloadTranslations({ * locales: ['en', 'es', 'fr', 'de'], * parallel: true, * onLocaleLoaded: (locale) => console.log(`${locale} ready`), * onComplete: () => console.log('All translations loaded') * }, options) * * @example * // Preload with priority (user's locale first) * preloadTranslations({ * locales: ['en', 'es', 'fr', 'de'], * parallel: false, * priority: { 'es': 10, 'en': 5 }, // Spanish first, then English * }, options) */ export declare function preloadTranslations(config: PreloadConfig, options: StxOptions): Promise<void>; /** * Start preloading translations in the background without blocking. * This function returns immediately and loads in the background. * * @param config - Preload configuration * @param options - stx options with i18n configuration * * @example * // Fire and forget background preloading * preloadTranslationsBackground({ * locales: ['en', 'es', 'fr'], * parallel: true * }, options) * // Execution continues immediately */ export declare function preloadTranslationsBackground(config: PreloadConfig, options: StxOptions): void; /** * Lazy load a translation file with deduplication. * If a load is already in progress for this locale, returns the existing promise. * This prevents multiple simultaneous loads of the same locale. * * @param locale - Locale code (e.g., 'en', 'fr', 'de') * @param options - stx options with i18n configuration * @returns Promise resolving to translation dictionary * * @example * // Multiple calls during loading period share the same promise * const p1 = loadTranslationLazy('en', options) * const p2 = loadTranslationLazy('en', options) * // p1 === p2 (same promise instance) */ export declare function loadTranslationLazy(locale: string, options: StxOptions): Promise<Record<string, any>>; /** * Get a translation synchronously if already cached, otherwise return undefined. * This is useful for non-blocking render patterns where you want to show * a fallback while translations load. * * @param locale - Locale code * @returns Cached translations or undefined if not loaded * * @example * const translations = getTranslationSync('en') * if (translations) { * // Use translations * } else { * // Show loading state or fallback * loadTranslationLazy('en', options).then(handleLoaded) * } */ export declare function getTranslationSync(locale: string): Record<string, any> | undefined; /** * Get translation with automatic loading. * Returns cached translations immediately if available, * otherwise loads them and returns. * * This is the recommended async API for most use cases. * * @param locale - Locale code * @param options - stx options * @returns Promise resolving to translations */ export declare function getTranslationAsync(locale: string, options: StxOptions): Promise<Record<string, any>>; /** * Wait for a locale to finish loading. * Useful when you've started a background preload and need to wait for it. * * @param locale - Locale to wait for * @param timeoutMs - Optional timeout in milliseconds * @returns Promise that resolves when loaded, or rejects on timeout/error * * @example * preloadTranslationsBackground({ locales: ['en', 'es'] }, options) * // ... later * await waitForLocale('en', 5000) // Wait up to 5 seconds */ export declare function waitForLocale(locale: string, timeoutMs?: number): Promise<Record<string, any>>; /** * Get all currently loading locales * * @returns Array of locale codes currently being loaded */ export declare function getLoadingLocales(): string[]; /** * Cancel pending translation loads (clears pending state). * Note: This doesn't actually abort HTTP requests, but clears tracking state. * * @param locale - Optional locale to cancel. If not provided, cancels all. */ export declare function cancelPendingLoads(locale?: string): void; /** * Load a translation file. * * This is the main entry point for loading translations. It uses lazy loading * with deduplication internally, so multiple calls for the same locale will * share the same promise. * * For more control over loading behavior, see: * - `loadTranslationLazy()` - Explicit lazy loading with deduplication * - `preloadTranslations()` - Preload multiple locales * - `getTranslationSync()` - Get cached translations without loading * - `getTranslationAsync()` - Get with automatic loading * * @param locale - Locale code (e.g., 'en', 'fr', 'de') * @param options - stx options with i18n configuration * @returns Translation dictionary */ export declare function loadTranslation(locale: string, options: StxOptions): Promise<Record<string, any>>; /** * ICU MessageFormat parser and formatter * * Supports: * - Simple replacement: {name} * - Plural: {count, plural, =0{none} one{# item} other{# items}} * - Select: {gender, select, male{He} female{She} other{They}} * - SelectOrdinal: {pos, selectordinal, one{#st} two{#nd} few{#rd} other{#th}} * - Number formatting: {amount, number} * - Date formatting: {date, date, short|medium|long|full} * * @example * formatICU('{count, plural, =0{No items} one{# item} other{# items}}', { count: 5 }) * // => '5 items' * * @example * formatICU('{gender, select, male{He} female{She} other{They}} liked this', { gender: 'female' }) * // => 'She liked this' */ export declare function formatICU(message: string, params?: Record<string, unknown>): string; /** * Check if a message uses ICU format */ export declare function isICUFormat(message: string): boolean; /** * Get a translation by key with parameter replacement and pluralization. * * Supports both Laravel-style (:param, |plural) and ICU MessageFormat. * * @param key - Dot-notation key (e.g., 'messages.welcome') * @param translations - Translation dictionary * @param fallbackToKey - Return key if translation not found * @param params - Parameters for replacement (use 'count' for pluralization) * @returns The translated string * * @example * // Simple parameter replacement * getTranslation('greeting', { greeting: 'Hello :name' }, true, { name: 'John' }) * // => 'Hello John' * * @example * // Pluralization (Laravel-style) * getTranslation('items', { items: 'One item|:count items' }, true, { count: 5 }) * // => '5 items' * * @example * // ICU MessageFormat * getTranslation('items', { items: '{count, plural, one{# item} other{# items}}' }, true, { count: 5 }) * // => '5 items' */ export declare function getTranslation(key: string, translations: Record<string, any>, fallbackToKey?: boolean, params?: Record<string, any>): string; /** * Process @translate directive */ export declare function processTranslateDirective(template: string, context: Record<string, any>, filePath: string, options: StxOptions): Promise<string>; /** * Create a translation filter for expressions */ export declare function createTranslateFilter(translations: Record<string, any>, fallbackToKey?: boolean): (value: string, params?: Record<string, any>) => string; // ============================================================================= // Configuration // ============================================================================= // Default i18n configuration export declare const defaultI18nConfig: I18nConfig; /** * Pending load tracking for deduplication */ declare interface PendingLoad { promise: Promise<Record<string, any>> state: LoadingState error?: Error } /** * Preload configuration */ export declare interface PreloadConfig { locales: string[] parallel?: boolean priority?: Record<string, number> onLocaleLoaded?: (locale: string) => void onComplete?: () => void onError?: (locale: string, error: Error) => void } /** * Loading state for async translation loading */ declare type LoadingState = 'idle' | 'loading' | 'loaded' | 'error'