@sixbell-telco/sdk 1.3.0 → 1.5.0

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 (97) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +437 -472
  3. package/_index.css +109 -11
  4. package/assets/styles/toast.css +8 -0
  5. package/components/forms/date-picker/constants/date-picker.constants.d.ts +13 -0
  6. package/components/forms/date-picker/index.d.ts +5 -0
  7. package/components/forms/date-picker/public-api.d.ts +3 -0
  8. package/components/forms/date-picker/src/date-picker.component.d.ts +323 -0
  9. package/components/forms/date-picker/types/date-picker.types.d.ts +39 -0
  10. package/components/{forms/datepicker → sonner}/index.d.ts +1 -1
  11. package/components/sonner/public-api.d.ts +2 -0
  12. package/components/sonner/src/sonner.component.d.ts +39 -0
  13. package/components/sonner/toaster/index.d.ts +5 -0
  14. package/components/sonner/toaster/public-api.d.ts +1 -0
  15. package/components/sonner/toaster/src/toaster.component.d.ts +89 -0
  16. package/components/toast/public-api.d.ts +9 -0
  17. package/components/toast/services/toast.service.d.ts +3 -0
  18. package/components/toast/toast-message/toast-message.component.d.ts +3 -0
  19. package/components/toast/toasts-container/toasts-container.component.d.ts +3 -0
  20. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +885 -0
  21. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -0
  22. package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs +132 -0
  23. package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs.map +1 -0
  24. package/fesm2022/sixbell-telco-sdk-components-sonner.mjs +179 -0
  25. package/fesm2022/sixbell-telco-sdk-components-sonner.mjs.map +1 -0
  26. package/fesm2022/sixbell-telco-sdk-components-toast.mjs +14 -0
  27. package/fesm2022/sixbell-telco-sdk-components-toast.mjs.map +1 -1
  28. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +90 -2
  29. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  30. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs +578 -0
  31. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs.map +1 -0
  32. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +1222 -0
  33. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +1 -0
  34. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1434 -180
  35. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  36. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +734 -182
  37. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  38. package/package.json +68 -51
  39. package/utils/date/src/date-utils.d.ts +44 -0
  40. package/utils/logger/README.md +539 -0
  41. package/utils/logger/index.d.ts +5 -0
  42. package/utils/logger/public-api.d.ts +3 -0
  43. package/utils/logger/src/constants.d.ts +15 -0
  44. package/utils/logger/src/logger.service.d.ts +123 -0
  45. package/utils/logger/src/models/logger.d.ts +25 -0
  46. package/utils/logger/src/providers/logger.provider.d.ts +3 -0
  47. package/utils/resource-loader/README.md +460 -0
  48. package/utils/resource-loader/index.d.ts +5 -0
  49. package/utils/resource-loader/public-api.d.ts +1 -0
  50. package/utils/resource-loader/src/cache/index.d.ts +2 -0
  51. package/utils/resource-loader/src/cache/layers/factory.d.ts +38 -0
  52. package/utils/resource-loader/src/cache/layers/index.d.ts +3 -0
  53. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +118 -0
  54. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +86 -0
  55. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +76 -0
  56. package/utils/resource-loader/src/cache/types.d.ts +107 -0
  57. package/utils/resource-loader/src/config/index.d.ts +1 -0
  58. package/utils/resource-loader/src/config/load-config.d.ts +32 -0
  59. package/utils/resource-loader/src/constants.d.ts +38 -0
  60. package/utils/resource-loader/src/http/index.d.ts +1 -0
  61. package/utils/resource-loader/src/http/retryable-client.d.ts +43 -0
  62. package/utils/resource-loader/src/index.d.ts +1 -0
  63. package/utils/resource-loader/src/resource-loader.d.ts +67 -0
  64. package/utils/resource-loader/src/types.d.ts +152 -0
  65. package/utils/resource-loader/src/utils/cache-validator.d.ts +72 -0
  66. package/utils/resource-loader/src/utils/helpers.d.ts +15 -0
  67. package/utils/resource-loader/src/utils/index.d.ts +2 -0
  68. package/utils/theme/README.md +1054 -109
  69. package/utils/theme/public-api.d.ts +9 -1
  70. package/utils/theme/src/constants.d.ts +74 -0
  71. package/utils/theme/src/models/theme.d.ts +288 -0
  72. package/utils/theme/src/providers/constants.d.ts +7 -0
  73. package/utils/theme/src/providers/theme.provider.d.ts +13 -0
  74. package/utils/theme/src/providers/theme.provider.types.d.ts +29 -0
  75. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +214 -0
  76. package/utils/theme/src/theme-assets/theme-assets.types.d.ts +10 -0
  77. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +87 -0
  78. package/utils/theme/src/theme-scheme/theme-scheme.service.d.ts +44 -0
  79. package/utils/theme/src/theme-storage/theme-storage.service.d.ts +47 -0
  80. package/utils/theme/src/theme.service.d.ts +40 -186
  81. package/utils/theme/src/utils/utils.d.ts +86 -0
  82. package/utils/translation/README.md +1414 -176
  83. package/utils/translation/public-api.d.ts +6 -0
  84. package/utils/translation/src/constants.d.ts +52 -0
  85. package/utils/translation/src/models/translation.d.ts +59 -0
  86. package/utils/translation/src/providers/constants.d.ts +11 -0
  87. package/utils/translation/src/providers/translation.provider.d.ts +73 -0
  88. package/utils/translation/src/providers/translation.provider.types.d.ts +26 -0
  89. package/utils/translation/src/translation-dom/translation-dom.service.d.ts +26 -0
  90. package/utils/translation/src/translation-storage/translation-storage.service.d.ts +34 -0
  91. package/utils/translation/src/translation.service.d.ts +19 -166
  92. package/components/forms/datepicker/constants/datepicker.constants.d.ts +0 -5
  93. package/components/forms/datepicker/public-api.d.ts +0 -3
  94. package/components/forms/datepicker/src/datepicker.component.d.ts +0 -165
  95. package/components/forms/datepicker/types/datepicker.types.d.ts +0 -7
  96. package/fesm2022/sixbell-telco-sdk-components-forms-datepicker.mjs +0 -487
  97. package/fesm2022/sixbell-telco-sdk-components-forms-datepicker.mjs.map +0 -1
@@ -1,262 +1,481 @@
1
- import { DOCUMENT } from '@angular/common';
2
- import { HttpBackend, HttpClient } from '@angular/common/http';
3
1
  import * as i0 from '@angular/core';
