reslib 2.0.3 → 2.1.1

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 (37) hide show
  1. package/build/auth/index.js +2 -2
  2. package/build/countries/index.js +2 -2
  3. package/build/currency/index.js +2 -2
  4. package/build/currency/session.js +2 -2
  5. package/build/exception/index.js +2 -2
  6. package/build/i18n/index.d.ts +399 -563
  7. package/build/i18n/index.js +2 -2
  8. package/build/i18n/types.d.ts +100 -0
  9. package/build/inputFormatter/index.js +2 -2
  10. package/build/logger/index.js +2 -2
  11. package/build/resources/index.d.ts +8 -46
  12. package/build/resources/index.js +3 -3
  13. package/build/types/index.d.ts +0 -1
  14. package/build/utils/date/dateHelper.js +2 -2
  15. package/build/utils/date/index.js +2 -2
  16. package/build/utils/index.js +3 -3
  17. package/build/utils/interpolate.d.ts +31 -1
  18. package/build/utils/interpolate.js +1 -1
  19. package/build/utils/numbers.js +2 -2
  20. package/build/validator/index.js +3 -3
  21. package/build/validator/rules/array.js +2 -2
  22. package/build/validator/rules/boolean.js +2 -2
  23. package/build/validator/rules/date.js +2 -2
  24. package/build/validator/rules/default.js +2 -2
  25. package/build/validator/rules/enum.js +2 -2
  26. package/build/validator/rules/file.js +2 -2
  27. package/build/validator/rules/format.js +3 -3
  28. package/build/validator/rules/index.js +3 -3
  29. package/build/validator/rules/multiRules.js +2 -2
  30. package/build/validator/rules/numeric.js +2 -2
  31. package/build/validator/rules/object.js +2 -2
  32. package/build/validator/rules/string.js +2 -2
  33. package/build/validator/rules/target.js +2 -2
  34. package/build/validator/validator.js +2 -2
  35. package/package.json +1 -2
  36. package/build/types/i18n.d.ts +0 -121
  37. /package/build/{types/i18n.js → i18n/types.js} +0 -0
@@ -1,648 +1,484 @@
1
- import { Observable, ObservableCallback } from '../observable';
2
- import { Dict, I18n as I18nJs, I18nOptions, Scope, TranslateOptions } from 'i18n-js';
3
1
  import { LocaleSpecification } from 'moment';
4
2
  import 'reflect-metadata';
5
- import { I18nEvent, I18nTranslation } from '../types/i18n';
6
3
  import { ClassConstructor, Dictionary } from '../types/index';
