@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
43 lines (41 loc) • 2.04 kB
JavaScript
import { checkIsURLAbsolute } from "../utils/checkIsURLAbsolute.mjs";
import { DefaultValues } from "@intlayer/config/client";
import configuration from "@intlayer/config/built";
//#region src/localization/getLocaleFromPath.ts
/**
* Extracts the locale segment from the given URL or pathname based on the routing mode.
*
* Mode Behaviors:
* - 'prefix-no-default': Checks path prefiIf no prefix found, assumes default locale.
* - 'prefix-all': Checks path prefix.
* - 'search-params': Checks for 'locale' query parameter.
* - 'no-prefix': Returns undefined (or default if fallback is true).
*
* @param inputUrl - The complete URL string or pathname to process.
* @returns The detected locale, default locale (if fallback/implicit), or undefined.
*/
const getLocaleFromPath = (inputUrl = "/", options) => {
const { defaultLocale, locales, mode } = {
defaultLocale: configuration?.internationalization?.defaultLocale ?? DefaultValues.Internationalization.DEFAULT_LOCALE,
mode: configuration?.routing?.mode ?? DefaultValues.Routing.ROUTING_MODE,
locales: configuration?.internationalization?.locales ?? DefaultValues.Internationalization.LOCALES,
...options
};
if (!defaultLocale || !locales) return DefaultValues.Internationalization.DEFAULT_LOCALE;
const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);
let fixedInputUrl = inputUrl;
if (inputUrl?.endsWith("/") && inputUrl.length > 1) fixedInputUrl = inputUrl.slice(0, -1);
const url = isAbsoluteUrl ? new URL(fixedInputUrl) : new URL(fixedInputUrl, "http://example.com");
if (mode === "search-params") {
const localeParam = url.searchParams.get("locale");
if (localeParam && locales.includes(localeParam)) return localeParam;
return defaultLocale;
}
if (mode === "no-prefix") return defaultLocale;
const firstSegment = url.pathname.split("/")[1];
if (firstSegment && locales.includes(firstSegment)) return firstSegment;
if (mode === "prefix-no-default") return defaultLocale;
};
//#endregion
export { getLocaleFromPath };
//# sourceMappingURL=getLocaleFromPath.mjs.map