4
- import { InjectionToken, inject, Optional, Inject, Injectable, provideAppInitializer } from '@angular/core';
5
- import { TranslateService, TranslateLoader, provideTranslateService, MissingTranslationHandler } from '@ngx-translate/core';
2
+ import { InjectionToken, Inject, Injectable, inject, signal, Optional, runInInjectionContext, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
+ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
4
+ import { TranslateService, provideTranslateService, MissingTranslationHandler, TranslateLoader } from '@ngx-translate/core';
6
5
  export * from '@ngx-translate/core';
7
- import { TranslateHttpLoader } from '@ngx-translate/http-loader';
6
+ import { LoggerService } from '@sixbell-telco/sdk/utils/logger';
7
+ import { ResourceLoader } from '@sixbell-telco/sdk/utils/resource-loader';
8
+ import { from, filter } from 'rxjs';
9
+ import { DOCUMENT } from '@angular/common';
10
+ import { Router, NavigationEnd } from '@angular/router';
8
11
  export * from '@ngx-translate/http-loader';
9
- import { MultiTranslateHttpLoader } from 'ngx-translate-multi-http-loader';
10
12
  export * from 'ngx-translate-multi-http-loader';
11
13
 
12
14
  /**
13
- * Helper function to create a language definition with full type safety and IntelliSense
15
+ * Translation Constants and Injection Tokens
16
+ * Centralized configuration values and DI tokens following Single Responsibility Principle
14
17
  */
15
- function createLanguage(config) {
16
- return {
17
- code: config.code,
18
- name: config.name,
19
- };
20
- }
21
- // Default base languages - always available
18
+ /**
19
+ * Default base language - always available unless explicitly excluded
20
+ * This is the foundational language that comes with the SDK
21
+ */
22
+ const DEFAULT_BASE_LANGUAGE = 'en';
23
+ /**
24
+ * List of default languages available out of the box
25
+ */
26
+ const DEFAULT_LANGUAGES_LIST = ['en', 'es', 'pt'];
27
+ /**
28
+ * Type-safe default language codes for IDE IntelliSense
29
+ */
30
+ const DEFAULT_LANGUAGE_CODES = DEFAULT_LANGUAGES_LIST;
31
+ /**
32
+ * LocalStorage namespace to prevent collisions with other apps
33
+ */
34
+ const TRANSLATION_STORAGE_NAMESPACE = 'translation:';
35
+ /**
36
+ * LocalStorage key for persisting selected language
37
+ */
38
+ const TRANSLATION_STORAGE_LANGUAGE_KEY = 'selectedLanguage';
39
+ /**
40
+ * Default translation file paths
41
+ */
42
+ const DEFAULT_TRANSLATION_PATHS = ['/assets/i18n/'];
43
+ /**
44
+ * HTML attribute name for setting the active language on document element
45
+ */
46
+ const LANGUAGE_ATTRIBUTE_NAME = 'lang';
47
+ /**
48
+ * Injection token for translation configuration
49
+ * Used to provide static translation configuration at bootstrap
50
+ */
51
+ const TRANSLATION_CONFIG_TOKEN = new InjectionToken('Translation Configuration');
52
+ /**
53
+ * Translation-specific IndexedDB database name for resource caching
54
+ */
55
+ const TRANSLATION_INDEXED_DB_NAME = 'sixbell-translation';
22
56
  const DEFAULT_LANGUAGES = [
23
57
  { code: 'en', name: 'English' },
24
58
  { code: 'es', name: 'Español' },
25
59
  { code: 'pt', name: 'Português' },
26
60
  ];
27
61
  const DEFAULT_LANGUAGE_CODE = 'en';
28
- // Export language codes for IntelliSense
29
- const DEFAULT_LANGUAGE_CODES = ['en', 'es', 'pt'];
30
- // Custom missing translation handler to show keys instead of falling back to default language
31
- class PlaceholderMissingTranslationHandler {
32
- handle(params) {
33
- // Return the translation key as placeholder to make missing translations visible
34
- return params.key;
62
+ const TRANSLATION_RESOURCE_LOADER_DEFAULTS = {
63
+ cacheName: 'translation-resources',
64
+ indexedDBName: TRANSLATION_INDEXED_DB_NAME,
65
+ storageOrder: ['indexedDB', 'memory'],
66
+ cacheTTL: 1000 * 60 * 60 * 12,
67
+ freshOnNavigation: true,
68
+ staleWhileRevalidate: true,
69
+ useStaleOnError: true,
70
+ revalidateOnFresh: true,
71
+ retries: 3,
72
+ retryDelayMs: 400,
73
+ timeoutMs: 6000,
74
+ seedCacheWithFallback: true,
75
+ logErrors: true,
76
+ };
77
+
78
+ /**
79
+ * Translation DOM Service
80
+ * Handles DOM operations related to language/localization
81
+ */
82
+ /**
83
+ * Service responsible for DOM manipulation related to language/localization
84
+ * Decouples DOM operations from business logic
85
+ */
86
+ class TranslationDomService {
87
+ rendererFactory;
88
+ document;
89
+ renderer;
90
+ constructor(rendererFactory, document) {
91
+ this.rendererFactory = rendererFactory;
92
+ this.document = document;
93
+ this.renderer = this.rendererFactory.createRenderer(null, null);
35
94
  }
95
+ /**
96
+ * Sets the language on the document element
97
+ * Updates the HTML lang attribute for accessibility and SEO
98
+ * @param language - Language code (e.g., 'en', 'es', 'pt')
99
+ */
100
+ setDocumentLanguage(language) {
101
+ if (!language) {
102
+ return;
103
+ }
104
+ const htmlElement = this.document.documentElement;
105
+ if (htmlElement) {
106
+ this.renderer.setAttribute(htmlElement, LANGUAGE_ATTRIBUTE_NAME, language);
107
+ }
108
+ }
109
+ /**
110
+ * Gets the current language from the document element
111
+ * Reads the HTML lang attribute
112
+ * @returns Current language code or empty string if not set
113
+ */
114
+ getDocumentLanguage() {
115
+ const htmlElement = this.document.documentElement;
116
+ if (!htmlElement) {
117
+ return '';
118
+ }
119
+ return htmlElement.getAttribute(LANGUAGE_ATTRIBUTE_NAME) || '';
120
+ }
121
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationDomService, deps: [{ token: i0.RendererFactory2 }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
122
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationDomService, providedIn: 'root' });
36
123
  }
37
- // Injection tokens for dependency injection
38
- const TRANSLATION_CONFIG_TOKEN = new InjectionToken('Translation Configuration');
39
- const LOCALIZATION_LOCAL_STORAGE_KEY = 'language';
124
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationDomService, decorators: [{
125
+ type: Injectable,
126
+ args: [{ providedIn: 'root' }]
127
+ }], ctorParameters: () => [{ type: i0.RendererFactory2 }, { type: Document, decorators: [{
128
+ type: Inject,
129
+ args: [DOCUMENT]
130
+ }] }] });
131
+
132
+ /**
133
+ * Translation Storage Service
134
+ * Handles persistent language preferences using localStorage
135
+ */
40
136
  /**
41
- * Factory function to create HTTP loader for translations with custom paths
137
+ * Helper function to check if localStorage is available
138
+ * Returns false in SSR or when storage is disabled
42
139
  */
