@intlayer/core 8.6.3 → 8.6.5
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.
- package/dist/cjs/deepTransformPlugins/getFilterMissingTranslationsContent.cjs +1 -2
- package/dist/cjs/deepTransformPlugins/getFilterMissingTranslationsContent.cjs.map +1 -1
- package/dist/cjs/deepTransformPlugins/getFilterTranslationsOnlyContent.cjs +2 -3
- package/dist/cjs/deepTransformPlugins/getFilterTranslationsOnlyContent.cjs.map +1 -1
- package/dist/cjs/deepTransformPlugins/getMissingLocalesContent.cjs +2 -3
- package/dist/cjs/deepTransformPlugins/getMissingLocalesContent.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +1 -2
- package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs +2 -4
- package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs.map +1 -1
- package/dist/cjs/formatters/compact.cjs +1 -2
- package/dist/cjs/formatters/compact.cjs.map +1 -1
- package/dist/cjs/formatters/currency.cjs +1 -2
- package/dist/cjs/formatters/currency.cjs.map +1 -1
- package/dist/cjs/formatters/date.cjs +1 -2
- package/dist/cjs/formatters/date.cjs.map +1 -1
- package/dist/cjs/formatters/list.cjs +1 -2
- package/dist/cjs/formatters/list.cjs.map +1 -1
- package/dist/cjs/formatters/number.cjs +1 -2
- package/dist/cjs/formatters/number.cjs.map +1 -1
- package/dist/cjs/formatters/percentage.cjs +1 -2
- package/dist/cjs/formatters/percentage.cjs.map +1 -1
- package/dist/cjs/formatters/relativeTime.cjs +1 -2
- package/dist/cjs/formatters/relativeTime.cjs.map +1 -1
- package/dist/cjs/formatters/units.cjs +1 -2
- package/dist/cjs/formatters/units.cjs.map +1 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs +2 -3
- package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
- package/dist/cjs/interpreter/getIntlayer.cjs +1 -2
- package/dist/cjs/interpreter/getIntlayer.cjs.map +1 -1
- package/dist/cjs/localization/getBrowserLocale.cjs +4 -8
- package/dist/cjs/localization/getBrowserLocale.cjs.map +1 -1
- package/dist/cjs/localization/getLocale.cjs +2 -3
- package/dist/cjs/localization/getLocale.cjs.map +1 -1
- package/dist/cjs/localization/getLocalizedUrl.cjs +1 -2
- package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
- package/dist/cjs/localization/getPathWithoutLocale.cjs +1 -2
- package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
- package/dist/cjs/localization/getPrefix.cjs +7 -11
- package/dist/cjs/localization/getPrefix.cjs.map +1 -1
- package/dist/cjs/localization/localeMapper.cjs +3 -4
- package/dist/cjs/localization/localeMapper.cjs.map +1 -1
- package/dist/cjs/localization/localeResolver.cjs +1 -2
- package/dist/cjs/localization/localeResolver.cjs.map +1 -1
- package/dist/cjs/utils/intl.cjs +1 -2
- package/dist/cjs/utils/intl.cjs.map +1 -1
- package/dist/cjs/utils/localeStorage.cjs +27 -34
- package/dist/cjs/utils/localeStorage.cjs.map +1 -1
- package/dist/esm/deepTransformPlugins/getFilterMissingTranslationsContent.mjs +2 -2
- package/dist/esm/deepTransformPlugins/getFilterMissingTranslationsContent.mjs.map +1 -1
- package/dist/esm/deepTransformPlugins/getFilterTranslationsOnlyContent.mjs +3 -3
- package/dist/esm/deepTransformPlugins/getFilterTranslationsOnlyContent.mjs.map +1 -1
- package/dist/esm/deepTransformPlugins/getMissingLocalesContent.mjs +3 -3
- package/dist/esm/deepTransformPlugins/getMissingLocalesContent.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs +2 -2
- package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/orderDictionaries.mjs +2 -3
- package/dist/esm/dictionaryManipulator/orderDictionaries.mjs.map +1 -1
- package/dist/esm/formatters/compact.mjs +2 -2
- package/dist/esm/formatters/compact.mjs.map +1 -1
- package/dist/esm/formatters/currency.mjs +2 -2
- package/dist/esm/formatters/currency.mjs.map +1 -1
- package/dist/esm/formatters/date.mjs +2 -2
- package/dist/esm/formatters/date.mjs.map +1 -1
- package/dist/esm/formatters/list.mjs +2 -2
- package/dist/esm/formatters/list.mjs.map +1 -1
- package/dist/esm/formatters/number.mjs +2 -2
- package/dist/esm/formatters/number.mjs.map +1 -1
- package/dist/esm/formatters/percentage.mjs +2 -2
- package/dist/esm/formatters/percentage.mjs.map +1 -1
- package/dist/esm/formatters/relativeTime.mjs +2 -2
- package/dist/esm/formatters/relativeTime.mjs.map +1 -1
- package/dist/esm/formatters/units.mjs +2 -2
- package/dist/esm/formatters/units.mjs.map +1 -1
- package/dist/esm/interpreter/getContent/getContent.mjs +3 -3
- package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
- package/dist/esm/interpreter/getIntlayer.mjs +2 -2
- package/dist/esm/interpreter/getIntlayer.mjs.map +1 -1
- package/dist/esm/localization/getBrowserLocale.mjs +1 -4
- package/dist/esm/localization/getBrowserLocale.mjs.map +1 -1
- package/dist/esm/localization/getLocale.mjs +3 -3
- package/dist/esm/localization/getLocale.mjs.map +1 -1
- package/dist/esm/localization/getLocalizedUrl.mjs +2 -2
- package/dist/esm/localization/getLocalizedUrl.mjs.map +1 -1
- package/dist/esm/localization/getPathWithoutLocale.mjs +2 -2
- package/dist/esm/localization/getPathWithoutLocale.mjs.map +1 -1
- package/dist/esm/localization/getPrefix.mjs +8 -11
- package/dist/esm/localization/getPrefix.mjs.map +1 -1
- package/dist/esm/localization/localeMapper.mjs +4 -4
- package/dist/esm/localization/localeMapper.mjs.map +1 -1
- package/dist/esm/localization/localeResolver.mjs +2 -2
- package/dist/esm/localization/localeResolver.mjs.map +1 -1
- package/dist/esm/utils/intl.mjs +2 -2
- package/dist/esm/utils/intl.mjs.map +1 -1
- package/dist/esm/utils/localeStorage.mjs +19 -25
- package/dist/esm/utils/localeStorage.mjs.map +1 -1
- package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts.map +1 -1
- package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts.map +1 -1
- package/dist/types/deepTransformPlugins/getMissingLocalesContent.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/mergeDictionaries.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/orderDictionaries.d.ts +1 -2
- package/dist/types/dictionaryManipulator/orderDictionaries.d.ts.map +1 -1
- package/dist/types/localization/getBrowserLocale.d.ts.map +1 -1
- package/dist/types/localization/getLocalizedUrl.d.ts.map +1 -1
- package/dist/types/localization/getPathWithoutLocale.d.ts.map +1 -1
- package/dist/types/localization/getPrefix.d.ts.map +1 -1
- package/dist/types/localization/localeResolver.d.ts.map +1 -1
- package/dist/types/utils/intl.d.ts.map +1 -1
- package/dist/types/utils/localeStorage.d.ts.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"units.cjs","names":["getCachedIntl","
|
|
1
|
+
{"version":3,"file":"units.cjs","names":["getCachedIntl","internationalization"],"sources":["../../../src/formatters/units.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCachedIntl } from '../utils/intl';\n\n/**\n * Formats a numeric value as a localized unit string.\n *\n * @example\n * units(5, { unit: \"kilometer\", unitDisplay: \"long\", locale: \"en-GB\" });\n * // \"5 kilometers\"\n */\nexport const units = (\n value: number | string,\n options?: Intl.NumberFormatOptions & { locale?: LocalesValues }\n): string =>\n getCachedIntl(\n Intl.NumberFormat,\n options?.locale ?? internationalization?.defaultLocale,\n\n {\n style: 'unit',\n unit: options?.unit ?? 'day',\n unitDisplay: options?.unitDisplay ?? 'short',\n useGrouping: options?.useGrouping ?? false,\n }\n ).format(Number(value));\n"],"mappings":";;;;;;;;;;;;;AAWA,MAAa,SACX,OACA,YAEAA,iCACE,KAAK,cACL,SAAS,UAAUC,6CAAsB,eAEzC;CACE,OAAO;CACP,MAAM,SAAS,QAAQ;CACvB,aAAa,SAAS,eAAe;CACrC,aAAa,SAAS,eAAe;CACtC,CACF,CAAC,OAAO,OAAO,MAAM,CAAC"}
|
|
@@ -3,15 +3,14 @@ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
|
3
3
|
const require_interpreter_getContent_deepTransform = require('./deepTransform.cjs');
|
|
4
4
|
const require_interpreter_getContent_plugins = require('./plugins.cjs');
|
|
5
5
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
6
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
7
6
|
|
|
8
7
|
//#region src/interpreter/getContent/getContent.ts
|
|
9
8
|
const getBasePlugins = (locale, fallback = true) => [
|
|
10
|
-
require_interpreter_getContent_plugins.translationPlugin(locale ?? _intlayer_config_built.
|
|
9
|
+
require_interpreter_getContent_plugins.translationPlugin(locale ?? _intlayer_config_built.internationalization.defaultLocale, fallback ? _intlayer_config_built.internationalization.defaultLocale : void 0),
|
|
11
10
|
require_interpreter_getContent_plugins.enumerationPlugin,
|
|
12
11
|
require_interpreter_getContent_plugins.conditionPlugin,
|
|
13
12
|
require_interpreter_getContent_plugins.insertionPlugin,
|
|
14
|
-
require_interpreter_getContent_plugins.nestedPlugin(locale ?? _intlayer_config_built.
|
|
13
|
+
require_interpreter_getContent_plugins.nestedPlugin(locale ?? _intlayer_config_built.internationalization.defaultLocale),
|
|
15
14
|
require_interpreter_getContent_plugins.filePlugin,
|
|
16
15
|
require_interpreter_getContent_plugins.genderPlugin
|
|
17
16
|
].filter(Boolean);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getContent.cjs","names":["translationPlugin","
|
|
1
|
+
{"version":3,"file":"getContent.cjs","names":["translationPlugin","internationalization","enumerationPlugin","conditionPlugin","insertionPlugin","nestedPlugin","filePlugin","genderPlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ].filter(Boolean) as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;;;AAqBA,MAAa,kBACX,QACA,WAAoB,SAEpB;CACEA,yDACE,UAAUC,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,OACjD;CACDC;CACAC;CACAC;CACAC,oDAAa,UAAUJ,4CAAqB,cAAc;CAC1DK;CACAC;CACD,CAAC,OAAO,QAAQ;;;;;;;AAQnB,MAAa,cAIX,MACA,WACA,UAAqB,EAAE,KAEvBC,+DAAkB,MAAM;CACtB,GAAG;CACH;CACD,CAAC"}
|
|
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_interpreter_getDictionary = require('./getDictionary.cjs');
|
|
4
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
6
5
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
7
6
|
let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
8
7
|
|
|
@@ -26,7 +25,7 @@ const createSafeFallback = (path = "") => {
|
|
|
26
25
|
const getIntlayer = (key, locale, plugins) => {
|
|
27
26
|
const dictionary = (0, _intlayer_dictionaries_entry.getDictionaries)()[key];
|
|
28
27
|
if (!dictionary) {
|
|
29
|
-
(0, _intlayer_config_logger.getAppLogger)(_intlayer_config_built.
|
|
28
|
+
(0, _intlayer_config_logger.getAppLogger)({ log: _intlayer_config_built.log })(`Dictionary ${(0, _intlayer_config_logger.colorizeKey)(key)} was not found. Using fallback proxy.`, {
|
|
30
29
|
level: "warn",
|
|
31
30
|
isVerbose: true
|
|
32
31
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayer.cjs","names":["
|
|
1
|
+
{"version":3,"file":"getIntlayer.cjs","names":["getDictionary"],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryContent,\n DictionaryRegistryElement,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy(\n // Target is a function so it can be called if the dictionary expects a function\n () => path,\n {\n get: (_target, prop) => {\n // Handle common object methods to prevent infinite recursion or weird behavior\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n // If the code tries to execute the missing key as a function: t.title()\n apply: () => {\n return path;\n },\n }\n );\n};\n\nexport const getIntlayer = <\n T extends DictionaryKeys,\n L extends LocalesValues = DeclaredLocales,\n>(\n key: T,\n locale?: L,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryContent<T>,\n IInterpreterPluginState,\n L\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T] as DictionaryRegistryElement<T>;\n\n if (!dictionary) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n `Dictionary ${colorizeKey(key as string)} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n isVerbose: true,\n }\n );\n\n if (process.env.NODE_ENV === 'development') {\n // Return the Safe Proxy\n // We initialize it with the dictionary key name so the UI shows \"my-dictionary.someKey\"\n return createSafeFallback(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n return getDictionary<DictionaryRegistryElement<T>, L>(\n dictionary,\n locale,\n plugins\n );\n};\n"],"mappings":";;;;;;;;;;;;AAqBA,MAAM,sBAAsB,OAAO,OAAY;AAC7C,QAAO,IAAI,YAEH,MACN;EACE,MAAM,SAAS,SAAS;AAEtB,OACE,SAAS,YACT,SAAS,OAAO,eAChB,SAAS,WAET,cAAa;AAEf,OAAI,SAAS,OACX;AAKF,UAAO,mBADU,OAAO,GAAG,KAAK,GAAG,OAAO,KAAK,KAAK,OAAO,KAAK,CAC7B;;EAGrC,aAAa;AACX,UAAO;;EAEV,CACF;;AAGH,MAAa,eAIX,KACA,QACA,YAKG;CAEH,MAAM,gEADgC,CACN;AAEhC,KAAI,CAAC,YAAY;AAGf,4CAD4B,EAAE,iCAAK,CAAC,CAElC,uDAA0B,IAAc,CAAC,wCACzC;GACE,OAAO;GACP,WAAW;GACZ,CACF;AAED,MAAI,QAAQ,IAAI,aAAa,cAG3B,QAAO,mBAAmB,IAAc;AAG1C,SAAO,mBAAmB,IAAc;;AAG1C,QAAOA,gDACL,YACA,QACA,QACD"}
|
|
@@ -3,7 +3,6 @@ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
|
3
3
|
const require_utils_localeStorage = require('../utils/localeStorage.cjs');
|
|
4
4
|
const require_localization_localeDetector = require('./localeDetector.cjs');
|
|
5
5
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
6
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
7
6
|
let _intlayer_types_locales = require("@intlayer/types/locales");
|
|
8
7
|
|
|
9
8
|
//#region src/localization/getBrowserLocale.tsx
|
|
@@ -79,9 +78,8 @@ const detectLanguage = (order, options) => {
|
|
|
79
78
|
};
|
|
80
79
|
const navigatorDetector = () => {
|
|
81
80
|
if (typeof navigator === "undefined") return;
|
|
82
|
-
const { internationalization } = _intlayer_config_built.default;
|
|
83
81
|
const languages = navigator.languages ?? [navigator.language];
|
|
84
|
-
const locale = require_localization_localeDetector.localeDetector({ "accept-language": languages.join(",") }, internationalization.locales, internationalization.defaultLocale);
|
|
82
|
+
const locale = require_localization_localeDetector.localeDetector({ "accept-language": languages.join(",") }, _intlayer_config_built.internationalization.locales, _intlayer_config_built.internationalization.defaultLocale);
|
|
85
83
|
if (locale) detected[LanguageDetector.Navigator] = locale;
|
|
86
84
|
};
|
|
87
85
|
const htmlTagDetector = () => {
|
|
@@ -89,8 +87,7 @@ const detectLanguage = (order, options) => {
|
|
|
89
87
|
if (htmlTag && typeof htmlTag.getAttribute === "function") {
|
|
90
88
|
const lang = htmlTag.getAttribute("lang");
|
|
91
89
|
if (lang) {
|
|
92
|
-
const {
|
|
93
|
-
const locale = require_localization_localeDetector.localeDetector({ "accept-language": lang }, internationalization.locales, internationalization.defaultLocale);
|
|
90
|
+
const locale = require_localization_localeDetector.localeDetector({ "accept-language": lang }, _intlayer_config_built.internationalization.locales, _intlayer_config_built.internationalization.defaultLocale);
|
|
94
91
|
detected[LanguageDetector.HtmlTag] = locale;
|
|
95
92
|
}
|
|
96
93
|
}
|
|
@@ -107,12 +104,11 @@ const detectLanguage = (order, options) => {
|
|
|
107
104
|
return detected;
|
|
108
105
|
};
|
|
109
106
|
const getFirstAvailableLocale = (locales, order) => {
|
|
110
|
-
const { internationalization } = _intlayer_config_built.default;
|
|
111
107
|
for (const detector of order) {
|
|
112
108
|
const locale = locales[detector];
|
|
113
|
-
if (locale && internationalization.locales.includes(locale)) return locale;
|
|
109
|
+
if (locale && _intlayer_config_built.internationalization.locales.includes(locale)) return locale;
|
|
114
110
|
}
|
|
115
|
-
return internationalization?.defaultLocale ?? _intlayer_types_locales.ENGLISH;
|
|
111
|
+
return _intlayer_config_built.internationalization?.defaultLocale ?? _intlayer_types_locales.ENGLISH;
|
|
116
112
|
};
|
|
117
113
|
/**
|
|
118
114
|
* Core language detector function for browser environments.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBrowserLocale.cjs","names":["getLocaleFromStorageClient","
|
|
1
|
+
{"version":3,"file":"getBrowserLocale.cjs","names":["getLocaleFromStorageClient","localeDetector","internationalization","ENGLISH"],"sources":["../../../src/localization/getBrowserLocale.tsx"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport {\n getLocaleFromStorageClient,\n type LocaleStorageClientOptions,\n} from '../utils/localeStorage';\nimport { localeDetector } from './localeDetector';\n\nexport enum LanguageDetector {\n Querystring = 'querystring',\n Storage = 'storage',\n Navigator = 'navigator',\n HtmlTag = 'htmlTag',\n}\n\nexport const localeStorageOptions: LocaleStorageClientOptions = {\n getCookie: (name: string) =>\n document.cookie\n .split(';')\n .find((c) => c.trim().startsWith(`${name}=`))\n ?.split('=')[1],\n getLocaleStorage: (name: string) => localStorage.getItem(name),\n getSessionStorage: (name: string) => sessionStorage.getItem(name),\n isCookieEnabled: true,\n setCookieStore: (name, value, attributes) =>\n cookieStore.set({\n name,\n value,\n path: attributes.path,\n domain: attributes.domain,\n expires: attributes.expires,\n sameSite: attributes.sameSite,\n }),\n setCookieString: (_name, cookie) => {\n // biome-ignore lint/suspicious/noDocumentCookie: set cookie fallback\n document.cookie = cookie;\n },\n setSessionStorage: (name, value) => sessionStorage.setItem(name, value),\n setLocaleStorage: (name, value) => localStorage.setItem(name, value),\n};\n\n// Default settings for the language detector\ntype LanguageDetectorOptions = {\n order?: LanguageDetector[];\n lookupQuerystring?: string;\n htmlTag?: HTMLElement | null;\n};\n\nconst getDefaultsOptions = (): LanguageDetectorOptions => {\n return {\n order: [\n LanguageDetector.Querystring,\n LanguageDetector.Storage,\n LanguageDetector.Navigator,\n LanguageDetector.HtmlTag,\n ],\n lookupQuerystring: 'locale',\n htmlTag: typeof document !== 'undefined' ? document.documentElement : null,\n };\n};\n\nconst detectLanguage = (\n order: string[],\n options: LanguageDetectorOptions\n): Record<LanguageDetector, Locale | undefined> => {\n const detected: Record<LanguageDetector, Locale | undefined> = {} as Record<\n LanguageDetector,\n Locale | undefined\n >;\n\n const queryStringDetector = () => {\n if (typeof window === 'undefined') return;\n const search = window.location.search || '';\n const params = new URLSearchParams(search);\n const value = params.get(options.lookupQuerystring ?? '');\n if (value) {\n detected[LanguageDetector.Querystring] = value as Locale;\n }\n };\n\n const storageDetector = () => {\n if (typeof window === 'undefined') return;\n\n const locale = getLocaleFromStorageClient({\n getCookie: (name: string) => {\n try {\n const cookies = document.cookie.split(';');\n const cookieName = `${name}=`;\n\n const cookie = cookies.find((cookie) =>\n cookie.trim().startsWith(cookieName)\n );\n\n if (cookie) {\n return cookie.split('=')[1].trim();\n }\n } catch {}\n return undefined;\n },\n getSessionStorage: (name: string) => {\n try {\n return window.sessionStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n getLocaleStorage: (name: string) => {\n try {\n return window.localStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n });\n\n if (locale) {\n detected[LanguageDetector.Storage] = locale;\n }\n };\n\n const navigatorDetector = () => {\n if (typeof navigator === 'undefined') return;\n\n const languages = navigator.languages ?? [navigator.language];\n\n // Use localeDetector to find the best matching locale\n const locale = localeDetector(\n { 'accept-language': languages.join(',') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n if (locale) {\n detected[LanguageDetector.Navigator] = locale;\n }\n };\n\n const htmlTagDetector = () => {\n const htmlTag = options.htmlTag;\n if (htmlTag && typeof htmlTag.getAttribute === 'function') {\n const lang = htmlTag.getAttribute('lang');\n if (lang) {\n // Validate and resolve the locale\n\n const locale = localeDetector(\n { 'accept-language': lang },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n detected[LanguageDetector.HtmlTag] = locale;\n }\n }\n };\n\n // Map detector names to their corresponding functions\n const detectors: Record<string, () => void> = {\n [LanguageDetector.Querystring]: queryStringDetector,\n [LanguageDetector.Storage]: storageDetector,\n [LanguageDetector.Navigator]: navigatorDetector,\n [LanguageDetector.HtmlTag]: htmlTagDetector,\n };\n\n // Use the provided order to run each detector\n order.forEach((detectorName) => {\n detectors[detectorName]?.();\n });\n\n return detected;\n};\n\nconst getFirstAvailableLocale = (\n locales: Record<LanguageDetector, Locale | undefined>,\n order: LanguageDetector[]\n): Locale => {\n for (const detector of order) {\n const locale = locales[detector];\n\n if (locale && internationalization.locales.includes(locale)) {\n return locale;\n }\n }\n\n return internationalization?.defaultLocale ?? ENGLISH;\n};\n\n/**\n * Core language detector function for browser environments.\n *\n * Detects the user's preferred locale by checking multiple sources in order:\n * 1. Query string parameter\n * 2. Storage (cookies, localStorage, sessionStorage) - uses getLocaleFromStorage\n * 3. Navigator languages - uses localeDetector\n * 4. HTML lang attribute - uses localeDetector\n *\n * @param userOptions - Optional configuration for detection order and lookup keys\n * @returns The detected locale or the default locale\n *\n * @example\n * const locale = getBrowserLocale({ order: [LanguageDetector.Storage, LanguageDetector.Navigator] });\n */\nexport const getBrowserLocale = (\n userOptions: LanguageDetectorOptions | undefined = {}\n): Locale => {\n const options = { ...getDefaultsOptions(), ...userOptions };\n\n const locales = detectLanguage(options.order ?? [], options);\n\n return getFirstAvailableLocale(locales, options.order ?? []);\n};\n"],"mappings":";;;;;;;;AASA,IAAY,mBAAL;AACL;AACA;AACA;AACA;;KACD;AAED,MAAa,uBAAmD;CAC9D,YAAY,SACV,SAAS,OACN,MAAM,IAAI,CACV,MAAM,MAAM,EAAE,MAAM,CAAC,WAAW,GAAG,KAAK,GAAG,CAAC,EAC3C,MAAM,IAAI,CAAC;CACjB,mBAAmB,SAAiB,aAAa,QAAQ,KAAK;CAC9D,oBAAoB,SAAiB,eAAe,QAAQ,KAAK;CACjE,iBAAiB;CACjB,iBAAiB,MAAM,OAAO,eAC5B,YAAY,IAAI;EACd;EACA;EACA,MAAM,WAAW;EACjB,QAAQ,WAAW;EACnB,SAAS,WAAW;EACpB,UAAU,WAAW;EACtB,CAAC;CACJ,kBAAkB,OAAO,WAAW;AAElC,WAAS,SAAS;;CAEpB,oBAAoB,MAAM,UAAU,eAAe,QAAQ,MAAM,MAAM;CACvE,mBAAmB,MAAM,UAAU,aAAa,QAAQ,MAAM,MAAM;CACrE;AASD,MAAM,2BAAoD;AACxD,QAAO;EACL,OAAO;GACL,iBAAiB;GACjB,iBAAiB;GACjB,iBAAiB;GACjB,iBAAiB;GAClB;EACD,mBAAmB;EACnB,SAAS,OAAO,aAAa,cAAc,SAAS,kBAAkB;EACvE;;AAGH,MAAM,kBACJ,OACA,YACiD;CACjD,MAAM,WAAyD,EAAE;CAKjE,MAAM,4BAA4B;AAChC,MAAI,OAAO,WAAW,YAAa;EACnC,MAAM,SAAS,OAAO,SAAS,UAAU;EAEzC,MAAM,QADS,IAAI,gBAAgB,OAAO,CACrB,IAAI,QAAQ,qBAAqB,GAAG;AACzD,MAAI,MACF,UAAS,iBAAiB,eAAe;;CAI7C,MAAM,wBAAwB;AAC5B,MAAI,OAAO,WAAW,YAAa;EAEnC,MAAM,SAASA,uDAA2B;GACxC,YAAY,SAAiB;AAC3B,QAAI;KACF,MAAM,UAAU,SAAS,OAAO,MAAM,IAAI;KAC1C,MAAM,aAAa,GAAG,KAAK;KAE3B,MAAM,SAAS,QAAQ,MAAM,WAC3B,OAAO,MAAM,CAAC,WAAW,WAAW,CACrC;AAED,SAAI,OACF,QAAO,OAAO,MAAM,IAAI,CAAC,GAAG,MAAM;YAE9B;;GAGV,oBAAoB,SAAiB;AACnC,QAAI;AACF,YAAO,OAAO,eAAe,QAAQ,KAAK,IAAI;YACxC;;GAGV,mBAAmB,SAAiB;AAClC,QAAI;AACF,YAAO,OAAO,aAAa,QAAQ,KAAK,IAAI;YACtC;;GAGX,CAAC;AAEF,MAAI,OACF,UAAS,iBAAiB,WAAW;;CAIzC,MAAM,0BAA0B;AAC9B,MAAI,OAAO,cAAc,YAAa;EAEtC,MAAM,YAAY,UAAU,aAAa,CAAC,UAAU,SAAS;EAG7D,MAAM,SAASC,mDACb,EAAE,mBAAmB,UAAU,KAAK,IAAI,EAAE,EAC1CC,4CAAqB,SACrBA,4CAAqB,cACtB;AAED,MAAI,OACF,UAAS,iBAAiB,aAAa;;CAI3C,MAAM,wBAAwB;EAC5B,MAAM,UAAU,QAAQ;AACxB,MAAI,WAAW,OAAO,QAAQ,iBAAiB,YAAY;GACzD,MAAM,OAAO,QAAQ,aAAa,OAAO;AACzC,OAAI,MAAM;IAGR,MAAM,SAASD,mDACb,EAAE,mBAAmB,MAAM,EAC3BC,4CAAqB,SACrBA,4CAAqB,cACtB;AAED,aAAS,iBAAiB,WAAW;;;;CAM3C,MAAM,YAAwC;GAC3C,iBAAiB,cAAc;GAC/B,iBAAiB,UAAU;GAC3B,iBAAiB,YAAY;GAC7B,iBAAiB,UAAU;EAC7B;AAGD,OAAM,SAAS,iBAAiB;AAC9B,YAAU,iBAAiB;GAC3B;AAEF,QAAO;;AAGT,MAAM,2BACJ,SACA,UACW;AACX,MAAK,MAAM,YAAY,OAAO;EAC5B,MAAM,SAAS,QAAQ;AAEvB,MAAI,UAAUA,4CAAqB,QAAQ,SAAS,OAAO,CACzD,QAAO;;AAIX,QAAOA,6CAAsB,iBAAiBC;;;;;;;;;;;;;;;;;AAkBhD,MAAa,oBACX,cAAmD,EAAE,KAC1C;CACX,MAAM,UAAU;EAAE,GAAG,oBAAoB;EAAE,GAAG;EAAa;AAI3D,QAAO,wBAFS,eAAe,QAAQ,SAAS,EAAE,EAAE,QAAQ,EAEpB,QAAQ,SAAS,EAAE,CAAC"}
|
|
@@ -4,13 +4,12 @@ const require_utils_localeStorage = require('../utils/localeStorage.cjs');
|
|
|
4
4
|
const require_localization_localeResolver = require('./localeResolver.cjs');
|
|
5
5
|
const require_localization_localeDetector = require('./localeDetector.cjs');
|
|
6
6
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
7
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
8
7
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
9
8
|
|
|
10
9
|
//#region src/localization/getLocale.ts
|
|
11
10
|
const getLocale = async (ctx = {}) => {
|
|
12
|
-
const defaultLocale = _intlayer_config_built.
|
|
13
|
-
const availableLocales = _intlayer_config_built.
|
|
11
|
+
const defaultLocale = _intlayer_config_built.internationalization?.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE;
|
|
12
|
+
const availableLocales = _intlayer_config_built.internationalization?.locales ?? _intlayer_config_defaultValues.LOCALES;
|
|
14
13
|
const storedLocale = require_utils_localeStorage.getLocaleFromStorageServer({
|
|
15
14
|
getCookie: ctx.getCookie,
|
|
16
15
|
getHeader: ctx.getHeader
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocale.cjs","names":["
|
|
1
|
+
{"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE","LOCALES","getLocaleFromStorageServer","localeResolver","getPreferredLanguages"],"sources":["../../../src/localization/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE, LOCALES } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageServer } from '../utils/localeStorage';\nimport { getPreferredLanguages } from './localeDetector';\nimport { localeResolver } from './localeResolver';\n\nexport type RequestContext = {\n getHeader?: (name: string) => string | null | undefined;\n getCookie?: (name: string) => string | null | undefined;\n};\n\nexport const getLocale = async (ctx: RequestContext = {}): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n const availableLocales = internationalization?.locales ?? LOCALES;\n\n // Try locale from storage (cookie or header)\n const storedLocale = getLocaleFromStorageServer({\n getCookie: ctx.getCookie,\n getHeader: ctx.getHeader,\n });\n\n if (storedLocale) {\n return storedLocale;\n }\n\n // Fallback to Accept-Language negotiation\n const acceptLanguageHeader = ctx.getHeader?.('accept-language');\n\n if (!acceptLanguageHeader) {\n return defaultLocale;\n }\n\n const preferredLocaleStrings = getPreferredLanguages(\n acceptLanguageHeader,\n availableLocales\n );\n\n const userFallbackLocale = localeResolver(\n preferredLocaleStrings,\n availableLocales,\n defaultLocale\n );\n\n if (userFallbackLocale) {\n return userFallbackLocale;\n }\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;AAYA,MAAa,YAAY,OAAO,MAAsB,EAAE,KAAsB;CAC5E,MAAM,gBAAgBA,6CAAsB,iBAAiBC;CAC7D,MAAM,mBAAmBD,6CAAsB,WAAWE;CAG1D,MAAM,eAAeC,uDAA2B;EAC9C,WAAW,IAAI;EACf,WAAW,IAAI;EAChB,CAAC;AAEF,KAAI,aACF,QAAO;CAIT,MAAM,uBAAuB,IAAI,YAAY,kBAAkB;AAE/D,KAAI,CAAC,qBACH,QAAO;CAQT,MAAM,qBAAqBC,mDALIC,0DAC7B,sBACA,iBACD,EAIC,kBACA,cACD;AAED,KAAI,mBACF,QAAO;AAIT,QAAO"}
|
|
@@ -5,7 +5,6 @@ const require_localization_getPathWithoutLocale = require('./getPathWithoutLocal
|
|
|
5
5
|
const require_localization_getPrefix = require('./getPrefix.cjs');
|
|
6
6
|
const require_localization_rewriteUtils = require('./rewriteUtils.cjs');
|
|
7
7
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
8
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
9
8
|
|
|
10
9
|
//#region src/localization/getLocalizedUrl.ts
|
|
11
10
|
/**
|
|
@@ -52,7 +51,7 @@ const TREE_SHAKE_SEARCH_PARAMS = process.env["INTLAYER_ROUTING_MODE"] && process
|
|
|
52
51
|
* @param options.mode - URL routing mode for locale handling. Defaults to configured mode.
|
|
53
52
|
* @returns The localized URL for the current locale.
|
|
54
53
|
*/
|
|
55
|
-
const getLocalizedUrl = (url, currentLocale = _intlayer_config_built.
|
|
54
|
+
const getLocalizedUrl = (url, currentLocale = _intlayer_config_built.internationalization?.defaultLocale, options = {}) => {
|
|
56
55
|
const { defaultLocale, mode, locales, rewrite } = require_localization_getPrefix.resolveRoutingConfig(options);
|
|
57
56
|
const urlWithoutLocale = require_localization_getPathWithoutLocale.getPathWithoutLocale(url, locales);
|
|
58
57
|
const rewriteRules = require_localization_rewriteUtils.getRewriteRules(rewrite, "url");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocalizedUrl.cjs","names":["
|
|
1
|
+
{"version":3,"file":"getLocalizedUrl.cjs","names":["internationalization","resolveRoutingConfig","getPathWithoutLocale","getRewriteRules","getLocalizedPath","getCanonicalPath","checkIsURLAbsolute","getPrefix"],"sources":["../../../src/localization/getLocalizedUrl.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when the build-time routing mode is known and is NOT 'no-prefix'.\n */\nconst TREE_SHAKE_NO_PREFIX =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'no-prefix';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\nimport {\n getPrefix,\n type RoutingOptions,\n resolveRoutingConfig,\n} from './getPrefix';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from './rewriteUtils';\n\nexport type { RoutingOptions };\n\n/**\n * Generate URL by prefixing the given URL with the referenced locale or adding search parameters\n * based on the routing mode. Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' });\n * // Returns '/fr/about' for the French locale\n * // Returns '/about' for the English locale (default)\n *\n * // prefix-all mode\n * getLocalizedUrl('/about', 'en', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' });\n * // Returns '/en/about' for the English locale\n * // Returns '/fr/about' for the French locale\n *\n * // search-params mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' });\n * // Returns '/about?locale=fr' for the French locale\n *\n * // no-prefix mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' });\n * // Returns '/about' for any locale\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param currentLocale - The current locale.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns The localized URL for the current locale.\n */\nexport const getLocalizedUrl = (\n url: string,\n currentLocale: LocalesValues = internationalization?.defaultLocale,\n\n options: RoutingOptions = {}\n): string => {\n const { defaultLocale, mode, locales, rewrite } =\n resolveRoutingConfig(options);\n\n const urlWithoutLocale = getPathWithoutLocale(url, locales);\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n if (!TREE_SHAKE_NO_PREFIX && mode === 'no-prefix') {\n return getLocalizedPath(\n getCanonicalPath(urlWithoutLocale, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n }\n\n const isAbsoluteUrl = checkIsURLAbsolute(urlWithoutLocale);\n const parsedUrl = isAbsoluteUrl\n ? new URL(urlWithoutLocale)\n : new URL(urlWithoutLocale, 'http://example.com');\n\n const translatedPathname = getLocalizedPath(\n getCanonicalPath(parsedUrl.pathname, undefined, rewriteRules),\n currentLocale as Locale,\n rewriteRules\n ).path;\n\n const baseUrl = isAbsoluteUrl\n ? `${parsedUrl.protocol}//${parsedUrl.host}`\n : '';\n\n if (!TREE_SHAKE_SEARCH_PARAMS && mode === 'search-params') {\n const searchParams = new URLSearchParams(parsedUrl.search);\n\n searchParams.set('locale', currentLocale.toString());\n\n const queryParams = searchParams.toString();\n const path = queryParams\n ? `${translatedPathname}?${queryParams}`\n : translatedPathname;\n\n return `${baseUrl}${path}${parsedUrl.hash}`;\n }\n\n const { prefix } = getPrefix(currentLocale, { defaultLocale, mode, locales });\n\n let localizedPath = `/${prefix}${translatedPathname}`.replace(/\\/+/g, '/');\n\n if (localizedPath.length > 1 && localizedPath.endsWith('/')) {\n localizedPath = localizedPath.slice(0, -1);\n }\n\n return `${baseUrl}${localizedPath}${parsedUrl.search}${parsedUrl.hash}`;\n};\n"],"mappings":";;;;;;;;;;;;AAUA,MAAM,uBACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;AAK3C,MAAM,2BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuD3C,MAAa,mBACX,KACA,gBAA+BA,6CAAsB,eAErD,UAA0B,EAAE,KACjB;CACX,MAAM,EAAE,eAAe,MAAM,SAAS,YACpCC,oDAAqB,QAAQ;CAE/B,MAAM,mBAAmBC,+DAAqB,KAAK,QAAQ;CAC3D,MAAM,eAAeC,kDAAgB,SAAS,MAAM;AAEpD,KAAI,CAAC,wBAAwB,SAAS,YACpC,QAAOC,mDACLC,mDAAiB,kBAAkB,QAAW,aAAa,EAC3D,eACA,aACD,CAAC;CAGJ,MAAM,gBAAgBC,oDAAmB,iBAAiB;CAC1D,MAAM,YAAY,gBACd,IAAI,IAAI,iBAAiB,GACzB,IAAI,IAAI,kBAAkB,qBAAqB;CAEnD,MAAM,qBAAqBF,mDACzBC,mDAAiB,UAAU,UAAU,QAAW,aAAa,EAC7D,eACA,aACD,CAAC;CAEF,MAAM,UAAU,gBACZ,GAAG,UAAU,SAAS,IAAI,UAAU,SACpC;AAEJ,KAAI,CAAC,4BAA4B,SAAS,iBAAiB;EACzD,MAAM,eAAe,IAAI,gBAAgB,UAAU,OAAO;AAE1D,eAAa,IAAI,UAAU,cAAc,UAAU,CAAC;EAEpD,MAAM,cAAc,aAAa,UAAU;AAK3C,SAAO,GAAG,UAJG,cACT,GAAG,mBAAmB,GAAG,gBACzB,qBAEuB,UAAU;;CAGvC,MAAM,EAAE,WAAWE,yCAAU,eAAe;EAAE;EAAe;EAAM;EAAS,CAAC;CAE7E,IAAI,gBAAgB,IAAI,SAAS,qBAAqB,QAAQ,QAAQ,IAAI;AAE1E,KAAI,cAAc,SAAS,KAAK,cAAc,SAAS,IAAI,CACzD,iBAAgB,cAAc,MAAM,GAAG,GAAG;AAG5C,QAAO,GAAG,UAAU,gBAAgB,UAAU,SAAS,UAAU"}
|
|
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
|
|
4
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
6
5
|
|
|
7
6
|
//#region src/localization/getPathWithoutLocale.ts
|
|
8
7
|
/**
|
|
@@ -38,7 +37,7 @@ const TREE_SHAKE_SEARCH_PARAMS = process.env["INTLAYER_ROUTING_MODE"] && process
|
|
|
38
37
|
* @param locales - Optional array of supported locales. Defaults to `localesDefault`.
|
|
39
38
|
* @returns The URL string or pathname without the locale segment or locale search parameter.
|
|
40
39
|
*/
|
|
41
|
-
const getPathWithoutLocale = (inputUrl, locales = _intlayer_config_built.
|
|
40
|
+
const getPathWithoutLocale = (inputUrl, locales = _intlayer_config_built.internationalization?.locales) => {
|
|
42
41
|
const isAbsoluteUrl = require_utils_checkIsURLAbsolute.checkIsURLAbsolute(inputUrl);
|
|
43
42
|
let fixedInputUrl = inputUrl;
|
|
44
43
|
if (inputUrl?.endsWith("/")) fixedInputUrl = inputUrl.slice(0, -1);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPathWithoutLocale.cjs","names":["
|
|
1
|
+
{"version":3,"file":"getPathWithoutLocale.cjs","names":["internationalization","checkIsURLAbsolute"],"sources":["../../../src/localization/getPathWithoutLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\n/**\n * True when the build-time routing mode is known and is NOT 'search-params'.\n */\nconst TREE_SHAKE_SEARCH_PARAMS =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'search-params';\n\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\n\n/**\n * Removes the locale segment from the given URL or pathname if present.\n * Also removes locale from search parameters if present.\n *\n * This function get the locales from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * getPathWithoutLocale('/en/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/fr/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('/dashboard') // Returns '/dashboard'\n * getPathWithoutLocale('dashboard') // Returns 'dashboard'\n * getPathWithoutLocale('/dashboard?locale=fr') // Returns '/dashboard'\n * getPathWithoutLocale('https://example.com/en/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/fr/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard') // Returns 'https://example.com/dashboard'\n * getPathWithoutLocale('https://example.com/dashboard?locale=fr') // Returns 'https://example.com/dashboard'\n * ```\n *\n * @param inputUrl - The complete URL string or pathname to process.\n * @param locales - Optional array of supported locales. Defaults to `localesDefault`.\n * @returns The URL string or pathname without the locale segment or locale search parameter.\n */\nexport const getPathWithoutLocale = (\n inputUrl: string,\n locales: LocalesValues[] = internationalization?.locales\n\n): string => {\n // Determine if the original URL is absolute (includes protocol)\n const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);\n\n let fixedInputUrl = inputUrl;\n\n if (inputUrl?.endsWith('/')) {\n fixedInputUrl = inputUrl.slice(0, -1);\n }\n\n // Initialize a URL object if the URL is absolute\n // For relative URLs, use a dummy base to leverage the URL API\n const url = isAbsoluteUrl\n ? new URL(fixedInputUrl)\n : new URL(fixedInputUrl, 'http://example.com');\n\n const pathname = url.pathname;\n\n // Ensure the pathname starts with '/'\n if (!pathname.startsWith('/')) {\n // If not, return the URL as is\n url.pathname = `/${pathname}`;\n }\n\n // Only strip locale path prefix in prefix-based routing modes\n if (!TREE_SHAKE_PREFIX_MODES) {\n // Split the pathname to extract the first segment\n const pathSegments = pathname.split('/');\n const firstSegment = pathSegments[1]; // The segment after the first '/'\n\n // Check if the first segment is a supported locale\n if (locales?.includes(firstSegment as LocalesValues)) {\n // Remove the locale segment from the pathname\n pathSegments.splice(1, 1); // Remove the first segment\n\n // Reconstruct the pathname\n const newPathname = pathSegments.join('/') ?? '/';\n url.pathname = newPathname;\n }\n }\n\n // Only strip locale from search parameters in search-params routing mode\n if (!TREE_SHAKE_SEARCH_PARAMS) {\n const searchParams = new URLSearchParams(url.search);\n if (searchParams.has('locale')) {\n searchParams.delete('locale');\n url.search = searchParams.toString();\n }\n }\n\n if (isAbsoluteUrl) {\n // Return the modified URL as a string\n return url.toString();\n }\n\n // Return the modified URL as a string\n return url.toString().replace('http://example.com', '');\n};\n"],"mappings":";;;;;;;;;;AAWA,MAAM,0BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBACzC,QAAQ,IAAI,6BAA6B;;;;AAK3C,MAAM,2BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3C,MAAa,wBACX,UACA,UAA2BA,6CAAsB,YAEtC;CAEX,MAAM,gBAAgBC,oDAAmB,SAAS;CAElD,IAAI,gBAAgB;AAEpB,KAAI,UAAU,SAAS,IAAI,CACzB,iBAAgB,SAAS,MAAM,GAAG,GAAG;CAKvC,MAAM,MAAM,gBACR,IAAI,IAAI,cAAc,GACtB,IAAI,IAAI,eAAe,qBAAqB;CAEhD,MAAM,WAAW,IAAI;AAGrB,KAAI,CAAC,SAAS,WAAW,IAAI,CAE3B,KAAI,WAAW,IAAI;AAIrB,KAAI,CAAC,yBAAyB;EAE5B,MAAM,eAAe,SAAS,MAAM,IAAI;EACxC,MAAM,eAAe,aAAa;AAGlC,MAAI,SAAS,SAAS,aAA8B,EAAE;AAEpD,gBAAa,OAAO,GAAG,EAAE;AAIzB,OAAI,WADgB,aAAa,KAAK,IAAI,IAAI;;;AAMlD,KAAI,CAAC,0BAA0B;EAC7B,MAAM,eAAe,IAAI,gBAAgB,IAAI,OAAO;AACpD,MAAI,aAAa,IAAI,SAAS,EAAE;AAC9B,gBAAa,OAAO,SAAS;AAC7B,OAAI,SAAS,aAAa,UAAU;;;AAIxC,KAAI,cAEF,QAAO,IAAI,UAAU;AAIvB,QAAO,IAAI,UAAU,CAAC,QAAQ,sBAAsB,GAAG"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
4
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
5
4
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
6
5
|
|
|
7
6
|
//#region src/localization/getPrefix.ts
|
|
@@ -14,16 +13,13 @@ const TREE_SHAKE_PREFIX_MODES = process.env["INTLAYER_ROUTING_MODE"] && process.
|
|
|
14
13
|
* Resolves routing configuration by merging provided options with configuration defaults.
|
|
15
14
|
* Single source of truth for default routing config resolution across all localization functions.
|
|
16
15
|
*/
|
|
17
|
-
const resolveRoutingConfig = (options = {}) => {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
...options
|
|
25
|
-
};
|
|
26
|
-
};
|
|
16
|
+
const resolveRoutingConfig = (options = {}) => ({
|
|
17
|
+
defaultLocale: _intlayer_config_built.internationalization?.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE,
|
|
18
|
+
mode: _intlayer_config_built.routing?.mode ?? _intlayer_config_defaultValues.ROUTING_MODE,
|
|
19
|
+
locales: _intlayer_config_built.internationalization?.locales ?? _intlayer_config_defaultValues.LOCALES,
|
|
20
|
+
rewrite: _intlayer_config_built.routing?.rewrite,
|
|
21
|
+
...options
|
|
22
|
+
});
|
|
27
23
|
/**
|
|
28
24
|
* Determines the URL prefix for a given locale based on the routing mode configuration.
|
|
29
25
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPrefix.cjs","names":["
|
|
1
|
+
{"version":3,"file":"getPrefix.cjs","names":["internationalization","DEFAULT_LOCALE","routing","ROUTING_MODE","LOCALES"],"sources":["../../../src/localization/getPrefix.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n ROUTING_MODE,\n} from '@intlayer/config/defaultValues';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when the build-time routing mode is known and is not a prefix-based\n * mode (neither 'prefix-all' nor 'prefix-no-default').\n */\nconst TREE_SHAKE_PREFIX_MODES =\n process.env['INTLAYER_ROUTING_MODE'] &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-all' &&\n process.env['INTLAYER_ROUTING_MODE'] !== 'prefix-no-default';\n\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { RoutingConfig } from '@intlayer/types/config';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Shared routing options used across all URL localization functions.\n */\nexport type RoutingOptions = {\n locales?: LocalesValues[];\n defaultLocale?: LocalesValues;\n mode?: RoutingConfig['mode'];\n rewrite?: RoutingConfig['rewrite'];\n};\n\n/**\n * Resolves routing configuration by merging provided options with configuration defaults.\n * Single source of truth for default routing config resolution across all localization functions.\n */\nexport const resolveRoutingConfig = (options: RoutingOptions = {}) => ({\n defaultLocale: internationalization?.defaultLocale ?? DEFAULT_LOCALE,\n mode: routing?.mode ?? ROUTING_MODE,\n locales: internationalization?.locales ?? LOCALES,\n rewrite: routing?.rewrite,\n ...options,\n});\n\nexport type GetPrefixOptions = {\n defaultLocale?: LocalesValues;\n mode?: RoutingConfig['mode'];\n};\n\nexport type GetPrefixResult = {\n /**\n * The complete base URL path with leading and trailing slashes.\n *\n * @example\n * // https://example.com/fr/about -> '/fr'\n * // https://example.com/about -> ''\n */\n prefix: string;\n /**\n * The locale identifier without slashes.\n *\n * @example\n * // https://example.com/fr/about -> 'fr'\n * // https://example.com/about -> undefined\n */\n localePrefix: Locale | undefined;\n};\n\n/**\n * Determines the URL prefix for a given locale based on the routing mode configuration.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode with default locale\n * getPrefix('en', { defaultLocale: 'en', mode: 'prefix-no-default' })\n * // Returns { prefix: '', localePrefix: undefined }\n *\n * // prefix-no-default mode with non-default locale\n * getPrefix('fr', { defaultLocale: 'en', mode: 'prefix-no-default' })\n * // Returns { prefix: '/fr', localePrefix: 'fr' }\n *\n * // prefix-all mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'prefix-all' })\n * // Returns { prefix: '/en', localePrefix: locale }\n *\n * // search-params mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'search-params' })\n * // Returns { prefix: '', localePrefix: undefined }\n *\n * // no-prefix mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'no-prefix' })\n * // Returns { prefix: '', localePrefix: undefined }\n * ```\n *\n * @param locale - The locale to check for prefix. If not provided, uses configured default locale.\n * @param options - Configuration options\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns An object containing pathPrefix, prefix, and localePrefix for the given locale.\n */\nexport const getPrefix = (\n locale: LocalesValues | undefined,\n options: RoutingOptions = {}\n): GetPrefixResult => {\n const { defaultLocale, mode, locales } = resolveRoutingConfig(options);\n\n if (TREE_SHAKE_PREFIX_MODES || !locale || !locales.includes(locale)) {\n return {\n prefix: '',\n localePrefix: undefined,\n };\n }\n\n // Handle prefix-based modes (prefix-all or prefix-no-default)\n const shouldPrefix =\n mode === 'prefix-all' ||\n (mode === 'prefix-no-default' && defaultLocale !== locale);\n\n if (shouldPrefix) {\n return {\n prefix: `${locale}/`,\n localePrefix: locale as Locale,\n };\n }\n\n return {\n prefix: '',\n localePrefix: undefined,\n };\n};\n"],"mappings":";;;;;;;;;;AAeA,MAAM,0BACJ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BAA6B,gBACzC,QAAQ,IAAI,6BAA6B;;;;;AAoB3C,MAAa,wBAAwB,UAA0B,EAAE,MAAM;CACrE,eAAeA,6CAAsB,iBAAiBC;CACtD,MAAMC,gCAAS,QAAQC;CACvB,SAASH,6CAAsB,WAAWI;CAC1C,SAASF,gCAAS;CAClB,GAAG;CACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DD,MAAa,aACX,QACA,UAA0B,EAAE,KACR;CACpB,MAAM,EAAE,eAAe,MAAM,YAAY,qBAAqB,QAAQ;AAEtE,KAAI,2BAA2B,CAAC,UAAU,CAAC,QAAQ,SAAS,OAAO,CACjE,QAAO;EACL,QAAQ;EACR,cAAc;EACf;AAQH,KAHE,SAAS,gBACR,SAAS,uBAAuB,kBAAkB,OAGnD,QAAO;EACL,QAAQ,GAAG,OAAO;EAClB,cAAc;EACf;AAGH,QAAO;EACL,QAAQ;EACR,cAAc;EACf"}
|
|
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_localization_getPrefix = require('./getPrefix.cjs');
|
|
4
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
6
5
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
7
6
|
|
|
8
7
|
//#region src/localization/localeMapper.ts
|
|
@@ -32,7 +31,7 @@ let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
|
32
31
|
* @param mapper - The mapper function that returns an object
|
|
33
32
|
* @returns An array of objects
|
|
34
33
|
*/
|
|
35
|
-
const localeMap = (mapper, locales = _intlayer_config_built.
|
|
34
|
+
const localeMap = (mapper, locales = _intlayer_config_built.internationalization.locales ?? [], defaultLocale = _intlayer_config_built.internationalization.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE, mode = _intlayer_config_built.routing?.mode ?? "prefix-no-default") => (locales ?? []).map((locale) => mapper({
|
|
36
35
|
locale,
|
|
37
36
|
defaultLocale,
|
|
38
37
|
locales,
|
|
@@ -69,7 +68,7 @@ const localeMap = (mapper, locales = _intlayer_config_built.default?.internation
|
|
|
69
68
|
* @param mapper - The mapper function that returns an array of objects
|
|
70
69
|
* @returns An array of objects
|
|
71
70
|
*/
|
|
72
|
-
const localeFlatMap = (mapper, locales = _intlayer_config_built.
|
|
71
|
+
const localeFlatMap = (mapper, locales = _intlayer_config_built.internationalization.locales ?? [], defaultLocale = _intlayer_config_built.internationalization.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE, mode = _intlayer_config_built.routing?.mode ?? "prefix-no-default") => locales.flatMap((locale) => mapper({
|
|
73
72
|
locale,
|
|
74
73
|
defaultLocale,
|
|
75
74
|
locales,
|
|
@@ -103,7 +102,7 @@ const localeFlatMap = (mapper, locales = _intlayer_config_built.default?.interna
|
|
|
103
102
|
* @param mode - URL routing mode for locale handling (defaults to configured value)
|
|
104
103
|
* @returns Record mapping locale codes to mapped values
|
|
105
104
|
*/
|
|
106
|
-
const localeRecord = (mapper, locales = _intlayer_config_built.
|
|
105
|
+
const localeRecord = (mapper, locales = _intlayer_config_built.internationalization.locales ?? [], defaultLocale = _intlayer_config_built.internationalization.defaultLocale ?? _intlayer_config_defaultValues.DEFAULT_LOCALE, mode = _intlayer_config_built.routing?.mode ?? "prefix-no-default") => (locales ?? []).reduce((acc, locale) => {
|
|
107
106
|
acc[locale] = mapper({
|
|
108
107
|
locale,
|
|
109
108
|
defaultLocale,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localeMapper.cjs","names":["
|
|
1
|
+
{"version":3,"file":"localeMapper.cjs","names":["internationalization","DEFAULT_LOCALE","routing","getPrefix"],"sources":["../../../src/localization/localeMapper.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getPrefix } from './getPrefix';\n\nexport type LocaleData = {\n locale: Locale;\n defaultLocale: Locale;\n isDefault: boolean;\n locales: Locale[];\n urlPrefix: string;\n};\n\n/**\n * Map the locale data to an array of objects\n *\n * @example\n * ```ts\n * const routes = localeMap((localizedData) =>\n * ({\n * path: localizedData.urlPrefix,\n * name: localizedData.locale,\n * isDefault: localizedData.isDefault,\n * locales: localizedData.locales,\n * defaultLocale: localizedData.defaultLocale,\n * }),\n * );\n *\n * // Result\n * [\n * { path: '/', name: 'en', isDefault: true, locales: ['en'], defaultLocale: 'en', urlPrefix: '' },\n * { path: '/fr', name: 'fr', isDefault: false, locales: ['fr'], defaultLocale: 'en', urlPrefix: '/fr' },\n * { path: '/es', name: 'es', isDefault: false, locales: ['es'], defaultLocale: 'en', urlPrefix: '/es' },\n * ]\n * ```\n *\n * @param mapper - The mapper function that returns an object\n * @returns An array of objects\n */\nexport const localeMap = <T>(\n mapper: (locale: LocaleData) => T,\n locales: LocalesValues[] = internationalization.locales ?? [],\n defaultLocale: LocalesValues = internationalization.defaultLocale ??\n DEFAULT_LOCALE,\n mode:\n | 'prefix-no-default'\n | 'prefix-all'\n | 'no-prefix'\n | 'search-params' = routing?.mode ?? 'prefix-no-default'\n): T[] =>\n (locales ?? []).map((locale) =>\n mapper({\n locale,\n defaultLocale,\n locales,\n isDefault: locale === defaultLocale,\n urlPrefix: getPrefix(locale, { defaultLocale, mode, locales })\n .localePrefix\n ? `/${locale}`\n : '',\n } as LocaleData)\n );\n\n/**\n * Flatten the locale map into a single array of objects\n *\n * @example\n * ```ts\n * const routes = localeMap((localizedData) =>\n * [{\n * path: localizedData.urlPrefix,\n * name: localizedData.locale,\n * isDefault: localizedData.isDefault,\n * locales: localizedData.locales,\n * defaultLocale: localizedData.defaultLocale,\n * }],\n * );\n *\n * // Result\n * [\n * path: '/', name: 'en', isDefault: true, locales: ['en'], defaultLocale: 'en', urlPrefix: '' ,\n * path: '/fr', name: 'fr', isDefault: false, locales: ['fr'], defaultLocale: 'en', urlPrefix: '/fr' ,\n * path: '/es', name: 'es', isDefault: false, locales: ['es'], defaultLocale: 'en', urlPrefix: '/es' ,\n * ]\n * ```\n *\n * @param mapper - The mapper function that returns an array of objects\n * @returns An array of objects\n */\nexport const localeFlatMap = <T>(\n mapper: (locale: LocaleData) => T[],\n locales: LocalesValues[] = internationalization.locales ?? [],\n defaultLocale: LocalesValues = internationalization.defaultLocale ??\n DEFAULT_LOCALE,\n mode:\n | 'prefix-no-default'\n | 'prefix-all'\n | 'no-prefix'\n | 'search-params' = routing?.mode ?? 'prefix-no-default'\n): T[] =>\n locales.flatMap((locale) =>\n mapper({\n locale,\n defaultLocale,\n locales,\n isDefault: locale === defaultLocale,\n urlPrefix: getPrefix(locale, { defaultLocale, mode, locales })\n .localePrefix\n ? `/${locale}`\n : '',\n } as LocaleData)\n );\n\n/**\n * Creates a record object mapping locales to values transformed by the mapper function\n *\n * @example\n * ```ts\n * const translations = localeRecord(({ locale }) =>\n * require(`./translations/${locale}.json`)\n * );\n *\n * // Result\n *\n * en: ... , // Content of translations/en.json\n * fr: ... , // Content of translations/fr.json\n * es: ...\n *\n * ```\n *\n * @param mapper - Function that takes locale data and returns a value for that locale\n * @param locales - Array of locale codes to map over (defaults to configured locales)\n * @param defaultLocale - The default locale (defaults to configured default)\n * @param mode - URL routing mode for locale handling (defaults to configured value)\n * @returns Record mapping locale codes to mapped values\n */\nexport const localeRecord = <T>(\n mapper: (locale: LocaleData) => T,\n locales: LocalesValues[] = internationalization.locales ?? [],\n defaultLocale: LocalesValues = internationalization.defaultLocale ??\n DEFAULT_LOCALE,\n mode:\n | 'prefix-no-default'\n | 'prefix-all'\n | 'no-prefix'\n | 'search-params' = routing?.mode ?? 'prefix-no-default'\n): Record<LocalesValues, T> =>\n (locales ?? []).reduce(\n (acc, locale) => {\n acc[locale] = mapper({\n locale,\n defaultLocale,\n locales,\n isDefault: locale === defaultLocale,\n urlPrefix: getPrefix(locale, { defaultLocale, mode, locales })\n .localePrefix\n ? `/${locale}`\n : '',\n } as LocaleData);\n return acc;\n },\n {} as Record<LocalesValues, T>\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,aACX,QACA,UAA2BA,4CAAqB,WAAW,EAAE,EAC7D,gBAA+BA,4CAAqB,iBAClDC,+CACF,OAIsBC,gCAAS,QAAQ,yBAEtC,WAAW,EAAE,EAAE,KAAK,WACnB,OAAO;CACL;CACA;CACA;CACA,WAAW,WAAW;CACtB,WAAWC,yCAAU,QAAQ;EAAE;EAAe;EAAM;EAAS,CAAC,CAC3D,eACC,IAAI,WACJ;CACL,CAAe,CACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BH,MAAa,iBACX,QACA,UAA2BH,4CAAqB,WAAW,EAAE,EAC7D,gBAA+BA,4CAAqB,iBAClDC,+CACF,OAIsBC,gCAAS,QAAQ,wBAEvC,QAAQ,SAAS,WACf,OAAO;CACL;CACA;CACA;CACA,WAAW,WAAW;CACtB,WAAWC,yCAAU,QAAQ;EAAE;EAAe;EAAM;EAAS,CAAC,CAC3D,eACC,IAAI,WACJ;CACL,CAAe,CACjB;;;;;;;;;;;;;;;;;;;;;;;;AAyBH,MAAa,gBACX,QACA,UAA2BH,4CAAqB,WAAW,EAAE,EAC7D,gBAA+BA,4CAAqB,iBAClDC,+CACF,OAIsBC,gCAAS,QAAQ,yBAEtC,WAAW,EAAE,EAAE,QACb,KAAK,WAAW;AACf,KAAI,UAAU,OAAO;EACnB;EACA;EACA;EACA,WAAW,WAAW;EACtB,WAAWC,yCAAU,QAAQ;GAAE;GAAe;GAAM;GAAS,CAAC,CAC3D,eACC,IAAI,WACJ;EACL,CAAe;AAChB,QAAO;GAET,EAAE,CACH"}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
4
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
5
4
|
|
|
6
5
|
//#region src/localization/localeResolver.ts
|
|
7
6
|
/**
|
|
8
7
|
* Resolves the most specific locale from a user-provided list,
|
|
9
8
|
* or falls back to the default locale if no match is found.
|
|
10
9
|
*/
|
|
11
|
-
const localeResolver = (selectedLocale, locales = _intlayer_config_built.
|
|
10
|
+
const localeResolver = (selectedLocale, locales = _intlayer_config_built.internationalization?.locales, defaultLocale = _intlayer_config_built.internationalization?.defaultLocale) => {
|
|
12
11
|
const requestedLocales = [selectedLocale].flat();
|
|
13
12
|
const normalize = (locale) => locale.trim().toLowerCase();
|
|
14
13
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localeResolver.cjs","names":["
|
|
1
|
+
{"version":3,"file":"localeResolver.cjs","names":["internationalization"],"sources":["../../../src/localization/localeResolver.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\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[] = internationalization?.locales,\n defaultLocale: LocalesValues = internationalization?.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 // Attempt exact match\n const exactMatch = locales.find(\n (locale) => normalize(locale) === normalizedRequested\n );\n if (exactMatch) {\n return exactMatch as Locale;\n }\n\n // 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 (locale) => normalize(locale).split('-')[0] === requestedLang\n );\n if (partialMatch) {\n return partialMatch as Locale;\n }\n }\n } catch {\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":";;;;;;;;;AAQA,MAAa,kBACX,gBACA,UAA2BA,6CAAsB,SACjD,gBAA+BA,6CAAsB,kBAC1C;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,WAAW,UAAU,OAAO,KAAK,oBACnC;AACD,OAAI,WACF,QAAO;GAMT,MAAM,CAAC,iBAAiB,oBAAoB,MAAM,IAAI;GACtD,MAAM,eAAe,QAAQ,MAC1B,WAAW,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,cACjD;AACD,OAAI,aACF,QAAO;;SAGL;AAKR,QAAO"}
|
package/dist/cjs/utils/intl.cjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
4
|
-
_intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
|
|
5
4
|
|
|
6
5
|
//#region src/utils/intl.ts
|
|
7
6
|
/**
|
|
@@ -35,7 +34,7 @@ const cache = /* @__PURE__ */ new Map();
|
|
|
35
34
|
* Generic caching instantiator for Intl constructors.
|
|
36
35
|
*/
|
|
37
36
|
const getCachedIntl = (Ctor, locale, options) => {
|
|
38
|
-
const resLoc = locale ?? _intlayer_config_built.
|
|
37
|
+
const resLoc = locale ?? _intlayer_config_built.internationalization?.defaultLocale;
|
|
39
38
|
const key = `${resLoc}|${options ? JSON.stringify(options) : ""}`;
|
|
40
39
|
let ctorCache = cache.get(Ctor);
|
|
41
40
|
if (!ctorCache) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intl.cjs","names":["
|
|
1
|
+
{"version":3,"file":"intl.cjs","names":["internationalization"],"sources":["../../../src/utils/intl.ts"],"sourcesContent":["/**\n * Cached Intl helper – drop‑in replacement for the global `Intl` object.\n * ‑‑‑\n * • Uses a `Proxy` to lazily wrap every *constructor* hanging off `Intl` (NumberFormat, DateTimeFormat, …).\n * • Each wrapped constructor keeps an in‑memory cache keyed by `[locales, options]` so that identical requests\n * reuse the same heavy instance instead of reparsing CLDR data every time.\n * • A polyfill warning for `Intl.DisplayNames` is emitted only once and only in dev.\n * • The public API is fully type‑safe and mirrors the native `Intl` surface exactly –\n * you can treat `CachedIntl` just like the built‑in `Intl`.\n *\n * Usage @example:\n * ---------------\n * ```ts\n * import { CachedIntl } from \"./cached-intl\";\n *\n * const nf = CachedIntl.NumberFormat(\"en-US\", { style: \"currency\", currency: \"USD\" });\n * console.log(nf.format(1234));\n *\n * const dn = CachedIntl.DisplayNames([\"fr\"], { type: \"language\" });\n * console.log(dn.of(\"en\")); * → \"anglais\"\n *\n * You can also spin up an isolated instance with its own caches (handy in test suites):\n * const TestIntl = createCachedIntl();\n * ```\n */\n\nimport { internationalization } from '@intlayer/config/built';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\nconst MAX_CACHE_SIZE = 50;\nconst cache = new Map<any, Map<string, any>>();\n\ntype IntlConstructors = {\n [K in keyof typeof Intl as (typeof Intl)[K] extends new (\n ...args: any\n ) => any\n ? K\n : never]: (typeof Intl)[K];\n};\n\ntype ReplaceLocaleWithLocalesValues<T> = T extends new (\n locales: any,\n options?: infer Options\n) => infer Instance\n ? {\n new (locales?: LocalesValues, options?: Options): Instance;\n new (options?: Options & { locale?: LocalesValues }): Instance;\n (locales?: LocalesValues, options?: Options): Instance;\n (options?: Options & { locale?: LocalesValues }): Instance;\n }\n : T extends new (\n locales: any\n ) => infer Instance\n ? {\n new (locales?: LocalesValues): Instance;\n new (options?: { locale?: LocalesValues }): Instance;\n (locales?: LocalesValues): Instance;\n (options?: { locale?: LocalesValues }): Instance;\n }\n : T;\n\nexport type WrappedIntl = {\n [K in keyof typeof Intl]: K extends keyof IntlConstructors\n ? ReplaceLocaleWithLocalesValues<(typeof Intl)[K]>\n : (typeof Intl)[K];\n};\n\n/**\n * Generic caching instantiator for Intl constructors.\n */\nexport const getCachedIntl = <T extends new (...args: any[]) => any>(\n Ctor: T,\n locale?: LocalesValues | string,\n options?: any\n): InstanceType<T> => {\n const resLoc = locale ?? internationalization?.defaultLocale;\n\n const optKey = options ? JSON.stringify(options) : '';\n const key = `${resLoc}|${optKey}`;\n\n let ctorCache = cache.get(Ctor);\n\n if (!ctorCache) {\n ctorCache = new Map();\n cache.set(Ctor, ctorCache);\n }\n\n let instance = ctorCache.get(key);\n\n if (!instance) {\n if (ctorCache.size > MAX_CACHE_SIZE) ctorCache.clear();\n instance = new Ctor(resLoc, options);\n ctorCache.set(key, instance);\n }\n return instance;\n};\n\n/**\n * Optional: Keep bindIntl if your library exports it publicly.\n * It now uses the much smaller getCachedIntl under the hood.\n */\nexport const bindIntl = (boundLocale: LocalesValues): WrappedIntl => {\n const bindWrap = (Ctor: any) =>\n // function is used as a constructor, do not change in arrow function\n function intlConstructor(locales?: any, options?: any) {\n const isOptsFirst =\n locales !== null &&\n typeof locales === 'object' &&\n !Array.isArray(locales);\n const resOpts = isOptsFirst ? locales : options;\n const resLoc = isOptsFirst\n ? (resOpts as any).locale || boundLocale\n : locales || boundLocale;\n\n return getCachedIntl(Ctor, resLoc, resOpts);\n };\n\n return {\n ...Intl,\n Collator: bindWrap(Intl.Collator),\n DateTimeFormat: bindWrap(Intl.DateTimeFormat),\n DisplayNames: bindWrap(Intl.DisplayNames),\n ListFormat: bindWrap(Intl.ListFormat),\n NumberFormat: bindWrap(Intl.NumberFormat),\n PluralRules: bindWrap(Intl.PluralRules),\n RelativeTimeFormat: bindWrap(Intl.RelativeTimeFormat),\n Locale: bindWrap(Intl.Locale),\n Segmenter: bindWrap((Intl as any).Segmenter),\n } as unknown as WrappedIntl;\n};\n\n// Add this to the bottom of utils/intl.ts ONLY if required for public API compatibility.\nexport const CachedIntl = {\n // function is used as a constructor, do not change in arrow function\n Collator: function Collator(locales?: any, options?: any) {\n return getCachedIntl(Intl.Collator, locales, options);\n },\n DateTimeFormat: function DateTimeFormat(locales?: any, options?: any) {\n return getCachedIntl(Intl.DateTimeFormat, locales, options);\n },\n DisplayNames: function DisplayNames(locales?: any, options?: any) {\n return getCachedIntl(Intl.DisplayNames, locales, options);\n },\n ListFormat: function ListFormat(locales?: any, options?: any) {\n return getCachedIntl(Intl.ListFormat as any, locales, options);\n },\n NumberFormat: function NumberFormat(locales?: any, options?: any) {\n return getCachedIntl(Intl.NumberFormat, locales, options);\n },\n PluralRules: function PluralRules(locales?: any, options?: any) {\n return getCachedIntl(Intl.PluralRules, locales, options);\n },\n RelativeTimeFormat: function RelativeTimeFormat(\n locales?: any,\n options?: any\n ) {\n return getCachedIntl(Intl.RelativeTimeFormat, locales, options);\n },\n Segmenter: function Segmenter(locales?: any, options?: any) {\n return getCachedIntl((Intl as any).Segmenter, locales, options);\n },\n} as any; // Cast to 'any' internally to avoid TS readonly errors\n\nexport { CachedIntl as Intl };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,iBAAiB;AACvB,MAAM,wBAAQ,IAAI,KAA4B;;;;AAwC9C,MAAa,iBACX,MACA,QACA,YACoB;CACpB,MAAM,SAAS,UAAUA,6CAAsB;CAG/C,MAAM,MAAM,GAAG,OAAO,GADP,UAAU,KAAK,UAAU,QAAQ,GAAG;CAGnD,IAAI,YAAY,MAAM,IAAI,KAAK;AAE/B,KAAI,CAAC,WAAW;AACd,8BAAY,IAAI,KAAK;AACrB,QAAM,IAAI,MAAM,UAAU;;CAG5B,IAAI,WAAW,UAAU,IAAI,IAAI;AAEjC,KAAI,CAAC,UAAU;AACb,MAAI,UAAU,OAAO,eAAgB,WAAU,OAAO;AACtD,aAAW,IAAI,KAAK,QAAQ,QAAQ;AACpC,YAAU,IAAI,KAAK,SAAS;;AAE9B,QAAO;;;;;;AAOT,MAAa,YAAY,gBAA4C;CACnE,MAAM,YAAY,SAEhB,SAAS,gBAAgB,SAAe,SAAe;EACrD,MAAM,cACJ,YAAY,QACZ,OAAO,YAAY,YACnB,CAAC,MAAM,QAAQ,QAAQ;EACzB,MAAM,UAAU,cAAc,UAAU;AAKxC,SAAO,cAAc,MAJN,cACV,QAAgB,UAAU,cAC3B,WAAW,aAEoB,QAAQ;;AAG/C,QAAO;EACL,GAAG;EACH,UAAU,SAAS,KAAK,SAAS;EACjC,gBAAgB,SAAS,KAAK,eAAe;EAC7C,cAAc,SAAS,KAAK,aAAa;EACzC,YAAY,SAAS,KAAK,WAAW;EACrC,cAAc,SAAS,KAAK,aAAa;EACzC,aAAa,SAAS,KAAK,YAAY;EACvC,oBAAoB,SAAS,KAAK,mBAAmB;EACrD,QAAQ,SAAS,KAAK,OAAO;EAC7B,WAAW,SAAU,KAAa,UAAU;EAC7C;;AAIH,MAAa,aAAa;CAExB,UAAU,SAAS,SAAS,SAAe,SAAe;AACxD,SAAO,cAAc,KAAK,UAAU,SAAS,QAAQ;;CAEvD,gBAAgB,SAAS,eAAe,SAAe,SAAe;AACpE,SAAO,cAAc,KAAK,gBAAgB,SAAS,QAAQ;;CAE7D,cAAc,SAAS,aAAa,SAAe,SAAe;AAChE,SAAO,cAAc,KAAK,cAAc,SAAS,QAAQ;;CAE3D,YAAY,SAAS,WAAW,SAAe,SAAe;AAC5D,SAAO,cAAc,KAAK,YAAmB,SAAS,QAAQ;;CAEhE,cAAc,SAAS,aAAa,SAAe,SAAe;AAChE,SAAO,cAAc,KAAK,cAAc,SAAS,QAAQ;;CAE3D,aAAa,SAAS,YAAY,SAAe,SAAe;AAC9D,SAAO,cAAc,KAAK,aAAa,SAAS,QAAQ;;CAE1D,oBAAoB,SAAS,mBAC3B,SACA,SACA;AACA,SAAO,cAAc,KAAK,oBAAoB,SAAS,QAAQ;;CAEjE,WAAW,SAAS,UAAU,SAAe,SAAe;AAC1D,SAAO,cAAe,KAAa,WAAW,SAAS,QAAQ;;CAElE"}
|