UNPKG

@intlayer/core

Version:

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

42 lines (40 loc) 1.96 kB
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs'); const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs'); let __intlayer_types = require("@intlayer/types"); let __intlayer_config_built = require("@intlayer/config/built"); __intlayer_config_built = require_rolldown_runtime.__toESM(__intlayer_config_built); //#region src/localization/getLocaleFromPath.ts /** * Extracts the locale segment from the given URL or pathname if present. * If no locale is present, returns the default locale (en). * * Example: * * ```ts * getLocaleFromPath('/en/dashboard') // Returns 'en' * getLocaleFromPath('/fr/dashboard') // Returns 'fr' * getLocaleFromPath('/dashboard') // Returns 'en' * getLocaleFromPath('dashboard') // Returns 'en' * getLocaleFromPath('https://example.com/es/dashboard') // Returns 'es' * getLocaleFromPath('https://example.com/fr/dashboard') // Returns 'fr' * getLocaleFromPath('https://example.com/dashboard') // Returns 'en' * ``` * * @param inputUrl - The complete URL string or pathname to process. * @returns The detected locale or default (en) if no locale is found */ const getLocaleFromPath = (inputUrl) => { const { defaultLocale, locales } = __intlayer_config_built.default?.internationalization ?? {}; if (!defaultLocale || !locales) return __intlayer_types.Locales.ENGLISH; const isAbsoluteUrl = require_utils_checkIsURLAbsolute.checkIsURLAbsolute(inputUrl); let fixedInputUrl = inputUrl; if (inputUrl.endsWith("/")) fixedInputUrl = inputUrl.slice(0, -1); const pathname = (isAbsoluteUrl ? new URL(fixedInputUrl) : new URL(fixedInputUrl, "http://example.com")).pathname; if (!pathname.startsWith("/")) return defaultLocale; const firstSegment = pathname.split("/")[1]; if (firstSegment && locales.includes(firstSegment)) return firstSegment; return defaultLocale; }; //#endregion exports.getLocaleFromPath = getLocaleFromPath; //# sourceMappingURL=getLocaleFromPath.cjs.map