common-header-lib 0.0.16 → 0.0.17

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.
@@ -4070,57 +4070,171 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImpor
4070
4070
  ],
4071
4071
  }]
4072
4072
  }] });
4073
+ // Single source of truth for the i18n asset path. Used by every translation
4074
+ // HTTP call and by the TranslateHttpLoader factory below.
4075
+ const I18N_BASE_PATH = 'assets/common-header-lib/i18n/';
4076
+ const LANGUAGES_CONFIG_URL = `${I18N_BASE_PATH}languages.json`;
4077
+ /**
4078
+ * Loads a language JSON file, applies it to TranslateService, and persists
4079
+ * the selected language to local storage. Returns true on success, false on
4080
+ * any failure (network error, missing file, etc.) — callers decide whether to
4081
+ * fall through to the next fallback.
4082
+ *
4083
+ * Centralizes the load → setTranslation → setDefaultLang → use → saveData
4084
+ * sequence so each fallback step in initTranslateService stays a single call.
4085
+ */
4086
+ async function loadAndApplyLanguage(lang, http, translate, storage) {
4087
+ try {
4088
+ const translations = await firstValueFrom(http.get(`${I18N_BASE_PATH}${lang.langKey}.json`));
4089
+ translate.setTranslation(lang.langKey, translations);
4090
+ translate.setDefaultLang(lang.langKey);
4091
+ await firstValueFrom(translate.use(lang.langKey));
4092
+ storage.saveData(COOKIECONSTANT.USERLANG, JSON.stringify(lang));
4093
+ return true;
4094
+ }
4095
+ catch {
4096
+ return false;
4097
+ }
4098
+ }
4099
+ /**
4100
+ * Initializes ngx-translate language configuration during application startup.
4101
+ *
4102
+ * Flow:
4103
+ * 1. Load and validate supported languages from:
4104
+ * assets/common-header-lib/i18n/languages.json
4105
+ *
4106
+ * 2. Build USERFILTEREDLANGUAGES using the exact order defined in languages.json:
4107
+ * - removes duplicate langKeys
4108
+ * - ignores unsupported language codes safely
4109
+ *
4110
+ * 3. Read USERLANG from localStorage:
4111
+ * COOKIECONSTANT.USERLANG
4112
+ *
4113
+ * 4. If USERLANG:
4114
+ * - exists in supported languages
4115
+ * - and translation JSON loads successfully
4116
+ * → initialize application using USERLANG
4117
+ *
4118
+ * 5. If USERLANG is invalid or translation loading fails:
4119
+ * → fallback to first language from USERFILTEREDLANGUAGES
4120
+ * (preserving languages.json order)
4121
+ *
4122
+ * 6. If first fallback language also fails:
4123
+ * → fallback to GlobalConstants.DEFAULTLANG
4124
+ *
4125
+ * 7. If DEFAULTLANG translation also fails:
4126
+ * → initialize empty translations safely
4127
+ * → prevent application bootstrap crash
4128
+ *
4129
+ * Example:
4130
+ * languages.json = ["it", "ja", "ko"]
4131
+ * localStorage USERLANG = { langKey: "vi" }
4132
+ *
4133
+ * Result:
4134
+ * - "vi" ignored because unsupported
4135
+ * - tries "it.json"
4136
+ * - if "it.json" fails → loads DEFAULTLANG ("en")
4137
+ *
4138
+ * Notes:
4139
+ * - languages.json controls supported language order and priority
4140
+ * - translation files are validated before translate.use(...)
4141
+ * - invalid localStorage data is ignored safely
4142
+ * - application startup is protected against translation failures
4143
+ */
4073
4144
  function initTranslateService(translate, localStorageService, http, msgService) {
4074
4145
  return async () => {
4075
- let selectedLang = GlobalConstants.DEFAULTLANG;
4146
+ // ---------------------------------------------------------------------
4147
+ // Step 1: Load and validate languages.json (the supported-language list)
4148
+ // ---------------------------------------------------------------------
4076
4149
  try {
4077
- /* 1. Load allowed languages from JSON */
4078
- const codes = await firstValueFrom(http.get('assets/common-header-lib/i18n/languages.json'));
4079
- /* 2. Filter languages */
4080
- GlobalConstants.USERFILTEREDLANGUAGES =
4081
- GlobalConstants.USERLANGUAGES.filter((lang, index, self) => codes?.includes(lang.langKey) &&
4082
- index === self.findIndex((x) => x.langKey === lang.langKey));
4083
- /* 3. Fallback if empty */
4084
- if (!GlobalConstants.USERFILTEREDLANGUAGES ||
4085
- GlobalConstants.USERFILTEREDLANGUAGES.length === 0) {
4150
+ const codes = await firstValueFrom(http.get(LANGUAGES_CONFIG_URL));
4151
+ // Reject anything that is not a non-empty array of non-empty strings.
4152
+ if (!codes ||
4153
+ !Array.isArray(codes) ||
4154
+ codes.length === 0 ||
4155
+ !codes.every((code) => typeof code === 'string' && code.trim().length > 0)) {
4086
4156
  GlobalConstants.USERFILTEREDLANGUAGES = [GlobalConstants.DEFAULTLANG];
4157
+ msgService.error('Invalid or empty languages configuration.', 'Error');
4158
+ }
4159
+ else {
4160
+ // Build filtered list in the exact order defined by languages.json.
4161
+ // Dedupe by langKey and silently drop unsupported codes.
4162
+ const seenKeys = new Set();
4163
+ const ordered = [];
4164
+ for (const raw of codes) {
4165
+ const key = raw.trim();
4166
+ if (seenKeys.has(key))
4167
+ continue;
4168
+ const match = GlobalConstants.USERLANGUAGES.find((lang) => lang.langKey === key);
4169
+ if (match) {
4170
+ seenKeys.add(key);
4171
+ ordered.push(match);
4172
+ }
4173
+ }
4174
+ // If none of the codes matched supported languages, fall back to default.
4175
+ GlobalConstants.USERFILTEREDLANGUAGES =
4176
+ ordered.length > 0 ? ordered : [GlobalConstants.DEFAULTLANG];
4087
4177
  }
4088
4178
  }
4089
4179
  catch {
4090
- /* If languages.json fails */
4180
+ // languages.json failed to load — fall back to default supported list.
4091
4181
  GlobalConstants.USERFILTEREDLANGUAGES = [GlobalConstants.DEFAULTLANG];
4092
- //* Note: Here we directly use English toast as no any .json file is loaded and we cannot rely on translate service to get the message.
4093
- msgService.error('Failed to load language file.', 'Error');
4182
+ msgService.error('Failed to load languages configuration.', 'Error');
4094
4183
  }
4095
- /* 4. Read saved language */
4184
+ // ---------------------------------------------------------------------
4185
+ // Step 2: Read USERLANG from storage and validate against supported list
4186
+ // ---------------------------------------------------------------------
4096
4187
  const saved = localStorageService.getData(COOKIECONSTANT.USERLANG);
4188
+ let userLang = null;
4097
4189
  if (saved) {
4098
4190
  try {
4099
4191
  const parsed = JSON.parse(saved);
4100
- const isValid = GlobalConstants.USERFILTEREDLANGUAGES.some((lang) => lang.langKey === parsed?.langKey);
4101
- if (isValid) {
4102
- selectedLang = parsed;
4192
+ // Only accept saved language if it is still in the supported list.
4193
+ if (GlobalConstants.USERFILTEREDLANGUAGES.some((lang) => lang.langKey === parsed?.langKey)) {
4194
+ userLang = parsed;
4103
4195
  }
4104
4196
  }
4105
4197
  catch {
4106
- selectedLang = GlobalConstants.DEFAULTLANG;
4198
+ // Saved data is corrupt JSON — ignore and fall through to defaults.
4107
4199
  }
4108
4200
  }
4109
- /* 5. Ensure selected language exists */
4110
- const validSelected = GlobalConstants.USERFILTEREDLANGUAGES.find((x) => x.langKey === selectedLang.langKey);
4111
- if (!validSelected) {
4112
- selectedLang =
4113
- GlobalConstants.USERFILTEREDLANGUAGES[0] || GlobalConstants.DEFAULTLANG;
4201
+ // ---------------------------------------------------------------------
4202
+ // Step 3: Attempt to apply USERLANG (highest priority)
4203
+ // ---------------------------------------------------------------------
4204
+ if (userLang) {
4205
+ const ok = await loadAndApplyLanguage(userLang, http, translate, localStorageService);
4206
+ if (ok)
4207
+ return; // Success — bootstrap complete.
4208
+ msgService.error(`Failed to load language file for ${userLang.langName}.`, 'Error');
4209
+ }
4210
+ // ---------------------------------------------------------------------
4211
+ // Step 4: Fallback 1 — first language from languages.json order
4212
+ // ---------------------------------------------------------------------
4213
+ const firstLang = GlobalConstants.USERFILTEREDLANGUAGES[0];
4214
+ if (firstLang) {
4215
+ const ok = await loadAndApplyLanguage(firstLang, http, translate, localStorageService);
4216
+ if (ok)
4217
+ return; // Success — bootstrap complete.
4218
+ msgService.error(`Failed to load language file for ${firstLang.langName}.`, 'Error');
4114
4219
  }
4115
- /* 6. Save corrected language */
4116
- localStorageService.saveData(COOKIECONSTANT.USERLANG, JSON.stringify(selectedLang));
4117
- /* 7. Apply translation */
4118
- translate.setDefaultLang(selectedLang.langKey);
4119
- await firstValueFrom(translate.use(selectedLang.langKey));
4220
+ // ---------------------------------------------------------------------
4221
+ // Step 5: Final fallback — DEFAULTLANG
4222
+ // ---------------------------------------------------------------------
4223
+ const defaultOk = await loadAndApplyLanguage(GlobalConstants.DEFAULTLANG, http, translate, localStorageService);
4224
+ if (defaultOk)
4225
+ return;
4226
+ // ---------------------------------------------------------------------
4227
+ // Step 6: Critical failure — initialize empty translations so the
4228
+ // application can still bootstrap without crashing.
4229
+ // ---------------------------------------------------------------------
4230
+ msgService.error('Critical: Failed to load default language file. Initializing with empty translations.', 'Error');
4231
+ translate.setDefaultLang(GlobalConstants.DEFAULTLANG.langKey);
4232
+ translate.setTranslation(GlobalConstants.DEFAULTLANG.langKey, {});
4233
+ localStorageService.saveData(COOKIECONSTANT.USERLANG, JSON.stringify(GlobalConstants.DEFAULTLANG));
4120
4234
  };
4121
4235
  }
4122
4236
  function createLibTranslateLoader(http) {
4123
- return new TranslateHttpLoader(http, 'assets/common-header-lib/i18n/', '.json');
4237
+ return new TranslateHttpLoader(http, I18N_BASE_PATH, '.json');
4124
4238
  }
4125
4239
 
4126
4240
  /*