UNPKG

@intlayer/core

Version:

Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.

1 lines 2.4 kB
{"version":3,"file":"localeResolver.mjs","names":[],"sources":["../../../src/localization/localeResolver.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { Locale, LocalesValues } from '@intlayer/types';\n\n/**\n * Resolves the most specific locale from a user-provided list,\n * or falls back to the default locale if no match is found.\n */\nexport const localeResolver = (\n selectedLocale: LocalesValues | LocalesValues[],\n locales: LocalesValues[] = configuration?.internationalization?.locales,\n defaultLocale: LocalesValues = configuration?.internationalization\n ?.defaultLocale\n): Locale => {\n // Ensure we can handle both a single locale or an array of locales uniformly\n const requestedLocales = [selectedLocale].flat();\n\n // Simple helper to normalize locale strings (e.g. \"en-US\" => \"en-us\")\n const normalize = (locale: string): string => locale.trim().toLowerCase();\n\n try {\n // Check each requested locale in order\n for (const requested of requestedLocales) {\n const normalizedRequested = normalize(requested);\n\n // 1) Attempt exact match\n const exactMatch = locales.find(\n (loc) => normalize(loc) === normalizedRequested\n );\n if (exactMatch) {\n return exactMatch as Locale;\n }\n\n // 2) Attempt partial match on language subtag\n // e.g. if requested is \"en-US\" and not found,\n // see if \"en\" is available among locales\n const [requestedLang] = normalizedRequested.split('-');\n const partialMatch = locales.find(\n (loc) => normalize(loc).split('-')[0] === requestedLang\n );\n if (partialMatch) {\n return partialMatch as Locale;\n }\n }\n } catch (_error) {\n // If anything unexpected happened, fall back to default\n }\n\n // If no match was found, return the default\n return defaultLocale as Locale;\n};\n"],"mappings":";;;;;;;AAOA,MAAa,kBACX,gBACA,UAA2B,eAAe,sBAAsB,SAChE,gBAA+B,eAAe,sBAC1C,kBACO;CAEX,MAAM,mBAAmB,CAAC,eAAe,CAAC,MAAM;CAGhD,MAAM,aAAa,WAA2B,OAAO,MAAM,CAAC,aAAa;AAEzE,KAAI;AAEF,OAAK,MAAM,aAAa,kBAAkB;GACxC,MAAM,sBAAsB,UAAU,UAAU;GAGhD,MAAM,aAAa,QAAQ,MACxB,QAAQ,UAAU,IAAI,KAAK,oBAC7B;AACD,OAAI,WACF,QAAO;GAMT,MAAM,CAAC,iBAAiB,oBAAoB,MAAM,IAAI;GACtD,MAAM,eAAe,QAAQ,MAC1B,QAAQ,UAAU,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,cAC3C;AACD,OAAI,aACF,QAAO;;UAGJ,QAAQ;AAKjB,QAAO"}