7
- /**
8
- * A decorator to attach metadata to properties or methods for translation.
9
- * @param key The translation key in the translations.
10
- * @returns A property and method decorator.
11
- * @example
12
- * ```ts
13
- * // Class with translations using the decorator
14
- class MyComponent {
15
- @Translate("greeting")
16
- public greeting: string;
17
-
18
- @Translate("nested.example")
19
- public nestedExample: string;
20
-
21
- @Translate("farewell")
22
- public sayGoodbye(): string {
23
- return "";
24
- }
25
- }
26
- * ```
27
- */
28
- export declare function Translate(key: string): PropertyDecorator & MethodDecorator;
29
- /**
30
- * The I18n class extends the i18n-js library to provide internationalization (i18n)
31
- * functionality with observable capabilities. It manages translations, allows for
32
- * dynamic loading of language dictionaries, and supports event-driven architecture
33
- * through observable patterns.
34
- *
35
- * @extends I18nJs
36
- * @implements Observable<I18nEvent>
37
- *
38
- * @example
39
- * // Example usage of the I18n class
40
- * const i18nInstance = I18n.getInstance();
41
- * i18nInstance.registerTranslations({
42
- * en: {
43
- * greeting: "Hello, %{name}!",
44
- * farewell: "Goodbye!",
45
- * },
46
- * });
47
- * console.log(i18nInstance.translate("greeting", { name: "John" })); // Outputs: Hello, John!
48
- * @see https://www.npmjs.com/package/i18n-js?activeTab=readme for more information on i18n-js library.
49
- */
50
- export declare class I18n extends I18nJs implements Observable<I18nEvent> {
4
+ import { I18nFormatter, I18nNamespaceResolver, I18nScope, I18nTranslateOptions, I18nTranslations } from './types';
5
+ export declare class I18n {
6
+ constructor(translations?: I18nTranslations, options?: Partial<I18nOptions>);
51
7
  /**
52
- * Custom instanceof check. When consumers import `I18n` from built packages or
53
- * across module boundaries, class identity can differ. Using Symbol.hasInstance
54
- * allows `instanceof I18n` to succeed if the object has the required i18n API
55
- * shape (duck typing). This preserves `instanceof` checks externally while
56
- * keeping the current exported API intact.
8
+ * Custom instanceof check. Checks if an object looks like an I18n instance.
9
+ * @param obj The object to check.
57
10
  */
58
11
  static [Symbol.hasInstance](obj: any): obj is I18n;
59
12
  /**
60
13
  * Type guard to check if an object is an instance of I18n.
61
- * Uses duck typing to verify the object has the required i18n methods,
62
- * allowing for cross-realm compatibility when instanceof checks fail.
14
+ * Uses duck typing.
63
15
  * @param obj The object to check.
64
- * @returns True if the object is an I18n instance, false otherwise.
65
16
  */
66
17
  static isI18nInstance(obj: any): obj is I18n;
67
18
  /**
68
- * Translates the given scope with the provided options.
69
- * If the scope is a string and the options include pluralization, the method will pluralize the translation.
70
- * Otherwise, it will call the parent `translate` method.
71
- * @param scope The translation scope.
72
- * @param options The translation options, including pluralization.
73
- * @returns The translated string or the type specified in the generic parameter.
74
- * @example
75
- * // Register translations for the "en" locale.
76
- * i18n.registerTranslations({
77
- * en: {
78
- * greeting: {
79
- * one: "Hello, %{name}!",
80
- * other: "Hello, %{name}s!",
81
- * zero: "Hello, %{name}s!"
82
- * },
83
- * farewell: "Goodbye!"
84
- * }
85
- * });
19
+ * Retrieves the singleton instance of the I18n class.
20
+ * @param options Optional configuration options.
21
+ * @returns The singleton I18n instance.
22
+ */
23
+ static getInstance(options?: Partial<I18nOptions>): I18n;
24
+ /**
25
+ * Factory method to create new I18n instances dynamically.
26
+ * @param translations Initial translations.
27
+ * @param options Configuration options.
28
+ * @returns A new I18n instance.
29
+ */
30
+ static createInstance(translations?: I18nTranslations, options?: Partial<I18nOptions>): I18n;
31
+ /**
32
+ * Flattens a nested object into a single-level object with dot-notation keys.
33
+ * @param obj Object to flatten.
34
+ */
35
+ static flattenObject(obj: any): Dictionary;
36
+ /**
37
+ * Retrieves the user's locale from the active session.
38
+ * @returns The locale string if found, otherwise `undefined`.
39
+ */
40
+ static getLocaleFromSession(): string | undefined;
41
+ /**
42
+ * Registers a custom Moment.js locale specification.
86
43
  *
87
- * // Translate the "greeting" scope with pluralization.
88
- * i18n.translate("greeting", { count: 1 }); // "Hello, John!"
89
- * i18n.translate("greeting", { count: 2 }); // "Hello, Johns!"
90
- * i18n.translate("greeting", { count: 0 }); // "Hello, Johns!"
44
+ * This allows defining locale-specific date/time formatting rules (months, weekdays, etc.)
45
+ * that will be applied when the locale is active.
91
46
  *
92
- * // Translate the "farewell" scope.
93
- * i18n.translate("farewell"); // "Goodbye!"
47
+ * @param locale - The locale code (e.g., "fr").
48
+ * @param momentLocale - The Moment.js locale specification object.
49
+ * @returns The updated dictionary of registered moment locales.
94
50
  */
95
- translate<T = string>(scope: Scope, options?: TranslateOptions): string | T;
96
- /***
97
- * Translates the keys of the given target class.
98
- * @param target The target class.
99
- * @param options The translation options.
100
- * @returns The translated keys.
51
+ static registerMomentLocale(locale: string, momentLocale: LocaleSpecification): Record<string, LocaleSpecification>;
52
+ /**
53
+ * Retrieves translation keys defined via `@Translate` decorators on a class.
54
+ *
55
+ * @template T - The class constructor type.
56
+ * @param target - The class to inspect.
57
+ * @returns A record of property names to translation keys.
101
58
  */
102
- translateClass<T extends ClassConstructor>(target: T, options?: TranslateOptions): Record<keyof T, string>;
59
+ static getClassTanslationKeys<T extends ClassConstructor>(target: T): Record<keyof InstanceType<T>, string>;
103
60
  /**
104
- * Translates an object containing translation keys as values.
105
- * This method takes an object where each property value is expected to be a translation key,
106
- * and returns a new object with the same structure but with translated values.
61
+ * Optional custom interpolation function.
107
62
  *
108
- * @template T - The type of the input object, extending Record<string, string>
109
- * @param object - The object containing translation keys as values to be translated
110
- * @param {TranslateOptions} options - additional options to pass to the i18n.translate function
111
- * @returns A new object with the same keys but translated values
63
+ * If provided, this function handles the replacement of placeholders in the translation string.
64
+ * It overrides the default `%{key}` interpolation.
112
65
  *
113
- * @example
114
- * ```typescript
115
- * // Register translations first
116
- * i18n.registerTranslations({
117
- * en: {
118
- * 'user.name': 'Name',
119
- * 'user.email': 'Email Address',
120
- * 'user.phone': 'Phone Number',
121
- * 'actions.save': 'Save',
122
- * 'actions.cancel': 'Cancel'
123
- * },
124
- * fr: {
125
- * 'user.name': 'Nom',
126
- * 'user.email': 'Adresse Email',
127
- * 'user.phone': 'Numéro de Téléphone',
128
- * 'actions.save': 'Enregistrer',
129
- * 'actions.cancel': 'Annuler'
130
- * }
131
- * });
66
+ * @param i18n - The I18n instance.
67
+ * @param str - The string to interpolate.
68
+ * @param params - The interpolation parameters.
69
+ * @returns The interpolated string.
70
+ */
71
+ interpolateFunc?: (i18n: I18n, str: string, params: Dictionary) => string;
72
+ /**
73
+ * Callback for handling missing placeholders/keys.
132
74
  *
133
- * // Define an object with translation keys
134
- * const formLabels = {
135
- * name: 'user.name',
136
- * email: 'user.email',
137
- * phone: 'user.phone'
138
- * };
75
+ * If defined, this function is called when a translation key (or placeholder) is not found.
76
+ * It provides a hook to log warnings, report errors, or provide custom fallback text.
139
77
  *
140
- * // Translate the object
141
- * const translatedLabels = i18n.translateObject(formLabels);
142
- * console.log(translatedLabels);
143
- * // Output (for 'en' locale): { name: 'Name', email: 'Email Address', phone: 'Phone Number' }
144
- * // Output (for 'fr' locale): { name: 'Nom', email: 'Adresse Email', phone: 'Numéro de Téléphone' }
78
+ * @param i18n - The I18n instance.
79
+ * @param placeholder - The missing key or placeholder.
80
+ * @param message - The default message/fallback.
81
+ * @param options - Context options.
82
+ */
83
+ missingPlaceholder?: (i18n: I18n, placeholder: string, message: string, options?: Dictionary) => string;
84
+ /**
85
+ * Translates a single key or a list of keys with support for pluralization and interpolation.
145
86
  *
146
- * // Can also be used with button configurations
147
- * const buttonConfig = {
148
- * saveButton: 'actions.save',
149
- * cancelButton: 'actions.cancel'
150
- * };
151
- * const translatedButtons = i18n.translateObject(buttonConfig);
152
- * // Output (for 'en' locale): { saveButton: 'Save', cancelButton: 'Cancel' }
153
- * ```
87
+ * This is the core method for retrieving localized strings. It executes the following logic:
88
+ * 1. **Key Resolution**: Searches for the key in the current locale. If not found, checks for a fallback locale.
89
+ * 2. **Fallback**: If the key is missing, looks for `options.defaultValue` or follows the missing key strategy (returns key).
90
+ * 3. **Pluralization**: If `options.count` is provided, it attempts to find and return the pluralized form (zero, one, other).
91
+ * 4. **Interpolation**: Replaces placeholders (e.g. `%{name}`) with values from `options`.
154
92
  *
155
- * @example
156
- * ```typescript
157
- * // Advanced usage with form validation messages
158
- * const validationMessages = {
159
- * required: 'validation.required',
160
- * email: 'validation.email.invalid',
161
- * minLength: 'validation.minLength',
162
- * maxLength: 'validation.maxLength'
163
- * };
93
+ * @template T - The expected return type (defaults to `string`).
94
+ * @param scope - The translation key (e.g. "auth.login") or an array of keys to try in order.
95
+ * @param options - Configuration options (interpolation params, `count` for pluralization, `locale`, etc).
96
+ * @returns The resolved translation string (or type `T`), interpolated and formatted.
164
97
  *
165
- * // Assuming you have registered validation translations
166
- * const translatedValidation = i18n.translateObject(validationMessages);
167
- * // This allows you to easily get all validation messages in the current locale
168
- * ```
98
+ * @example
99
+ * // Basic
100
+ * i18n.translate("welcome");
169
101
  *
170
- * @note If the input object is not a valid object, an empty object of type T is returned.
171
- * @note Only string values that are non-null and non-empty are translated; other values are skipped.
172
- * @note This method is particularly useful for translating configuration objects, form labels,
173
- * button texts, or any structured data containing translation keys.
102
+ * @example
103
+ * // Interpolation & Pluralization
104
+ * i18n.translate("messages.inbox", { count: 3, user: "Alice" });
105
+ * // "Alice, you have 3 messages"
106
+ */
107
+ translate<T = string>(scope: I18nScope, options?: I18nTranslateOptions): T;
108
+ /**
109
+ * An alias for `translate`.
174
110
  *
175
- * @see {@link translateClass} for translating class properties decorated with @Translate
176
- * @see {@link t} for translating individual keys with interpolation support
111
+ * A concise helper method for calling {@link translate}.
177
112
  *
113
+ * @see {@link translate}
114
+ * @param scope - The translation key or keys.
115
+ * @param options - Translation options.
116
+ * @returns The translated result.
178
117
  */
179
- translateObject<T extends Record<string, string>>(object: T, options?: TranslateOptions): T;
180
- /***
181
- * returns the translation keys for the target class
182
- * @param target the target class
183
- * @returns the translation keys for the target class
184
- */
185
- static getClassTanslationKeys<T extends ClassConstructor>(target: T): Record<keyof T, string>;
186
- private _isLoading;
187
- /***
188
- * locales that are superted by the i18n instance
118
+ t(scope: I18nScope, options?: I18nTranslateOptions): string;
119
+ /**
120
+ * Checks if a translation key exists in the store.
121
+ *
122
+ * @param scope - The key or array of keys to check.
123
+ * @param locale - Optional locale to check in (defaults to current).
124
+ * @returns `true` if the translation exists, `false` otherwise.
189
125
  */
190
- private _locales;
126
+ has(scope: I18nScope, locale?: string): boolean;
191
127
  /**
192
- * Namespace resolvers for loading translations.
128
+ * Gets the currently active locale.
129
+ * @returns The language code of the current locale (e.g. "en").
193
130
  */
194
- private namespaceResolvers;
131
+ getLocale(): string;
195
132
  /**
196
- * Singleton instance of the I18n class.
133
+ * Sets the active locale and triggers necessary updates.
134
+ *
135
+ * This method performs several actions:
136
+ * 1. Loads required namespaces for the new locale (if resolvers are registered).
137
+ * 2. Updates the internal `locale` state.
138
+ * 3. Persists the locale to the session (if default instance).
139
+ * 4. Updates the global Moment.js locale.
140
+ *
141
+ * @param locale - The new locale to set.
142
+ * @param forceUpdate - If true, reloads namespaces even if the locale is already active.
143
+ * @returns A promise that resolves to the new locale string.
197
144
  */
198
- private static instance;
145
+ setLocale(locale: string, forceUpdate?: boolean): Promise<string>;
199
146
  /**
200
- * Creates an instance of the I18n class.
201
- * @param options Optional configuration options for the I18n instance.
202
- */
203
- constructor(translations?: I18nTranslation, options?: Partial<I18nOptions>);
204
- readonly _observableFactory: {
205
- _____isObservable?: boolean;
206
- on: (event: I18nEvent, fn: ObservableCallback) => {
207
- remove: () => any;
208
- };
209
- finally: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
210
- off: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
211
- trigger: (event: "*" | I18nEvent, ...args: any[]) => /*elided*/ any;
212
- offAll: () => /*elided*/ any;
213
- once: (event: I18nEvent, fn: ObservableCallback) => {
214
- remove: () => any;
215
- };
216
- getEventCallBacks: () => Partial<Record<"*" | I18nEvent, ObservableCallback[]>>;
217
- };
218
- readonly _____isObservable?: boolean | undefined;
219
- /**
220
- * Subscribes a callback function to a specific event.
221
- * @param event The event name to listen for.
222
- * @param fn The callback function to be invoked when the event is triggered.
223
- * @returns An object containing a remove method to unsubscribe from the event.
224
- */
225
- on(event: I18nEvent, fn: ObservableCallback): {
226
- remove: () => any;
227
- };
228
- /**
229
- * Registers a callback to be invoked finally when an event is triggered.
230
- * @param event The event name.
231
- * @param fn The callback function to be invoked.
232
- * @returns The observable instance.
233
- */
234
- finally(event: I18nEvent, fn: ObservableCallback): {
235
- _____isObservable?: boolean;
236
- on: (event: I18nEvent, fn: ObservableCallback) => {
237
- remove: () => any;
238
- };
239
- finally: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
240
- off: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
241
- trigger: (event: "*" | I18nEvent, ...args: any[]) => /*elided*/ any;
242
- offAll: () => /*elided*/ any;
243
- once: (event: I18nEvent, fn: ObservableCallback) => {
244
- remove: () => any;
245
- };
246
- getEventCallBacks: () => Partial<Record<"*" | I18nEvent, ObservableCallback[]>>;
247
- };
248
- /**
249
- * Unsubscribes a callback from a specific event.
250
- * @param event The event name.
251
- * @param fn The callback function to remove.
252
- * @returns The observable instance.
253
- */
254
- off(event: I18nEvent, fn: ObservableCallback): {
255
- _____isObservable?: boolean;
256
- on: (event: I18nEvent, fn: ObservableCallback) => {
257
- remove: () => any;
258
- };
259
- finally: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
260
- off: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
261
- trigger: (event: "*" | I18nEvent, ...args: any[]) => /*elided*/ any;
262
- offAll: () => /*elided*/ any;
263
- once: (event: I18nEvent, fn: ObservableCallback) => {
264
- remove: () => any;
265
- };
266
- getEventCallBacks: () => Partial<Record<"*" | I18nEvent, ObservableCallback[]>>;
267
- };
268
- /**
269
- * Triggers a specific event with optional arguments.
270
- * @param event The event name to trigger.
271
- * @param args Optional arguments to pass to the event callbacks.
272
- * @returns The observable instance.
273
- */
274
- trigger(event: I18nEvent | '*', ...args: any[]): {
275
- _____isObservable?: boolean;
276
- on: (event: I18nEvent, fn: ObservableCallback) => {
277
- remove: () => any;
278
- };
279
- finally: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
280
- off: (event: I18nEvent, fn: ObservableCallback) => /*elided*/ any;
281
- trigger: (event: "*" | I18nEvent, ...args: any[]) => /*elided*/ any;
282
- offAll: () => /*elided*/ any;
283
- once: (event: I18nEvent, fn: ObservableCallback) => {
284
- remove: () => any;
285
- };
286
- getEventCallBacks: () => Partial<Record<"*" | I18nEvent, ObservableCallback[]>>;
287
- };
288
- /**
289
- * Unsubscribes all event callbacks for this component.
290
- * @returns The observable instance.
291
- */
292
- offAll(): Observable<I18nEvent>;
293
- /**
294
- * Subscribes a callback function to be triggered once for a specific event.
295
- * @param event The event name.
296
- * @param fn The callback function to be invoked.
297
- * @returns An object containing a remove method to unsubscribe from the event.
298
- */
299
- once(event: I18nEvent, fn: ObservableCallback): {
300
- remove: () => any;
301
- };
302
- /**
303
- * Retrieves all registered event callbacks.
304
- * @returns An object mapping event names to their respective callback functions.
305
- */
306
- getEventCallBacks(): Partial<Record<"*" | I18nEvent, ObservableCallback[]>>;
147
+ * Defines the list of supported locales.
148
+ *
149
+ * Ensures that "en" (default) is always included in the supported list.
150
+ *
151
+ * @param locales - An array of locale codes.
152
+ * @returns The updated list of supported locales.
153
+ */
154
+ setLocales(locales: string[]): string[];
307
155
  /**
308
- * Retrieves the singleton instance of the I18n class.
309
- * @returns The singleton I18n instance.
156
+ * Retrieves all available locales.
157
+ *
158
+ * Combines the explicitly supported locales (set via `setLocales`) with any
159
+ * locales discovered in the loaded translation store.
160
+ *
161
+ * @returns A unique list of all known locale codes.
310
162
  */
311
- static getInstance(options?: I18nOptions): I18n;
312
- /***
313
- * returns true if the instance is the default instance.
314
- * @returns true if the instance is the default instance.
163
+ getLocales(): string[];
164
+ /**
165
+ * Checks if a specific locale is supported and known.
166
+ *
167
+ * @param locale - The locale code to check.
168
+ * @returns `true` if the locale is in the supported/available list.
315
169
  */
170
+ hasLocale(locale: string): boolean;
316
171
  isDefaultInstance(): boolean;
317
- private static setLocaleToSession;
318
- static getLocaleFromSession(): any;
319
- /**
320
- * Checks if the provided translation key can be pluralized for the given locale.
321
- * @param scope The translation scope to check.
322
- * @param locale The locale to use for the check. If not provided, the current locale is used.
323
- * @returns `true` if the translation key can be pluralized, `false` otherwise.
324
- * @note This method is useful for determining if a translation key can be pluralized for a specific locale.
325
- * A translation key can be pluralized if it has pluralization rules defined in the translation dictionary.
326
- * The pluralization rules are defined in the `one`, `other`, and `zero` properties of the translation dictionary.
172
+ /**
173
+ * Registers and merges new translations into the global store.
174
+ *
175
+ * This method merges the provided translation object with the existing translations.
176
+ * New keys are added, and existing keys are updated (overwritten).
177
+ *
178
+ * @param translations - The translations to register, grouped by locale.
179
+ * @returns The updated translation store.
180
+ *
327
181
  * @example
328
- * //register a translation dictionary for the "en" locale.
329
182
  * i18n.registerTranslations({
330
- * en: {
331
- * greeting: {
332
- * one: "Hello, {name}!",
333
- * other: "Hello, {name}s!",
334
- * zero: "Hello, {name}s!"
335
- * },
336
- * farewell: "Goodbye!"
337
- * }
338
- * );
183
+ * en: { title: "Welcome" },
184
+ * fr: { title: "Bienvenue" }
339
185
  * });
340
- * // Check if the translation key "greeting" can be pluralized for the current locale.
341
- * i18n.canPluralize("greeting");
342
- *
343
- * // Check if the translation key "greeting" can be pluralized for the "en" locale.
344
- * i18n.canPluralize("greeting", "en");
345
- * i18n.canPluralize("greeting", "fr"); // returns false
346
- * i18n.canPluralize("farewell", "en"); // returns false
347
186
  */
348
- canPluralize(scope: Scope, locale?: string): boolean;
187
+ registerTranslations(translations: I18nTranslations): I18nTranslations;
349
188
  /**
350
- * Checks if the provided translation key exists for the given locale.
351
- * @since 1.1.1
352
- * @param scope The translation scope to check.
353
- * @param locale The locale to use for the check. If not provided, the current locale is used.
354
- * @returns `true` if the translation key exists, `false` otherwise.
189
+ * Retrieves specific translations or the entire store.
190
+ *
191
+ * @param locale - The locale to retrieve translations for. If omitted, returns the entire store.
192
+ * @returns A dictionary of translations (for a locale) or the full store (if no locale provided).
355
193
  */
356
- has(scope: Scope, locale?: string): boolean;
194
+ getTranslations(locale?: string): Dictionary;
357
195
  /**
358
- * Resolves translation for nested keys.
359
- * @param scope {Scope} The translation scope.
360
- * @param locale The locale to use for translation.
361
- * @returns The translated string or undefined if not found.
362
- * @example
363
- * // Register translations for the "en" locale.
364
- * i18n.registerTranslations({
365
- * en: {
366
- * greeting: {
367
- * one: "Hello, {name}!",
368
- * other: "Hello, {name}s!",
369
- * zero: "Hello, {name}s!"
370
- * },
371
- * farewell: "Goodbye!"
372
- * }
373
- * });
374
- *
375
- * // Resolve translation for the "greeting" key.
376
- * i18n.getNestedTranslation("greeting.one", "en");
377
- *
378
- * // Resolve translation for the "greeting" key.
379
- * i18n.getNestedTranslation("greeting.other", "en");
196
+ * Registers a function to lazily load translations for a specific namespace.
380
197
  *
381
- * // Resolve translation for the "greeting" key.
382
- * i18n.getNestedTranslation("en", "greeting.zero", 0);
198
+ * The resolver function is called when `loadNamespace` is invoked. It should return
199
+ * a promise resolving to a dictionary of translations.
383
200
  *
384
- * // Resolve translation for the "farewell" key.
385
- * i18n.getNestedTranslation("en", "farewell");
201
+ * @param {string} namespace - The unique name of the namespace.
202
+ * @param {I18nNamespaceResolver} resolver - The async function that fetches translations.
386
203
  */
387
- getNestedTranslation<T = string | Dictionary>(scope: Scope, locale?: string): T | undefined;
204
+ registerNamespaceResolver(namespace: string, resolver: I18nNamespaceResolver): void;
388
205
  /**
389
- * Checks if the provided `TranslateOptions` object has a `count` property of type `number`.
390
- * This is used to determine if the translation should be pluralized based on the provided count.
391
- * @param options The `TranslateOptions` object to check.
392
- * @returns `true` if the `options` object has a `count` property of type `number`, `false` otherwise.
206
+ * Loads translations for a specific namespace and merges them into the store.
207
+ *
208
+ * @param namespace - The namespace to load.
209
+ * @param locale - The locale to load for (defaults to current).
210
+ * @param updateTranslations - If true, automatically registers the loaded translations.
211
+ * @returns A promise resolving to the dictionary of loaded translations.
393
212
  */
394
- isPluralizeOptions(options?: TranslateOptions): options is TranslateOptions;
395
- /**
396
- * static function to attach translations to the I18n default instance.
397
- @example :
398
- // --- Usage as a decorator ---
399
- I18n.RegisterTranslations({
400
- de: {
401
- greeting: "Hallo, {name}!",
402
- farewell: "Auf Wiedersehen!",
403
- },
404
- })
405
- * @param translations The language translations.
406
- */
407
- static RegisterTranslations(translations: I18nTranslation): I18nTranslation;
213
+ loadNamespace(namespace: string, locale?: string, updateTranslations?: boolean): Promise<Dictionary>;
408
214
  /**
409
- * Factory method to create I18n instances dynamically.
410
- * @param options Optional configuration options for the I18n instance.
411
- * @returns A new I18n instance.
215
+ * Loads all registered namespaces for a specific locale.
216
+ *
217
+ * Executes all registered namespace resolvers concurrently.
218
+ *
219
+ * @param locale - The locale to load.
220
+ * @param updateTranslations - If true, updates the store with results.
221
+ * @returns A promise resolving to the combined translations from all namespaces.
412
222
  */
413
- static createInstance(translations?: I18nTranslation, options?: Partial<I18nOptions> & {
414
- interpolate?: (i18n: I18nJs, str: string, params: Dictionary) => string;
415
- }): I18n;
223
+ loadNamespaces(locale?: string, updateTranslations?: boolean): Promise<I18nTranslations>;
416
224
  /**
417
- * Gets the translations for the specified locale, or all translations if no locale is provided.
418
- * @param locale The locale to get translations for. If not provided, returns all translations.
419
- * @returns The translations for the specified locale, or all translations if no locale is provided.
225
+ * Retrieves a raw translation value or object from the store for a specific scope and locale.
226
+ *
227
+ * This method provides direct access to the translation structure without performing
228
+ * interpolation, pluralization, or missing key fallbacks. It strictly traverses
229
+ * the object tree based on the provided dot-separated scope or array path.
230
+ *
231
+ * It is particularly useful for:
232
+ * - Retrieving entire sections of translations (e.g., a dictionary of validation messages).
233
+ * - Accessing lists/arrays defined in the localization files.
234
+ * - Checking if a specific key or branch exists in the store.
235
+ *
236
+ * Key Resolution:
237
+ * - Dots in the scope string are ALWAYS treated as separators (traversal).
238
+ * - To match keys containing literal dots, use `lookup` internally or ensure your store structure matches.
239
+ *
240
+ * @template T - The expected return type (defaults to `string | Dictionary`).
241
+ * @param scope - The path to the value. Can be a dot-separated string (e.g., "auth.login.title")
242
+ * or an array of keys (e.g., ["auth", "login"]).
243
+ * @param locale - The locale to search in. Defaults to the current instance locale if omitted.
244
+ * @returns The value at the specified path cast to `T`, or `undefined` if resolution fails.
245
+ *
420
246
  * @example
421
- * // Get all translations
422
- * const translations = i18n.getTranslations();
423
- * console.log(translations);
247
+ * // Get a simple string
248
+ * const title = i18n.get("app.title");
424
249
  *
425
- * // Get translations for the "en" locale
426
- * const enTranslations = i18n.getTranslations("en");
427
- * console.log(enTranslations);
428
- */
429
- getTranslations(locale?: string): any;
430
- /***
431
- * list of registered moment locales
432
- */
433
- private static momentLocales;
434
- private hasRegisteredDefaultTranslations;
435
- /***
436
- * register a moment locale
437
- * @param {string} locale
438
- * @param {LocaleSpecification} momentLocale
439
- * @see https://momentjs.com/docs/#/customization/ for more information on customizing moment locales
440
- * @see https://momentjs.com/docs/#/i18n/ for more information on moment locales
441
- * @returns
442
- */
443
- static registerMomentLocale(locale: string, momentLocale: LocaleSpecification): Record<string, LocaleSpecification>;
444
- /***
445
- * get a registered moment locale
446
- * @param {string} locale
447
- * @returns {LocaleSpecification}
448
- */
449
- static getMomentLocale(locale: string): LocaleSpecification;
450
- /***
451
- * set a moment locale. the locale is picked from the momentLocales list
452
- * @param {string} locale
453
- * @param {Moment} momentInstance, The moment instance to set the locale on
454
- * @returns {boolean}
250
+ * @example
251
+ * // Get a full dictionary object
252
+ * const validationMessages = i18n.get<Dictionary>("validation");
253
+ * // Result: { required: "Field is required", email: "Invalid email" }
254
+ *
255
+ * @example
256
+ * // Get from a specific locale (e.g. 'fr')
257
+ * const label = i18n.get("button.submit", "fr");
455
258
  */
456
- static setMomentLocale(locale: string): boolean;
259
+ get<T = string | Dictionary>(scope: I18nScope, locale?: string): T | undefined;
457
260
  /**
458
- * Registers translations into the I18n manager.
459
- * @param translations The translations to register.
460
- * @returns The updated translations.
261
+ * Resolves and translates properties decorated with `@Translate` on a specific class.
262
+ *
263
+ * This method uses reflection to find properties on the `target` that have been decorated
264
+ * with the `@Translate` decorator. It retrieves the translation keys stored in the metadata,
265
+ * translates them using the current locale and options, and returns a mapped object.
266
+ *
267
+ * **Note**: This does NOT modify the class itself. It returns a separate object containing
268
+ * the translated values for the decorated properties.
269
+ *
270
+ * Use Cases:
271
+ * - Fetching all localized labels for a specific component or form class.
272
+ * - aggregating static translation requirements for a module.
273
+ *
274
+ * @template T - The constructor type of the target class.
275
+ * @param target - The class constructor to inspect for `@Translate` decorators.
276
+ * @param options - Optional translation options (arguments, locale) to apply to all keys.
277
+ * @returns A dictionary mapping the property names to their translated string values.
278
+ *
279
+ * @example
280
+ * class AuthForm {
281
+ * @Translate("auth.title")
282
+ * static formTitle: string;
283
+ *
284
+ * @Translate("auth.submit")
285
+ * static submitBtn: string;
286
+ * }
287
+ *
288
+ * const texts = i18n.translateClass(AuthForm);
289
+ * // Returns: { formTitle: "Login", submitBtn: "Sign In" }
461
290
  */
462
- registerTranslations(translations: I18nTranslation): I18nTranslation;
291
+ translateClass<T extends ClassConstructor>(target: T, options?: I18nTranslateOptions): Record<keyof InstanceType<T>, string>;
463
292
  /**
464
- * Stores the provided translations and triggers a "translations-changed" event with the current locale and translations.
465
- * @param translations The translations to store.
293
+ * Translates the string values of a given object, treating them as translation keys.
294
+ *
295
+ * This method iterates over the provided object's properties. If a property value is a string,
296
+ * it treats that string as a translation scope (key) and attempts to translate it using the
297
+ * current or specified locale.
298
+ *
299
+ * Key Behaviors:
300
+ * - **Shallow Processing**: It processes only the top-level properties of the object. It does not recurse into nested objects.
301
+ * - **Immutability**: It returns a new object with the translated values, ensuring the original object remains unmodified.
302
+ * - **Type Safety**: It is typed to accept objects where values are strings (translation keys).
303
+ * - **Filtering**: Only non-null string values are processed and included in the result. Non-string values are omitted.
304
+ *
305
+ * Use cases:
306
+ * - specific dictionaries of labels (e.g. for dropdown options or map keys).
307
+ * - Batch translating a set of related keys.
308
+ *
309
+ * @template T - The type of the object (must extend Record<string, string>).
310
+ * @param object - The object containing translation keys as values.
311
+ * @param options - Optional translations options (e.g., interpolation parameters) that will be applied to EVERY translation in the object.
312
+ * @returns A new object with the same keys but translated values.
313
+ *
314
+ * @example
315
+ * const keys = {
316
+ * welcome: "app.welcome",
317
+ * goodbye: "app.goodbye"
318
+ * };
319
+ *
320
+ * const texts = i18n.translateObject(keys);
321
+ * // Returns: { welcome: "Welcome!", goodbye: "Goodbye!" }
322
+ *
323
+ * @example
324
+ * // Using interpolation parameters for all keys
325
+ * const keys = { msg: "alerts.user_msg" }; // "alerts.user_msg" -> "User: %{user}"
326
+ * const result = i18n.translateObject(keys, { user: "Bob" });
327
+ * // Returns: { msg: "User: Bob" }
466
328
  */
467
- store(translations: Dict): void;
329
+ translateObject<T extends Record<string, string>>(object: T, options?: I18nTranslateOptions): T;
468
330
  /**
469
- * Automatically resolves translations using reflect Metadata.
470
- * Translations created using the @Translate decorator will be resolved.
471
- * @param target The target class instance or object.
331
+ * Applies translations to the decorated properties of a target object instance.
332
+ *
333
+ * This method performs a lookup for properties on the `target` object that have been
334
+ * decorated with `@Translate`. For each such property, it resolves the translation
335
+ * using the stored key and overwrites the property's value on the instance.
336
+ *
337
+ * **Side Effect Warning**: This method **mutates** the `target` object in place.
338
+ *
339
+ * Use Cases:
340
+ * - Hydrating a component instance with localized strings after initialization or locale change.
341
+ * - Converting a DTO with annotated fields into a display-ready object.
342
+ *
343
+ * @template T - The type of the target object.
344
+ * @param target - The object instance to apply translations to.
345
+ *
472
346
  * @example
473
- * // Class with translations using the decorator
474
- * class MyComponent {
475
- * @Translate("greeting")
476
- * public greeting: string;
477
- *
478
- * @Translate("nested.example")
479
- * public nestedExample: string;
480
- *
481
- * @Translate("farewell")
482
- * public sayGoodbye(): string {
483
- * return "";
484
- * }
347
+ * class Page {
348
+ * @Translate("page.title")
349
+ * title: string = "";
485
350
  * }
486
- * // Resolve translations and print them
487
- * const component = new MyComponent();
488
- * I18n.getInstance().resolveTranslations(component);
489
- */
490
- resolveTranslations<T extends object>(target: T): void;
491
- /***
492
- * returns the missing placeholder string for the given placeholder and message.
493
- * @param placeholder - The placeholder to be replaced.
494
- * @param message - The message to be displayed.
495
- * @param options - The options for the missing placeholder string.
496
- * @returns The missing placeholder string.
351
+ *
352
+ * const page = new Page();
353
+ * i18n.applyTranslations(page);
354
+ * console.log(page.title); // "My Page Title"
497
355
  */
498
- getMissingPlaceholderString(placeholder: string, message?: string, options?: I18nTranslation): string;
356
+ applyTranslations<T extends object>(target: T): void;
499
357
  /**
500
- * Gets the current locale for the i18n instance.
501
- * @returns {string} The current locale.
358
+ * The current locale.
502
359
  */
503
- getLocale(): string;
360
+ private locale;
504
361
  /**
505
- * Sets the list of supported locales for the i18n instance.
506
- * @param locales - An array of locale strings to set as the supported locales.
507
- * @returns The list of all locales supported by the i18n instance, including both the locales for which translations are available and the locales explicitly set as supported.
362
+ * Supported locales.
508
363
  */
509
- setLocales(locales: string[]): string[];
510
- /***
511
- * returns true if the locale is supported by a i18n instance.
512
- * @param locale - The locale to check.
513
- * @returns true if the locale is supported, false otherwise.
364
+ private _locales;
365
+ /**
366
+ * Fallback locale.
514
367
  */
515
- hasLocale(locale: string): boolean;
368
+ private _fallbackLocale;
516
369
  /**
517
- * Gets the list of all locales supported by the i18n instance, including both the locales for which translations are available and the locales explicitly set as supported.
518
- * @returns {string[]} The list of all supported locales.
370
+ * Dictionary of translations: { locale: { key: "value", ... } }
519
371
  */
520
- getLocales(): string[];
521
- /***
522
- * returns true if the locale is supported by the i18n instance.
523
- * @param locale - The locale to check.
524
- * @returns true if the locale is supported, false otherwise.
525
- */
526
- isLocaleSupported(locale: string): boolean;
527
- /***
528
- * returns true if the instance is loading translations.
529
- * @returns true if the instance is loading translations, false otherwise.
530
- * @example
531
- * // Check if the instance is loading translations.
532
- * i18n.isLoading();
372
+ private _translations;
373
+ /**
374
+ * Namespace resolvers.
533
375
  */
534
- isLoading(): boolean;
376
+ private namespaceResolvers;
535
377
  private _namespacesLoaded;
536
- setLocale(locale: string, forceUpdate?: boolean): Promise<string>;
378
+ private _hasDefaultTranslations;
537
379
  /**
538
- * Register a namespace resolver.
539
- * @param namespace The namespace to register.
540
- * @param resolver The resolver function to load the namespace.
541
- * @example
542
- * // Register a namespace resolver for the "common" namespace.
543
- * i18n.registerNamespaceResolver("common", async (locale) => {
544
- * const response = await fetch(`/i18n/${locale}/common.json`);
545
- * return await response.json();
546
- * });
380
+ * Singleton instance of the I18n class.
547
381
  */
548
- registerNamespaceResolver(namespace: string, resolver: (locale: string) => Promise<I18nTranslation>): void;
382
+ private static instance;
549
383
  /**
550
- * Static method to register a namespace resolver to the I18n default instance.
551
- * @param namespace, The namespace to register.
552
- * @param resolver, The resolver function to load the namespace.
553
- * @returns
554
- * @example
555
- * // Register a namespace resolver for the "common" namespace.
556
- * I18n.RegisterNamespaceResolver("common", async (locale) => {
557
- * const response = await fetch(`/i18n/${locale}/common.json`);
558
- * return await response.json();
559
- * });
384
+ * Fallback method when translation is missing.
560
385
  */
561
- static RegisterNamespaceResolver(namespace: string, resolver: (locale: string) => Promise<any>): void;
562
- loadNamespace(namespace: string, locale?: string, updateTranslations?: boolean): Promise<I18nTranslation>;
563
- static LoadNamespace(namespace: string, locale?: string, updateTranslations?: boolean): Promise<I18nTranslation>;
564
- loadNamespaces(locale?: string, updateTranslations?: boolean): Promise<I18nTranslation>;
565
- /***
566
- * Load all registered namespaces for the current locale on the I18n default instance.
567
- * @param locale optional locale to load the namespaces for
568
- * @param updateTranslations optional boolean to update the translations
569
- * @returns {Promise<I18nTranslation>} A promise that resolves to the combined translations for the current local
386
+ private missingTranslation;
387
+ private static momentLocales;
388
+ /**
389
+ * Lookup a key in the translations for a locale.
390
+ * Supports dot notation 'a.b.c'.
570
391
  */
571
- static LoadNamespaces(locale?: string, updateTranslations?: boolean): Promise<I18nTranslation>;
392
+ private lookup;
572
393
  /**
573
- * Flattens a nested object into a single-level object with dot-notation keys.
574
- *
575
- * This utility method transforms complex nested objects into flat key-value pairs,
576
- * where nested properties are represented using dot notation (e.g., `user.name`).
577
- * This is particularly useful for interpolation processes that need to access
578
- * nested values using simple string keys.
579
- *
580
- * @param obj - The object to flatten. Can be any type.
581
- * @returns A flattened object where nested properties are accessible via dot-notation keys,
582
- * or the original input if it's not an object.
583
- *
584
- * @example
585
- * ```typescript
586
- * // Basic flattening
587
- * const nested = {
588
- * user: {
589
- * name: 'John',
590
- * profile: {
591
- * age: 30,
592
- * city: 'New York'
593
- * }
594
- * },
595
- * settings: { theme: 'dark' }
596
- * };
597
- *
598
- * const flattened = I18n.flattenObject(nested);
599
- * // Result: {
600
- * // 'user.name': 'John',
601
- * // 'user.profile.age': 30,
602
- * // 'user.profile.city': 'New York',
603
- * // 'settings.theme': 'dark'
604
- * // }
605
- * ```
606
- *
607
- * @example
608
- * ```typescript
609
- * // Non-object inputs are returned as-is
610
- * I18n.flattenObject("string"); // Returns: "string"
611
- * I18n.flattenObject(42); // Returns: 42
612
- * I18n.flattenObject(null); // Returns: null
613
- * ```
394
+ * Performs the interpolation on a string.
395
+ */
396
+ private performInterpolation;
397
+ private defaultInterpolator;
398
+ private static setLocaleToSession;
399
+ private getMomentLocale;
400
+ private setMomentLocale;
401
+ }
402
+ declare const i18n: I18n;
403
+ export { i18n };
404
+ /**
405
+ * A decorator to attach metadata to properties or methods for translation.
406
+ * @param key The translation key in the translations.
407
+ * @returns A property and method decorator.
408
+ * @example
409
+ * ```ts
410
+ * // Class with translations using the decorator
411
+ * class MyComponent {
412
+ * @Translate("greeting")
413
+ * public greeting: string;
414
+ *
415
+ * @Translate("nested.example")
416
+ * public nestedExample: string;
417
+ *
418
+ * @Translate("farewell")
419
+ * public sayGoodbye(): string {
420
+ * return "";
421
+ * }
422
+ * }
423
+ * ```
424
+ */
425
+ export declare function Translate(key: string): PropertyDecorator & MethodDecorator;
426
+ /**
427
+ * @interface I18nOptions
428
+ * Options for configuring internationalization (i18n) settings.
429
+ *
430
+ * This interface defines the options that can be used to customize
431
+ * the behavior of the i18n system, including the locale, fallback
432
+ * locale, and a custom formatter for string values.
433
+ *
434
+ * @property {string} locale - The primary locale to use for translations.
435
+ * @property {string} [fallbackLocale] - An optional fallback locale to use if the primary locale is not available.
436
+ * @property {I18nFormatter} [formatter] - An optional custom formatter function for formatting strings.
437
+ *
438
+ * @example
439
+ * const i18nOptions: I18nOptions = {
440
+ * locale: "en",
441
+ * fallbackLocale: "es",
442
+ * formatter: (value, params) => value.replace(/{(\w+)}/g, (_, key) => params[key] || '')
443
+ * };
444
+ */
445
+ export interface I18nOptions {
446
+ /**
447
+ * The primary locale to use for translations.
614
448
  *
449
+ * @type {string}
615
450
  * @example
616
- * ```typescript
617
- * // Usage in interpolation
618
- * const params = { user: { firstName: 'John', lastName: 'Doe' } };
619
- * const flattened = I18n.flattenObject(params);
620
- * // Now flattened can be used for interpolation like:
621
- * // "Hello %{user.firstName} %{user.lastName}" -> "Hello John Doe"
622
- * ```
623
- *
624
- * @note This method relies on `Object.flatten()` which should be available
625
- * in the environment. If the input is not an object, it is returned unchanged.
626
- * @note Circular references in objects may cause issues during flattening.
627
- * @note Arrays are treated as objects and their indices become keys in the flattened result.
628
- *
629
- * @see {@link defaultInterpolator} for how this method is used in string interpolation.
451
+ * const currentLocale = i18nOptions.locale; // "en"
630
452
  */
631
- static flattenObject(obj: any): TranslateOptions;
453
+ locale: string;
632
454
  /**
633
- * Provides a default interpolation function for the I18n instance.
634
- *
635
- * If the input `value` is `undefined` or `null`, an empty string is returned.
636
- * If the input `value` is not a number, boolean, or string, it is converted to a string using `stringify`.
637
- * If the input `params` is not an object, the `value` is returned as-is.
638
- * If the input `params` is an object, the `value` is replaced with any matching placeholders in the format `%{key}` using the corresponding values from the `params` object.
455
+ * An optional fallback locale to use if the primary locale is not available.
639
456
  *
640
- * @param i18n The I18n instance.
641
- * @param value The input value to be interpolated.
642
- * @param params Optional object containing replacement values for placeholders in the `value`.
643
- * @returns The interpolated string.
644
- */
645
- private static defaultInterpolator;
457
+ * @type {string}
458
+ * @example
459
+ * const fallback = i18nOptions.fallbackLocale; // "es"
460
+ */
461
+ fallbackLocale?: string;
462
+ /**
463
+ * An optional custom formatter function for formatting strings.
464
+ *
465
+ * @type {I18nFormatter}
466
+ * @example
467
+ * const formattedString = i18nOptions.formatter("Hello, {name}!", { name: "Alice" });
468
+ * // Outputs: "Hello, Alice!"
469
+ ```typescript
470
+ *
471
+ * @example
472
+ * const i18nOptions: I18nOptions = {
473
+ * locale: "en",
474
+ * fallbackLocale: "es",
475
+ * formatter: (value, params) => value.replace(/{(\w+)}/g, (_, key) => params[key] || '')
476
+ * };
477
+ */
478
+ formatter?: I18nFormatter;
479
+ /**
480
+ * Optional custom interpolation.
481
+ */
482
+ interpolate?: (i18n: I18n, str: string, params: Dictionary) => string;
646
483
  }
647
- declare const i18n: I18n;
648
- export { i18n };
484
+ export * from './types';