UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

418 lines (417 loc) 14.8 kB
export default TinyI18; /** * Supported operating modes for TinyI18. * - `"local"` → All translations are managed entirely in memory (browser + Node.js). * - `"file"` → Translations are loaded from JSON files on disk (Node.js only). */ export type ModeTypes = "local" | "file"; /** * Dictionary of translation keys mapped to values. */ export type Dict = Record<string, any>; /** * `$pattern` - Regex string (will be compiled into RegExp). * * `$fn` - Helper function name associated with this entry. * * `[key]` - Additional key-value pairs for interpolation or extra metadata. */ export type FileValue = { $pattern: string; $fn: string; [key: string]: string; }; /** * Represents a valid locale code string. * Example: "en", "pt-BR", "fr". */ export type LocaleCode = string; /** * Represents a single regex-based translation entry. */ export type PatternEntry = { /** * - Compiled regular expression used for matching. */ $pattern: RegExp; /** * - Translation value or resolver function associated with the pattern. */ value: any; /** * - Translation value or resolver function associated with the pattern. */ elseValue: any; }; export type FileModeEntryJSON = { /** * - regex as string e.g. "^user\\.(\\d+)$" */ $pattern?: string | undefined; /** * - string or { $fn: string, args?: any } */ value: string | Object; /** * - string or { $fn: string, args?: any } */ elseValue: string | Object; }; export type TinyI18Options = { mode: ModeTypes; defaultLocale: LocaleCode; /** * - Required in file mode. Directory with <locale>.json */ basePath?: string | undefined; /** * - Optional initial map { locale: dict } for local mode */ localResources?: Dict | undefined; /** * - If true, throws on missing keys; else returns key */ strict?: boolean | undefined; }; export type ResolveOptions = { /** * - force resolve using a specific locale first */ locale?: string | undefined; }; /** * Represents statistics for a specific locale. */ export type StatLocale = { /** * - The locale code (e.g., "en", "pt-BR"). */ locale: string; /** * - Total number of static string entries in this locale. */ strings: number; /** * - Total number of regex-based pattern entries in this locale. */ patterns: number; /** * - Whether this locale is the default fallback. */ isDefault: boolean; /** * - Whether this locale is currently loaded/active. */ isCurrent: boolean; }; /** * Read-only view of registered helpers, exposed to function-based entries. * * Provides safe access to: * - check if a helper exists by name * - call a helper by name, passing arguments */ export type HelpersReadonly<T extends unknown, R extends unknown> = { /** * - Check if a helper with given name is registered. */ has?: ((name: string) => boolean) | undefined; /** * - * Invoke a helper by name with an argument and optional extras. */ call?: ((name: string, arg: T, extras?: HelpersReadonly<T, R>) => R) | undefined; }; /** * A helper callback function used in translations. * * - Receives user-supplied parameters and a read-only facade for calling other helpers. * - Must return a string (e.g. processed, interpolated, or formatted output). */ export type HelperCallback = (params: Dict, helpers: HelpersReadonly<any, any>) => string; /** * Supported operating modes for TinyI18. * - `"local"` → All translations are managed entirely in memory (browser + Node.js). * - `"file"` → Translations are loaded from JSON files on disk (Node.js only). * @typedef {"local" | "file"} ModeTypes */ /** * Dictionary of translation keys mapped to values. * * @typedef {Record<string, any>} Dict */ /** * Represents a translation entry as it appears in JSON files. * * @typedef {{ * $pattern: string, * $fn: string, * [key: string]: string * }} FileValue * * `$pattern` - Regex string (will be compiled into RegExp). * * `$fn` - Helper function name associated with this entry. * `[key]` - Additional key-value pairs for interpolation or extra metadata. */ /** * Represents a valid locale code string. * Example: "en", "pt-BR", "fr". * * @typedef {string} LocaleCode */ /** * Value types stored per locale: * - string: a direct translation with optional {named} interpolation * - Function: (params, helpers) => any (advanced rendering; HTML-safe if you control it) * - { $pattern: RegExp, value: string | { $fn: string, args?: any } | Function } * - { $fn: string, args?: any } // in file mode; resolved to a registered function */ /** * Represents a single regex-based translation entry. * * @typedef {Object} PatternEntry * @property {RegExp} $pattern - Compiled regular expression used for matching. * @property {any} value - Translation value or resolver function associated with the pattern. * @property {any} elseValue - Translation value or resolver function associated with the pattern. */ /** * @typedef {Object} FileModeEntryJSON * @property {string} [$pattern] - regex as string e.g. "^user\\.(\\d+)$" * @property {string|Object} value - string or { $fn: string, args?: any } * @property {string|Object} elseValue - string or { $fn: string, args?: any } */ /** * @typedef {Object} TinyI18Options * @property {ModeTypes} mode * @property {LocaleCode} defaultLocale * @property {string} [basePath] - Required in file mode. Directory with <locale>.json * @property {Dict} [localResources] - Optional initial map { locale: dict } for local mode * @property {boolean} [strict=true] - If true, throws on missing keys; else returns key */ /** * @typedef {Object} ResolveOptions * @property {LocaleCode} [locale] - force resolve using a specific locale first */ /** * Represents statistics for a specific locale. * * @typedef {Object} StatLocale * @property {string} locale - The locale code (e.g., "en", "pt-BR"). * @property {number} strings - Total number of static string entries in this locale. * @property {number} patterns - Total number of regex-based pattern entries in this locale. * @property {boolean} isDefault - Whether this locale is the default fallback. * @property {boolean} isCurrent - Whether this locale is currently loaded/active. */ /** * Read-only view of registered helpers, exposed to function-based entries. * * Provides safe access to: * - check if a helper exists by name * - call a helper by name, passing arguments * * @template {any} T * @template {any} R * @typedef {Object} HelpersReadonly * @property {(name: string) => boolean} [has] - Check if a helper with given name is registered. * @property {(name: string, arg: T, extras?: HelpersReadonly<T, R>) => R} [call] - * Invoke a helper by name with an argument and optional extras. */ /** * A helper callback function used in translations. * * - Receives user-supplied parameters and a read-only facade for calling other helpers. * - Must return a string (e.g. processed, interpolated, or formatted output). * * @callback HelperCallback * @param {Dict} params - Key-value parameters passed from the translation entry. * @param {HelpersReadonly<any, any>} helpers - Read-only access to other registered helpers. * @returns {string} Processed string result. */ /** * TinyI18 — Professional and flexible i18n manager with dual mode (local/file), * regex-based keys, and function-based entries for advanced rendering (incl. HTML). * * - Mode "local": in-memory resources (Node + Browser). * - Mode "file": JSON files on disk via fs/path (Node only). * - Keeps only default + selected locale in memory. * - Selected locale overrides default; fallback resolves to default. * - Supports string entries, regex pattern entries, and function-backed entries. * - Safe: no dynamic code eval from files; functions in file mode are referenced by name ("$fn"). */ declare class TinyI18 { /** * Merges multiple JSON locale files into a single file for TinyI18 usage. * @param {Object} options * @param {string[]} options.files - List of JSON file paths to merge. * @param {string} options.output - Path where the merged JSON file will be written. * @param {number} [options.spaces=0] - Number of spaces to use for indentation in the output file (0 for compact JSON). * @throws {TypeError} If arguments are invalid. * @throws {Error} If file reading or writing fails. */ static mergeLocaleFiles({ files, output, spaces }: { files: string[]; output: string; spaces?: number | undefined; }): Promise<void>; /** * Creates a new TinyI18 instance for managing localized strings and patterns. * * Supports two modes: * - "local": loads translations directly from provided objects. * - "file": loads translations from JSON files on demand. * * Ensures the default locale is always initialized. In "file" mode, `basePath` is required. * * @param {TinyI18Options} options - Configuration options for the instance. */ constructor(options: TinyI18Options); /** * Gets the currently selected locale, or null if only default is active. * @returns {LocaleCode|null} */ get currentLocale(): LocaleCode | null; /** * The default locale code chosen at construction time. * This locale is always kept in memory as a fallback. * @type {LocaleCode} */ get defaultLocale(): LocaleCode; /** * The current operating mode of this instance. * Determines whether translations are managed in memory ("local") * or loaded from JSON files ("file"). * @type {ModeTypes} */ get mode(): ModeTypes; /** * Whether strict mode is enabled. * - `true` → Missing keys, invalid regex, or helper errors throw exceptions. * - `false` → Failures are ignored silently, returning fallback values. * @type {boolean} */ get strict(): boolean; /** * Base directory path used in `"file"` mode to locate locale JSON files. * - In `"local"` mode this will always be `null`. * - In `"file"` mode this is the root folder passed to the constructor. * @type {string|null} */ get basePath(): string | null; /** * Returns basic stats for debugging/memory insights. * @returns {StatLocale[]} */ get stats(): StatLocale[]; /** * Deep-cloned view of string tables (Map → Object). * Preserves strings, $fn objects, and functions. * @returns {Record<string, Dict>} */ get stringTables(): Record<string, Dict>; /** * Deep-cloned view of pattern tables (Map → Object). * Recreates RegExp objects to avoid mutation. * @returns {Record<string, PatternEntry[]>} */ get patternTables(): Record<string, PatternEntry[]>; /** * Deep-cloned view of helpers (Map → Object). * Functions are referenced (cannot deep clone functions). * @returns {Record<string, HelperCallback>} */ get helpers(): Record<string, HelperCallback>; /** * Deep-cloned view of regex cache (Map → Object). * Recreates RegExp objects to avoid mutation. * @returns {Record<string, RegExp>} */ get regexCache(): Record<string, RegExp>; /** * Clears the internal regex cache. * * The regex cache stores compiled {@link RegExp} objects to avoid * recompiling frequently used patterns. This wrapper ensures cache * management is always controlled via the API instead of direct access. */ clearRegexCache(): void; /** * Registers a helper function available to function-based entries and $fn references. * @param {string} name * @param {HelperCallback} fn */ registerHelper(name: string, fn: HelperCallback): void; /** * Unregisters a previously registered helper function. * * If the helper does not exist, this method silently does nothing. * * @param {string} name - The name of the helper to remove. * @returns {boolean} `true` if the helper was removed, `false` if it was not found. */ unregisterHelper(name: string): boolean; /** * Loads or updates a locale data in-memory (local mode only). * @param {LocaleCode} locale * @param {Dict} data */ loadLocaleLocal(locale: LocaleCode, data: Dict): void; /** * Sets the current selected locale. In file mode, loads it from disk. * Keeps only the default and the selected locale in memory (unloads previous selected). * @param {LocaleCode|null} locale - null -> keep only default */ setLocale(locale: LocaleCode | null): Promise<void>; /** * Resolves a translation by exact key. * * Resolution order: * 1. Current locale (if set) * 2. Default locale (fallback) * * @param {string} key - Translation key (dot.notation). * @param {Dict} [params] - Parameters for string interpolation or helper functions. * @param {ResolveOptions} [options] - Override resolution options (e.g., force locale). * @returns {any} - Usually string, but may be HTMLElement, DocumentFragment, or any return type from a helper. */ t(key: string, params?: Dict, options?: ResolveOptions): any; /** * Alias of t() * @param {string} key * @param {Dict} [params] * @param {ResolveOptions} [options] * @returns {any} */ get(key: string, params?: Dict, options?: ResolveOptions): any; /** * Resolves a translation by regex pattern match. * * If multiple patterns exist, returns the first matching entry. * * @param {string} key - Input string to test against regex patterns. * @param {ResolveOptions} [options] - Override resolution options (e.g., force locale). * @returns {any} - Translation value (string or custom return type). */ p(key: string, options?: ResolveOptions): any; /** * Alias of p() * @param {string} key * @param {ResolveOptions} [options] * @returns {any} */ resolveByPattern(key: string, options?: ResolveOptions): any; /** * Clears everything except the default locale (keeps its data). * Selected locale becomes null. */ resetToDefaultOnly(): void; /** * Returns stats for a specific locale. * @param {LocaleCode} locale * @returns {StatLocale} * @throws {Error} If the locale is not registered. */ getStatsForLocale(locale: LocaleCode): StatLocale; #private; } //# sourceMappingURL=TinyI18.d.mts.map