43
- function HttpLoaderFactory(http) {
44
- return new TranslateHttpLoader(http, './assets/i18n/', '.json');
140
+ function hasLocalStorage() {
141
+ try {
142
+ if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
143
+ return false;
144
+ }
145
+ // Try to access localStorage to catch any errors
146
+ localStorage.getItem('test');
147
+ return true;
148
+ }
149
+ catch {
150
+ return false;
151
+ }
45
152
  }
46
153
  /**
47
- * Factory function to create multi-path HTTP loader for translations
154
+ * Service for managing language preferences in local storage
155
+ * Provides safe access to localStorage with error handling
156
+ * Works gracefully in non-browser environments (SSR)
48
157
  */
49
- function MultiPathHttpLoaderFactory(httpBackend, paths) {
50
- return new MultiTranslateHttpLoader(httpBackend, paths);
158
+ class TranslationStorageService {
159
+ logger = inject(LoggerService);
160
+ /**
161
+ * Retrieves the saved language preference from localStorage
162
+ * Returns null if no saved preference or storage unavailable
163
+ * @returns Saved language code or null
164
+ */
165
+ getSavedLanguage() {
166
+ try {
167
+ if (!hasLocalStorage()) {
168
+ return null;
169
+ }
170
+ const key = this.getStorageKey(TRANSLATION_STORAGE_LANGUAGE_KEY);
171
+ return localStorage.getItem(key);
172
+ }
173
+ catch (error) {
174
+ this.logger.error('Failed to retrieve saved language', error, {
175
+ component: 'TranslationStorageService',
176
+ action: 'getSavedLanguage',
177
+ });
178
+ return null;
179
+ }
180
+ }
181
+ /**
182
+ * Saves the current language preference to localStorage
183
+ * Fails silently if storage is unavailable
184
+ * @param language - Language code to save
185
+ */
186
+ saveLanguage(language) {
187
+ try {
188
+ if (!hasLocalStorage()) {
189
+ return;
190
+ }
191
+ const key = this.getStorageKey(TRANSLATION_STORAGE_LANGUAGE_KEY);
192
+ localStorage.setItem(key, language);
193
+ }
194
+ catch (error) {
195
+ this.logger.error('Failed to save language', error, {
196
+ component: 'TranslationStorageService',
197
+ action: 'saveLanguage',
198
+ language,
199
+ });
200
+ }
201
+ }
202
+ /**
203
+ * Clears all saved language preferences from localStorage
204
+ * Useful for resetting to defaults
205
+ */
206
+ clear() {
207
+ try {
208
+ if (!hasLocalStorage()) {
209
+ return;
210
+ }
211
+ const key = this.getStorageKey(TRANSLATION_STORAGE_LANGUAGE_KEY);
212
+ localStorage.removeItem(key);
213
+ }
214
+ catch (error) {
215
+ this.logger.error('Failed to clear storage', error, {
216
+ component: 'TranslationStorageService',
217
+ action: 'clear',
218
+ });
219
+ }
220
+ }
221
+ /**
222
+ * Constructs a namespaced storage key to avoid collisions
223
+ * @param key - The base storage key
224
+ * @returns Namespaced key (e.g., "translation:selectedLanguage")
225
+ */
226
+ getStorageKey(key) {
227
+ return `${TRANSLATION_STORAGE_NAMESPACE}${key}`;
228
+ }
229
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
230
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationStorageService, providedIn: 'root' });
51
231
  }
232
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationStorageService, decorators: [{
233
+ type: Injectable,
234
+ args: [{ providedIn: 'root' }]
235
+ }] });
236
+
52
237
  /**
53
- * Utility function to extend default languages with additional ones
238
+ * Translation Service
239
+ * Main service for handling language selection, translation loading, and management
240
+ * Mirrors ThemeService - config via DI token + ResourceLoader for multi-path loading
54
241
  */
242
+ function createLanguage(config) {
243
+ return {
244
+ code: config.code,
245
+ name: config.name,
246
+ };
247
+ }
55
248
  function extendDefaultLanguages(additionalLanguages) {
56
249
  return [...DEFAULT_LANGUAGES, ...additionalLanguages];
57
250
  }
251
+ class PlaceholderMissingTranslationHandler {
252
+ handle(params) {
253
+ return params.key;
254
+ }
255
+ }
58
256
  class TranslationService {
59
257
  translationConfig;
60
258
  translate = inject(TranslateService);
61
- document = inject(DOCUMENT);
259
+ storageService = inject(TranslationStorageService);
260
+ domService = inject(TranslationDomService);
261
+ logger = inject(LoggerService);
62
262
  initialized = false;
63
- // Default configuration - can be overridden by provider
263
+ currentTranslationPaths = [...DEFAULT_TRANSLATION_PATHS];
264
+ translationResourceLoader = null;
265
+ hasAppliedInitialLanguage = false;
64
266
  config = {
65
267
  availableLanguages: [...DEFAULT_LANGUAGES],
66
- defaultLang: DEFAULT_LANGUAGE_CODE,
67
- translationPaths: ['/assets/i18n/'],
268
+ defaultLanguage: DEFAULT_LANGUAGE_CODE,
68
269
  };
270
+ currentLanguage = signal(DEFAULT_LANGUAGE_CODE);
271
+ onLanguageChange$ = this.translate.onLangChange.asObservable();
272
+ onLanguageChange = signal(0);
273
+ ready = signal(false);
69
274
  constructor(translationConfig) {
70
275
  this.translationConfig = translationConfig;
71
- // Configure with provided config or defaults
72
276
  if (translationConfig) {
73
277
  this.configure(translationConfig);
74
278
  }
75
279
  else {
76
- // Initialize with defaults immediately
77
280
  this.initializeFromStorage();
78
- this.applyLanguage();
79
- this.initialized = true;
80
281
  }
282
+ this.currentLanguage.set(this.getCurrentLanguage());
81
283
  }
82
- /**
83
- * Configure and initialize the translation service (used by provider)
84
- */
85
284
  configure(config = {}) {
86
- // Start with default base languages (en, es, pt)
285
+ this.logger.debug('configure - starting', {
286
+ component: 'TranslationService',
287
+ action: 'configure',
288
+ configProvidedPaths: config.translationPaths,
289
+ configDefaultLang: config.defaultLang,
290
+ configAdditionalLanguages: config.additionalLanguages?.length,
291
+ configExcludedLanguages: config.excludeLanguages,
292
+ });
87
293
  let availableLanguages = [...DEFAULT_LANGUAGES];
88
- // Handle additional languages
89
294
  if (config.additionalLanguages) {
90
- availableLanguages = [...DEFAULT_LANGUAGES, ...config.additionalLanguages];
295
+ availableLanguages = [...availableLanguages, ...config.additionalLanguages];
91
296
  }
92
- // Apply language exclusions if specified
93
297
  if (config.excludeLanguages) {
94
- const excludeCodes = config.excludeLanguages;
95
- availableLanguages = availableLanguages.filter((lang) => !excludeCodes.includes(lang.code));
298
+ availableLanguages = availableLanguages.filter((lang) => !config.excludeLanguages?.includes(lang.code));
96
299
  }
97
- // Determine default language
98
300
  const defaultLang = config.defaultLang || DEFAULT_LANGUAGE_CODE;
99
- // Update configuration
301
+ const newPaths = (config.translationPaths || DEFAULT_TRANSLATION_PATHS);
302
+ if (JSON.stringify(newPaths) !== JSON.stringify(this.currentTranslationPaths)) {
303
+ this.currentTranslationPaths = newPaths;
304
+ this.logger.debug('Translation paths updated', {
305
+ component: 'TranslationService',
306
+ action: 'configure',
307
+ newPaths,
308
+ });
309
+ this.translate.reloadLang(this.getCurrentLanguage());
310
+ }
100
311
  this.config = {
101
312
  availableLanguages,
102
- defaultLang,
103
- translationPaths: config.translationPaths || this.config.translationPaths,
313
+ defaultLanguage: defaultLang,
104
314
  };
105
- // Validate defaultLang is in available languages
106
315
  const availableCodes = this.config.availableLanguages.map((lang) => lang.code);
107
- if (!availableCodes.includes(this.config.defaultLang)) {
108
- console.warn(`TranslationService: defaultLang '${this.config.defaultLang}' not in availableLanguages, using '${availableCodes[0] || DEFAULT_LANGUAGE_CODE}'`);
109
- this.config.defaultLang = availableCodes[0] || DEFAULT_LANGUAGE_CODE;
316
+ if (!availableCodes.includes(this.config.defaultLanguage)) {
317
+ this.logger.warn('Default language not available in configured languages', {
318
+ component: 'TranslationService',
319
+ action: 'configure',
320
+ defaultLang: this.config.defaultLanguage,
321
+ availableCodes,
322
+ });
323
+ this.config.defaultLanguage = availableCodes[0] || DEFAULT_LANGUAGE_CODE;
110
324
  }
111
- // If this is called after constructor (provider case), re-initialize with new config
325
+ this.logger.debug('Configuration complete', {
326
+ component: 'TranslationService',
327
+ action: 'configure',
328
+ finalDefaultLang: this.config.defaultLanguage,
329
+ availableLangCodes: availableCodes,
330
+ });
112
331
  if (this.initialized) {
332
+ // This is a runtime config update (not initial construction)
333
+ // Set signal to defaults, then restore from storage if available
334
+ this.currentLanguage.set(this.config.defaultLanguage);
113
335
  this.initializeFromStorage();
336
+ // Mark that we've applied the initial language so init() can apply it on next call
337
+ this.hasAppliedInitialLanguage = true;
114
338
  }
115
339
  else {
116
- this.initializeFromStorage();
117
340
  this.initialized = true;
341
+ // IMPORTANT: Do NOT call applyLanguage() here during construction!
342
+ // This causes circular dependency because ngx-translate tries to use
343
+ // the loader during provider setup phase. Instead, applyLanguage()
344
+ // will be deferred until setRuntimeConfig() is called.
118
345
  }
119
346
  }
120
- /**
121
- * Initialize translation from localStorage and apply it immediately
122
- */
347
+ async setRuntimeConfig(config) {
348
+ this.logger.debug('setRuntimeConfig - starting', {
349
+ component: 'TranslationService',
350
+ action: 'setRuntimeConfig',
351
+ configPath: config.translationPaths,
352
+ });
353
+ // Update configuration (this will update currentLanguage signal and restore from storage)
354
+ this.configure(config);
355
+ // Apply language now that runtime config has loaded
356
+ // This saves to storage with the correct default from config file
357
+ this.applyLanguage();
358
+ // CRITICAL: Force reload even if paths didn't change
359
+ // This ensures fresh translations are loaded when config is updated at runtime
360
+ const currentLang = this.getCurrentLanguage();
361
+ this.logger.debug('setRuntimeConfig - forcing reload', {
362
+ component: 'TranslationService',
363
+ action: 'setRuntimeConfig',
364
+ currentLanguage: currentLang,
365
+ });
366
+ this.translate.reloadLang(currentLang);
367
+ await this.waitForTranslations();
368
+ this.logger.debug('setRuntimeConfig - complete', {
369
+ component: 'TranslationService',
370
+ action: 'setRuntimeConfig',
371
+ currentLanguage: this.getCurrentLanguage(),
372
+ });
373
+ }
123
374
  initializeFromStorage() {
124
- // Safety checks for browser environment
125
- if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
126
- console.warn('TranslationService: Browser environment not available, using defaults');
127
- this.applyLanguage();
128
- return;
129
- }
130
375
  try {
131
- // Set up translate service with available languages
132
- this.translate.setDefaultLang(this.config.defaultLang);
133
- // Load available translations
134
- const languageCodes = this.config.availableLanguages.map((lang) => lang.code);
135
- this.translate.addLangs(languageCodes);
136
- // Get current language from storage or use default
137
- const savedLang = localStorage.getItem(LOCALIZATION_LOCAL_STORAGE_KEY);
138
- const currentLang = savedLang && languageCodes.includes(savedLang) ? savedLang : this.config.defaultLang;
139
- // Apply language immediately
140
- this.applyLanguage(currentLang);
376
+ const saved = this.storageService.getSavedLanguage();
377
+ const availableCodes = this.config.availableLanguages.map((l) => l.code);
378
+ if (saved && availableCodes.includes(saved)) {
379
+ this.logger.debug('Restoring saved language', {
380
+ component: 'TranslationService',
381
+ action: 'initializeFromStorage',
382
+ savedLanguage: saved,
383
+ });
384
+ this.currentLanguage.set(saved);
385
+ }
386
+ this.applyLanguage();
141
387
  }
142
388
  catch (error) {
143
- console.error('TranslationService: Failed to initialize from storage:', error);
144
- this.applyLanguage();
389
+ this.logger.error('Error initializing from storage', error, {
390
+ component: 'TranslationService',
391
+ action: 'initializeFromStorage',
392
+ });
145
393
  }
146
394
  }
147
- /**
148
- * Apply the current language to the translate service and document
149
- */
150
- applyLanguage(lang) {
151
- const targetLang = lang || this.config.defaultLang;
152
- // Set the language in translate service
395
+ applyLanguage() {
396
+ const targetLang = this.currentLanguage();
153
397
  this.translate.use(targetLang);
154
- // Update HTML lang attribute for accessibility and SEO
155
- this.document.documentElement.lang = targetLang;
156
- // Persist to localStorage
157
- if (typeof localStorage !== 'undefined') {
158
- localStorage.setItem(LOCALIZATION_LOCAL_STORAGE_KEY, targetLang);
159
- }
398
+ this.domService.setDocumentLanguage(targetLang);
399
+ // Always save to storage - keeps state consistent from the start
400
+ // This mirrors theme service behavior: saves defaults on init,
401
+ // then saves user preferences when they change language
402
+ this.storageService.saveLanguage(targetLang);
160
403
  }
161
- /**
162
- * Set the current language and persist to localStorage
163
- */
164
404
  setLanguage(lang) {
165
405
  if (lang) {
166
- // Validate language is available
167
406
  const availableCodes = this.config.availableLanguages.map((l) => l.code);
168
407
  if (!availableCodes.includes(lang)) {
169
- console.warn(`TranslationService: Language '${lang}' not available, using default '${this.config.defaultLang}'`);
170
- lang = this.config.defaultLang;
408
+ this.logger.warn('Language not available, using default', {
409
+ component: 'TranslationService',
410
+ action: 'setLanguage',
411
+ requestedLang: lang,
412
+ defaultLang: this.config.defaultLanguage,
413
+ availableCodes,
414
+ });
415
+ lang = this.config.defaultLanguage;
171
416
  }
172
- this.applyLanguage(lang);
417
+ this.logger.debug('setLanguage', {
418
+ component: 'TranslationService',
419
+ action: 'setLanguage',
420
+ language: lang,
421
+ });
422
+ this.currentLanguage.set(lang);
423
+ this.applyLanguage();
173
424
  }
174
425
  }
175
- /**
176
- * Get the current language from localStorage or default
177
- */
178
426
  getCurrentLanguage() {
179
- if (typeof localStorage === 'undefined') {
180
- return this.config.defaultLang;
181
- }
182
- const saved = localStorage.getItem(LOCALIZATION_LOCAL_STORAGE_KEY);
427
+ const saved = this.storageService.getSavedLanguage();
183
428
  const availableCodes = this.config.availableLanguages.map((l) => l.code);
184
- return saved && availableCodes.includes(saved) ? saved : this.config.defaultLang;
429
+ return saved && availableCodes.includes(saved) ? saved : this.config.defaultLanguage;
185
430
  }
186
- /**
187
- * Get the current HTML lang attribute
188
- */
189
- getCurrentHtmlLanguage() {
190
- return this.document.documentElement.lang || this.config.defaultLang;
191
- }
192
- /**
193
- * Get available languages
194
- */
195
431
  getAvailableLanguages() {
196
432
  return this.translate.getLangs();
197
433
  }
198
- /**
199
- * Get default language
200
- */
201
434
  getDefaultLanguage() {
202
- return this.config.defaultLang;
435
+ return this.config.defaultLanguage;
203
436
  }
204
- /**
205
- * Instantly translate a key with optional parameters
206
- */
207
437
  instant(key, params) {
208
- if (params) {
209
- return this.translate.instant(key, params);
438
+ const result = params ? this.translate.instant(key, params) : this.translate.instant(key);
439
+ if (result === key) {
440
+ const currentLang = this.getCurrentLanguage();
441
+ const loadedTranslations = this.translate.translations[currentLang] || {};
442
+ const loadedKeys = Object.keys(loadedTranslations);
443
+ this.logger.warn('Translation key not found', {
444
+ component: 'TranslationService',
445
+ action: 'instant',
446
+ key,
447
+ currentLanguage: currentLang,
448
+ hasParams: !!params,
449
+ totalLoadedKeys: loadedKeys.length,
450
+ });
210
451
  }
211
- return this.translate.instant(key);
452
+ return result;
212
453
  }
213
- /**
214
- * Get observable translation for a key
215
- */
216
454
  get(key, params) {
217
455
  if (params) {
218
456
  return this.translate.get(key, params);
219
457
  }
220
458
  return this.translate.get(key);
221
459
  }
222
- /**
223
- * Get stream of translations for a key
224
- */
225
460
  stream(key, params) {
226
461
  if (params) {
227
462
  return this.translate.stream(key, params);
228
463
  }
229
464
  return this.translate.stream(key);
230
465
  }
231
- /**
232
- * Get available languages configuration
233
- */
234
466
  getAvailableLanguagesConfig() {
235
467
  return this.config.availableLanguages;
236
468
  }
237
- /**
238
- * Get available language codes
239
- */
240
469
  getAvailableLanguageCodes() {
241
470
  return this.config.availableLanguages.map((lang) => lang.code);
242
471
  }
243
- /**
244
- * Get language configuration by code
245
- */
246
472
  getLanguageByCode(code) {
247
473
  return this.config.availableLanguages.find((lang) => lang.code === code);
248
474
  }
249
- /**
250
- * Get language display name by code
251
- */
252
475
  getLanguageDisplayName(code) {
253
476
  const language = this.getLanguageByCode(code);
254
477
  return language ? language.name : code.toUpperCase();
255
478
  }
256
- /**
257
- * Get localized language name by code using translations
258
- * This automatically returns the localized name based on the current language
259
- */
260
479
  getLocalizedLanguageName(code) {
261
480
  const translationKey = `sdk.language.languages.${code}`;
262
481
  const translatedName = this.translate.instant(translationKey);
@@ -266,66 +485,399 @@ class TranslationService {
266
485
  const language = this.getLanguageByCode(code);
267
486
  return language ? language.name : code.toUpperCase();
268
487
  }
269
- /**
270
- * Force initialization method for MFE environments
271
- */
488
+ isReady() {
489
+ return this.ready.asReadonly();
490
+ }
491
+ async waitForTranslations(timeoutMs = 10000) {
492
+ return new Promise((resolve, reject) => {
493
+ if (this.ready()) {
494
+ resolve();
495
+ return;
496
+ }
497
+ const startTime = Date.now();
498
+ const checkInterval = setInterval(() => {
499
+ if (this.ready()) {
500
+ clearInterval(checkInterval);
501
+ resolve();
502
+ }
503
+ else if (Date.now() - startTime > timeoutMs) {
504
+ clearInterval(checkInterval);
505
+ this.logger.warn('waitForTranslations timeout', {
506
+ component: 'TranslationService',
507
+ action: 'waitForTranslations',
508
+ timeoutMs,
509
+ isReady: this.ready(),
510
+ });
511
+ reject(new Error(`Translation service not ready after ${timeoutMs}ms`));
512
+ }
513
+ }, 50);
514
+ });
515
+ }
272
516
  init() {
273
- // This method just ensures the service is instantiated and initialized
274
- this.getAvailableLanguagesConfig(); // Trigger any lazy initialization
517
+ this.getAvailableLanguagesConfig();
518
+ // IMPORTANT: Do NOT apply the language here on first init!
519
+ // The runtime config hasn't loaded yet, so we'd save the hardcoded default to storage.
520
+ // Instead, applyLanguage() will be called from setRuntimeConfig() after config loads.
521
+ if (this.hasAppliedInitialLanguage) {
522
+ this.applyLanguage();
523
+ }
524
+ this.translate.onLangChange.pipe(takeUntilDestroyed()).subscribe({
525
+ next: (event) => {
526
+ this.currentLanguage.set(event.lang);
527
+ this.onLanguageChange.update((val) => val + 1);
528
+ this.ready.set(true);
529
+ this.logger.debug('Translations ready - language loaded', {
530
+ component: 'TranslationService',
531
+ action: 'init - onLangChange',
532
+ ready: true,
533
+ language: event.lang,
534
+ });
535
+ },
536
+ error: (err) => {
537
+ this.logger.error('Error loading translations', err, {
538
+ component: 'TranslationService',
539
+ action: 'init - onLangChange',
540
+ });
541
+ this.ready.set(true);
542
+ },
543
+ });
544
+ }
545
+ getOrCreateResourceLoader() {
546
+ if (!this.translationResourceLoader) {
547
+ this.translationResourceLoader = new ResourceLoader(TRANSLATION_RESOURCE_LOADER_DEFAULTS, this.logger);
548
+ }
549
+ return this.translationResourceLoader;
550
+ }
551
+ buildResourceOptions(overrides) {
552
+ return {
553
+ ...TRANSLATION_RESOURCE_LOADER_DEFAULTS,
554
+ ...overrides,
555
+ fallbackData: overrides?.fallbackData ?? {},
556
+ parser: overrides?.parser ?? (async (response) => (await response.json())),
557
+ };
558
+ }
559
+ createTranslateLoader() {
560
+ const loader = this.getOrCreateResourceLoader();
561
+ const options = this.buildResourceOptions();
562
+ const suffix = '.json';
563
+ return {
564
+ getTranslation: (lang) => {
565
+ this.logger.debug('TranslateLoader.getTranslation called', {
566
+ language: lang,
567
+ pathsToUse: this.currentTranslationPaths,
568
+ });
569
+ const pathsToUse = this.currentTranslationPaths;
570
+ if (pathsToUse.length === 0) {
571
+ this.logger.warn('No translation paths configured', { language: lang });
572
+ return from(Promise.resolve({}));
573
+ }
574
+ const loadPromises = pathsToUse.map((path) => {
575
+ const url = `${path.endsWith('/') ? path : `${path}/`}${lang}${suffix}`;
576
+ return loader.load(url, {
577
+ ...options,
578
+ cacheKey: `${lang}:${url}`,
579
+ });
580
+ });
581
+ return from(Promise.all(loadPromises).then((results) => {
582
+ const merged = results.reduce((acc, result) => {
583
+ return this.deepMergeTranslations(acc, result.data ?? {});
584
+ }, {});
585
+ this.logger.debug('Translations loaded and merged', {
586
+ language: lang,
587
+ filesLoaded: results.length,
588
+ totalKeys: Object.keys(merged).length,
589
+ });
590
+ return merged;
591
+ }));
592
+ },
593
+ };
594
+ }
595
+ deepMergeTranslations(target, source) {
596
+ const result = { ...target };
597
+ for (const key in source) {
598
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
599
+ const sourceValue = source[key];
600
+ const targetValue = result[key];
601
+ if (typeof sourceValue === 'object' &&
602
+ sourceValue !== null &&
603
+ !Array.isArray(sourceValue) &&
604
+ typeof targetValue === 'object' &&
605
+ targetValue !== null &&
606
+ !Array.isArray(targetValue)) {
607
+ result[key] = this.deepMergeTranslations(targetValue, sourceValue);
608
+ }
609
+ else {
610
+ result[key] = sourceValue;
611
+ }
612
+ }
613
+ }
614
+ return result;
275
615
  }
276
616
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationService, deps: [{ token: TRANSLATION_CONFIG_TOKEN, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
277
617
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationService, providedIn: 'root' });
278
618
  }
279
619
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: TranslationService, decorators: [{
280
620
  type: Injectable,
281
- args: [{
282
- providedIn: 'root',
283
- }]
621
+ args: [{ providedIn: 'root' }]
284
622
  }], ctorParameters: () => [{ type: undefined, decorators: [{
285
623
  type: Optional
286
624
  }, {
287
625
  type: Inject,
288
626
  args: [TRANSLATION_CONFIG_TOKEN]
289
627
  }] }] });
290
- // Implementation
628
+
629
+ /**
630
+ * Default resource loader options for runtime translation config files
631
+ * Matches theme's resilient loading pattern
632
+ */
633
+ const RUNTIME_TRANSLATION_LOADER_DEFAULTS = {
634
+ cacheName: 'translation-runtime-config',
635
+ indexedDBName: TRANSLATION_INDEXED_DB_NAME,
636
+ storageOrder: ['indexedDB', 'memory'],
637
+ cacheTTL: 1000 * 60 * 60 * 24,
638
+ freshOnNavigation: true, // Hot-reload on every navigation by default
639
+ staleWhileRevalidate: true,
640
+ useStaleOnError: true,
641
+ revalidateOnFresh: true,
642
+ retries: 3,
643
+ retryDelayMs: 400,
644
+ timeoutMs: 8000,
645
+ seedCacheWithFallback: true,
646
+ logErrors: true,
647
+ };
648
+ /**
649
+ * Fallback translation config when file loading fails
650
+ */
651
+ const FALLBACK_RUNTIME_TRANSLATION_CONFIG = {
652
+ additionalLanguages: [],
653
+ defaultLang: 'en',
654
+ translationPaths: ['/assets/i18n/'],
655
+ };
656
+
657
+ // ============================================================
658
+ // CUSTOM LOADER - Deferred injection pattern
659
+ // ============================================================
660
+ /**
661
+ * Custom TranslateLoader that defers injection of TranslationService.
662
+ *
663
+ * This loader is instantiated by ngx-translate when first needed.
664
+ * By deferring the inject() call until getTranslation is called,
665
+ * we avoid circular dependency issues during DI setup.
666
+ *
667
+ * Key: DO NOT use providedIn: 'root' - let ngx-translate manage the lifecycle.
668
+ */
669
+ class RuntimeTranslationCustomLoader {
670
+ injector;
671
+ constructor(injector) {
672
+ this.injector = injector;
673
+ }
674
+ getTranslation(lang) {
675
+ // Use runInInjectionContext to safely inject TranslationService
676
+ // even when called outside the normal DI context
677
+ return runInInjectionContext(this.injector, () => {
678
+ const translationService = inject(TranslationService);
679
+ return translationService['createTranslateLoader']().getTranslation(lang);
680
+ });
681
+ }
682
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: RuntimeTranslationCustomLoader, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable });
683
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: RuntimeTranslationCustomLoader });
684
+ }
685
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: RuntimeTranslationCustomLoader, decorators: [{
686
+ type: Injectable
687
+ }], ctorParameters: () => [{ type: i0.Injector }] });
688
+ // ============================================================
689
+ // DEPRECATED PROVIDER - STANDALONE (will be removed in major)
690
+ // ============================================================
691
+ /**
692
+ * @deprecated Use `provideRuntimeTranslation()` instead.
693
+ *
694
+ * Provide the Translation service with static configuration.
695
+ * This provider is completely standalone and does NOT include ngx-translate setup.
696
+ * It just provides the configuration token for the service to use.
697
+ *
698
+ * Configuration is baked into the app at build time. For dynamic configuration,
699
+ * use `provideRuntimeTranslation()` to load from a JSON file.
700
+ *
701
+ * @param config - Configuration for languages and paths (optional)
702
+ * @returns Environment providers for bootstrapping
703
+ *
704
+ * @example
705
+ * ```typescript
706
+ * // DEPRECATED: Static config - do not use in new code
707
+ * bootstrapApplication(AppComponent, [
708
+ * provideTranslation({
709
+ * defaultLang: 'es',
710
+ * translationPaths: ['/assets/i18n/'],
711
+ * }),
712
+ * ]);
713
+ *
714
+ * // RECOMMENDED: Use runtime config instead
715
+ * bootstrapApplication(AppComponent, [
716
+ * provideRuntimeTranslation('/assets/config/translation-config.json'),
717
+ * ]);
718
+ * ```
719
+ */
291
720
  function provideTranslation(config) {
292
- // Determine which loader to use based on configuration
293
- const loaderProvider = config?.translationPaths && config.translationPaths.length > 0
294
- ? {
295
- provide: TranslateLoader,
296
- useFactory: (httpBackend) => MultiPathHttpLoaderFactory(httpBackend, config.translationPaths),
297
- deps: [HttpBackend],
298
- }
299
- : {
300
- provide: TranslateLoader,
301
- useFactory: HttpLoaderFactory,
302
- deps: [HttpClient],
303
- };
304
- return [
305
- // Provide the complete ngx-translate setup with appropriate loader and missing translation handler
721
+ return makeEnvironmentProviders([
722
+ {
723
+ provide: TRANSLATION_CONFIG_TOKEN,
724
+ useValue: config || {},
725
+ },
726
+ ]);
727
+ }
728
+ // ============================================================
729
+ // RUNTIME PROVIDER - WITH NGXTRANSLATE SETUP
730
+ // ============================================================
731
+ /**
732
+ * Configuration options for the runtime translation provider (like themes).
733
+ *
734
+ * @property loader - Custom loader instance (optional; uses default if not provided)
735
+ * @property loaderOptions - Loader configuration options (cache TTL, retries, storage, etc.)
736
+ *
737
+ * @example
738
+ * ```typescript
739
+ * // Default mode: Always fetch fresh translations with fallback to cache
740
+ * provideRuntimeTranslation('/assets/config/translation-config.json')
741
+ *
742
+ * // Custom caching mode
743
+ * provideRuntimeTranslation('/assets/config/translation-config.json', {
744
+ * loaderOptions: {
745
+ * freshOnNavigation: false,
746
+ * retries: 3,
747
+ * },
748
+ * })
749
+ * ```
750
+ */
751
+ /**
752
+ * Build runtime translation loader options with defaults
753
+ */
754
+ function buildRuntimeTranslationLoaderOptions(configPath, overrides) {
755
+ const merged = { ...RUNTIME_TRANSLATION_LOADER_DEFAULTS, ...overrides };
756
+ return {
757
+ ...merged,
758
+ cacheKey: overrides?.cacheKey ?? configPath,
759
+ fallbackData: overrides?.fallbackData ?? FALLBACK_RUNTIME_TRANSLATION_CONFIG,
760
+ parser: overrides?.parser ?? (async (response) => (await response.json())),
761
+ };
762
+ }
763
+ /**
764
+ * Provide Translation service with configuration loaded from a JSON file at runtime (like themes).
765
+ *
766
+ * This is the ONLY provider that sets up ngx-translate. It:
767
+ * - Loads translation configuration from a JSON file
768
+ * - Sets up ngx-translate with custom loader that loads from multiple paths
769
+ * - Supports hot-reload on navigation
770
+ * - Supports offline scenarios with caching
771
+ *
772
+ * @param configPath - Path to translation configuration JSON file
773
+ * @param options - Optional loader configuration
774
+ * @returns Environment providers
775
+ *
776
+ * @example
777
+ * ```typescript
778
+ * bootstrapApplication(AppComponent, [
779
+ * provideRuntimeTranslation('/assets/translation/translation-config.json')
780
+ * ]);
781
+ * ```
782
+ */
783
+ function provideRuntimeTranslation(configPath, options) {
784
+ const initialConfig = options?.loaderOptions?.fallbackData ?? FALLBACK_RUNTIME_TRANSLATION_CONFIG;
785
+ return makeEnvironmentProviders([
786
+ // Provide initial config token FIRST
787
+ {
788
+ provide: TRANSLATION_CONFIG_TOKEN,
789
+ useValue: initialConfig,
790
+ },
791
+ // NOW provide ngx-translate - TranslationService will be injected when needed
792
+ // Do NOT provide TranslationService directly since it's providedIn: 'root'
306
793
  provideTranslateService({
307
- loader: loaderProvider,
794
+ loader: {
795
+ provide: TranslateLoader,
796
+ useClass: RuntimeTranslationCustomLoader,
797
+ },
308
798
  missingTranslationHandler: {
309
799
  provide: MissingTranslationHandler,
310
800
  useClass: PlaceholderMissingTranslationHandler,
311
801
  },
312
- useDefaultLang: false, // Don't fall back to default language, use missing translation handler instead
802
+ useDefaultLang: false,
313
803
  }),
314
- // Provide our translation configuration
315
- {
316
- provide: TRANSLATION_CONFIG_TOKEN,
317
- useValue: config || {},
318
- },
319
- // Automatically initialize translation service for MFE compatibility
320
- provideAppInitializer(() => inject(TranslationService).init()),
321
- ];
804
+ // Load runtime config and initialize service
805
+ provideAppInitializer(() => {
806
+ const translationService = inject(TranslationService);
807
+ const logger = inject(LoggerService);
808
+ const router = inject(Router);
809
+ // First initialize the service (will use initial fallback config)
810
+ translationService.init();
811
+ // Helper to load config from file
812
+ const loadConfigFromFile = async () => {
813
+ try {
814
+ const loader = options?.loader ?? new ResourceLoader(RUNTIME_TRANSLATION_LOADER_DEFAULTS, logger);
815
+ const loaderOptions = buildRuntimeTranslationLoaderOptions(configPath, options?.loaderOptions);
816
+ logger.debug('Loading runtime translation config file', { component: 'TranslationProvider', action: 'loadConfigFromFile', configPath });
817
+ const result = await loader.load(configPath, loaderOptions);
818
+ logger.debug('Runtime config loaded', {
819
+ component: 'TranslationProvider',
820
+ action: 'loadConfigFromFile',
821
+ configPath,
822
+ source: result.source,
823
+ translationPaths: result.data?.translationPaths,
824
+ });
825
+ // Update the service with the runtime config
826
+ // This will update paths and reload translations
827
+ await translationService.setRuntimeConfig(result.data);
828
+ logger.debug('Service configured with runtime config', {
829
+ component: 'TranslationProvider',
830
+ action: 'loadConfigFromFile',
831
+ });
832
+ }
833
+ catch (error) {
834
+ logger.error('Failed to load runtime translation config, using fallback', error instanceof Error ? error : new Error(String(error)), {
835
+ component: 'TranslationProvider',
836
+ action: 'loadConfigFromFile',
837
+ configPath,
838
+ });
839
+ }
840
+ };
841
+ // Load config on init
842
+ const initPromise = loadConfigFromFile();
843
+ // Get the effective freshOnNavigation value (from overrides or defaults)
844
+ const effectiveLoaderOptions = buildRuntimeTranslationLoaderOptions(configPath, options?.loaderOptions);
845
+ const shouldUsesFreshOnNavigation = effectiveLoaderOptions.freshOnNavigation ?? false;
846
+ // Also reload config on navigation if freshOnNavigation is enabled
847
+ if (shouldUsesFreshOnNavigation) {
848
+ router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe(() => {
849
+ loadConfigFromFile();
850
+ });
851
+ }
852
+ // CRITICAL: Wait for translations to be fully loaded before returning
853
+ // This ensures the ready() signal is true before components render
854
+ return initPromise.then(async () => {
855
+ try {
856
+ await translationService.waitForTranslations(5000);
857
+ logger.debug('Translation initialization complete', {
858
+ component: 'TranslationProvider',
859
+ action: 'init',
860
+ isReady: translationService.ready(),
861
+ });
862
+ }
863
+ catch (error) {
864
+ logger.warn('Translation service did not reach ready state', {
865
+ component: 'TranslationProvider',
866
+ action: 'init',
867
+ error: error instanceof Error ? error.message : String(error),
868
+ });
869
+ // Don't throw - let app continue with partial translations
870
+ }
871
+ });
872
+ }),
873
+ ]);
322
874
  }
323
875
 
324
- // Export our translation service and types
876
+ // Export main translation service and types
325
877
 
326
878
  /**
327
879
  * Generated bundle index. Do not edit.
328
880
  */
329
881
 
330
- export { DEFAULT_LANGUAGES, DEFAULT_LANGUAGE_CODE, DEFAULT_LANGUAGE_CODES, HttpLoaderFactory, MultiPathHttpLoaderFactory, PlaceholderMissingTranslationHandler, TRANSLATION_CONFIG_TOKEN, TranslationService, createLanguage, extendDefaultLanguages, provideTranslation };
882
+ export { DEFAULT_BASE_LANGUAGE, DEFAULT_LANGUAGES_LIST, DEFAULT_LANGUAGE_CODES, LANGUAGE_ATTRIBUTE_NAME, PlaceholderMissingTranslationHandler, TRANSLATION_CONFIG_TOKEN, TRANSLATION_STORAGE_LANGUAGE_KEY, TRANSLATION_STORAGE_NAMESPACE, TranslationDomService, TranslationService, TranslationStorageService, createLanguage, extendDefaultLanguages, provideRuntimeTranslation, provideTranslation };
331
883
  //# sourceMappingURL=sixbell-telco-sdk-utils-translation.mjs.map