next-intlayer 8.4.1 → 8.4.3

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.
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./localeDetector.cjs`);let n=require(`@intlayer/core/localization`),r=require(`@intlayer/config/built`);r=e.__toESM(r);let i=require(`@intlayer/config/client`),a=require(`@intlayer/core/utils`),o=require(`next/server`);const{internationalization:s,routing:c}=r.default??{},{locales:l,defaultLocale:u}=s??{},{basePath:d,mode:f,rewrite:p}=c??{},m=f??i.DefaultValues.Routing.ROUTING_MODE,h=m===`no-prefix`||m===`search-params`,g=m===`prefix-all`,_=!h,v=(0,n.getRewriteRules)(p,`url`),y=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},b=(e,t)=>{if(m!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},x=(e,t,n)=>{let r=e.nextUrl.pathname,i=S(e);return h?C(e,i,r):T(e,i,w(r),r)},S=e=>(0,a.getLocaleFromStorage)({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),C=(e,r,i)=>{let a=w(i);if(a){let t=(0,n.getCanonicalPath)(i.slice(`/${a}`.length)||`/`,a,v),r=b(e.nextUrl.search,a);return j(e,r?`${t}${r}`:`${t}${e.nextUrl.search??``}`)}if(m===`search-params`){let a=new URLSearchParams(e.nextUrl.search).get(`locale`),o=l?.includes(a),s=r??(o?a:void 0)??r??t.localeDetector?.(e)??u;l?.includes(s)||(s=u);let c=(0,n.getCanonicalPath)(i,s,v);if(a===s)return A(e,`${_?`/${s}${c}`:c}${e.nextUrl.search??``}`,s);let d=b(e.nextUrl.search,s);return j(e,d?`${i}${d}`:`${i}${e.nextUrl.search??``}`)}let o=r??t.localeDetector?.(e)??u;l?.includes(o)||(o=u);let s=(0,n.getCanonicalPath)(i,o,v),c=_?`/${o}${s}`:s,d=b(e.nextUrl.search,o);return A(e,d?`${c}${d}`:`${c}${e.nextUrl.search??``}`,o)},w=e=>l.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),T=(e,t,n,r)=>n?D(e,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,r,i)=>{let a=r??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,n.getCanonicalPath)(i,a,v),s=(0,n.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=k(a,c,d,b(e.nextUrl.search,a));return g||a!==u?j(e,f):A(e,_?`/${a}${o}`:o,a)},D=(e,t,r)=>{let i=r.slice(`/${t}`.length)||`/`,a=(0,n.getCanonicalPath)(i,t,v),o=(0,n.getLocalizedPath)(a,t,v),s=typeof o==`string`?o:o.path;if(typeof o!=`string`&&o.isRewritten&&s!==i)return j(e,k(t,s,d,b(e.nextUrl.search,t)));let c=_?`/${t}${a}`:a;if(!g&&t===u)return O(e,t,r);let l=e.nextUrl.search;return A(e,c+(l??``),t)},O=(e,t,r)=>{if(!g&&t===u){let i=(0,n.getLocalizedPath)(r,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),j(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${r}`:r;return A(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},k=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(m===`no-prefix`||m===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},A=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t,s=new Headers(e.headers);(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{s.set(e,t)}});let c=new URL(i,e.url),l=c.href===e.nextUrl.href?o.NextResponse.next({request:{headers:s}}):o.NextResponse.rewrite(c,{request:{headers:s}});return(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},j=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return o.NextResponse.redirect(new URL(r,e.url))};exports.intlayerProxy=x;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./localeDetector.cjs`);let n=require(`@intlayer/core/localization`),r=require(`@intlayer/config/built`);r=e.__toESM(r);let i=require(`@intlayer/config/defaultValues`),a=require(`@intlayer/core/utils`),o=require(`next/server`);const{internationalization:s,routing:c}=r.default??{},{locales:l,defaultLocale:u}=s??{},{basePath:d,mode:f,rewrite:p}=c??{},m=f??i.ROUTING_MODE,h=m===`no-prefix`||m===`search-params`,g=m===`prefix-all`,_=!h,v=(0,n.getRewriteRules)(p,`url`),y=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},b=(e,t)=>{if(m!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},x=(e,t,n)=>{let r=e.nextUrl.pathname,i=S(e);return h?C(e,i,r):T(e,i,w(r),r)},S=e=>(0,a.getLocaleFromStorage)({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),C=(e,r,i)=>{let a=w(i);if(a){let t=(0,n.getCanonicalPath)(i.slice(`/${a}`.length)||`/`,a,v),r=b(e.nextUrl.search,a);return j(e,r?`${t}${r}`:`${t}${e.nextUrl.search??``}`)}if(m===`search-params`){let a=new URLSearchParams(e.nextUrl.search).get(`locale`),o=l?.includes(a),s=r??(o?a:void 0)??r??t.localeDetector?.(e)??u;l?.includes(s)||(s=u);let c=(0,n.getCanonicalPath)(i,s,v);if(a===s)return A(e,`${_?`/${s}${c}`:c}${e.nextUrl.search??``}`,s);let d=b(e.nextUrl.search,s);return j(e,d?`${i}${d}`:`${i}${e.nextUrl.search??``}`)}let o=r??t.localeDetector?.(e)??u;l?.includes(o)||(o=u);let s=(0,n.getCanonicalPath)(i,o,v),c=_?`/${o}${s}`:s,d=b(e.nextUrl.search,o);return A(e,d?`${c}${d}`:`${c}${e.nextUrl.search??``}`,o)},w=e=>l.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),T=(e,t,n,r)=>n?D(e,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,r,i)=>{let a=r??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,n.getCanonicalPath)(i,a,v),s=(0,n.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=k(a,c,d,b(e.nextUrl.search,a));return g||a!==u?j(e,f):A(e,_?`/${a}${o}`:o,a)},D=(e,t,r)=>{let i=r.slice(`/${t}`.length)||`/`,a=(0,n.getCanonicalPath)(i,t,v),o=(0,n.getLocalizedPath)(a,t,v),s=typeof o==`string`?o:o.path;if(typeof o!=`string`&&o.isRewritten&&s!==i)return j(e,k(t,s,d,b(e.nextUrl.search,t)));let c=_?`/${t}${a}`:a;if(!g&&t===u)return O(e,t,r);let l=e.nextUrl.search;return A(e,c+(l??``),t)},O=(e,t,r)=>{if(!g&&t===u){let i=(0,n.getLocalizedPath)(r,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),j(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${r}`:r;return A(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},k=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(m===`no-prefix`||m===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},A=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t,s=new Headers(e.headers);(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{s.set(e,t)}});let c=new URL(i,e.url),l=c.href===e.nextUrl.href?o.NextResponse.next({request:{headers:s}}):o.NextResponse.rewrite(c,{request:{headers:s}});return(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},j=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return o.NextResponse.redirect(new URL(r,e.url))};exports.intlayerProxy=x;
2
2
  //# sourceMappingURL=intlayerProxy.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.cjs","names":["configuration","DefaultValues","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests can be identified by several headers:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js router prefetch)\n * - next-url: present (Next.js internal navigation)\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n const nextUrl = request.headers.get('next-url');\n const xNextjsData = request.headers.get('x-nextjs-data');\n\n return (\n purpose === 'prefetch' ||\n nextRouterPrefetch === '1' ||\n !!nextUrl ||\n !!xNextjsData\n );\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @returns - The redirect response.\n */\nconst redirectUrl = (request: NextRequest, newPath: string): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"8VA+CA,KAAM,CAAE,uBAAsB,WAAYA,EAAAA,SAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQC,EAAAA,cAAc,QAAQ,aAC9C,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,GAAA,EAAA,EAAA,iBAA+B,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OACE,IAAY,YACZ,IAAuB,KACvB,CAAC,CAAC,GACF,CAAC,CAAC,GAKA,GACJ,EACA,IACuB,CACvB,GAAI,IAAkB,gBAAiB,OAAO,EAC9C,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAEhD,OADA,EAAO,IAAI,SAAU,EAAO,CACrB,IAAI,EAAO,UAAU,IA0BjB,GACX,EACA,EACA,IACiB,CACjB,IAAM,EAAW,EAAQ,QAAQ,SAE3B,EAAc,EAAe,EAAQ,CAO3C,OALI,EACK,EAAe,EAAS,EAAa,EAAS,CAIhD,EAA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D,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,EACnD,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/BC,EAAAA,aAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACFA,EAAAA,aAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
1
+ {"version":3,"file":"intlayerProxy.cjs","names":["configuration","ROUTING_MODE","localeDetector","NextResponse"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests can be identified by several headers:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js router prefetch)\n * - next-url: present (Next.js internal navigation)\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n const nextUrl = request.headers.get('next-url');\n const xNextjsData = request.headers.get('x-nextjs-data');\n\n return (\n purpose === 'prefetch' ||\n nextRouterPrefetch === '1' ||\n !!nextUrl ||\n !!xNextjsData\n );\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @returns - The redirect response.\n */\nconst redirectUrl = (request: NextRequest, newPath: string): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"qWA+CA,KAAM,CAAE,uBAAsB,WAAYA,EAAAA,SAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQC,EAAAA,aACxB,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,GAAA,EAAA,EAAA,iBAA+B,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OACE,IAAY,YACZ,IAAuB,KACvB,CAAC,CAAC,GACF,CAAC,CAAC,GAKA,GACJ,EACA,IACuB,CACvB,GAAI,IAAkB,gBAAiB,OAAO,EAC9C,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAEhD,OADA,EAAO,IAAI,SAAU,EAAO,CACrB,IAAI,EAAO,UAAU,IA0BjB,GACX,EACA,EACA,IACiB,CACjB,IAAM,EAAW,EAAQ,QAAQ,SAE3B,EAAc,EAAe,EAAQ,CAO3C,OALI,EACK,EAAe,EAAS,EAAa,EAAS,CAIhD,EAA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D,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,EACnD,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/BC,EAAAA,aAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACFA,EAAAA,aAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/core/localization`),n=require(`@intlayer/config/built`);n=e.__toESM(n);let r=require(`@intlayer/config/client`),i=require(`@intlayer/core/utils`),a=require(`next/headers.js`);const o=async()=>{let e=n.default?.internationalization?.defaultLocale??r.DefaultValues.Internationalization.DEFAULT_LOCALE,o=await(0,a.headers)(),s=await(0,a.cookies)(),c=(0,i.getLocaleFromStorage)({getCookie:e=>s.get(e)?.value??null,getHeader:e=>o.get(e)??null});if(c)return c;let l={};return o.forEach((e,t)=>{l[t]=e}),(0,t.localeDetector)(l)||e};exports.getLocale=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/core/localization`),n=require(`@intlayer/config/built`);n=e.__toESM(n);let r=require(`@intlayer/config/defaultValues`),i=require(`@intlayer/core/utils`),a=require(`next/headers.js`);const o=async()=>{let e=n.default?.internationalization?.defaultLocale??r.DEFAULT_LOCALE,o=await(0,a.headers)(),s=await(0,a.cookies)(),c=(0,i.getLocaleFromStorage)({getCookie:e=>s.get(e)?.value??null,getHeader:e=>o.get(e)??null});if(c)return c;let l={};return o.forEach((e,t)=>{l[t]=e}),(0,t.localeDetector)(l)||e};exports.getLocale=o;
2
2
  //# sourceMappingURL=getLocale.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.cjs","names":["configuration","DefaultValues"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"gUA0BA,MAAa,EAAY,SAA6B,CACpD,IAAM,EACJA,EAAAA,SAAe,sBAAsB,eACrCC,EAAAA,cAAc,qBAAqB,eAG/B,EAAc,MAAA,EAAA,EAAA,UAAe,CAC7B,EAAc,MAAA,EAAA,EAAA,UAAe,CAE7B,GAAA,EAAA,EAAA,sBAAoC,CACxC,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAE,OAAS,KAC7D,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAI,KACvD,CAAC,CAEF,GAAI,EAAc,OAAO,EAGzB,IAAM,EAA4C,EAAE,CASpD,OARA,EAAY,SAAS,EAAO,IAAQ,CAClC,EAAkB,GAAO,GACzB,EAEI,EAAA,EAAA,gBAAoC,EAAkB,EAIrD"}
1
+ {"version":3,"file":"getLocale.cjs","names":["configuration","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"uUA0BA,MAAa,EAAY,SAA6B,CACpD,IAAM,EACJA,EAAAA,SAAe,sBAAsB,eAAiBC,EAAAA,eAGlD,EAAc,MAAA,EAAA,EAAA,UAAe,CAC7B,EAAc,MAAA,EAAA,EAAA,UAAe,CAE7B,GAAA,EAAA,EAAA,sBAAoC,CACxC,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAE,OAAS,KAC7D,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAI,KACvD,CAAC,CAEF,GAAI,EAAc,OAAO,EAGzB,IAAM,EAA4C,EAAE,CASpD,OARA,EAAY,SAAS,EAAO,IAAQ,CAClC,EAAkB,GAAO,GACzB,EAEI,EAAA,EAAA,gBAAoC,EAAkB,EAIrD"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/config/client`),n=require(`node:path`),r=require(`@intlayer/chokidar/build`),i=require(`@intlayer/chokidar/cli`),a=require(`@intlayer/chokidar/utils`),o=require(`@intlayer/config/logger`),s=require(`@intlayer/config/node`),c=require(`@intlayer/config/utils`),l=require(`@intlayer/dictionaries-entry`),u=require(`@intlayer/webpack`),d=require(`defu`),f=require(`next/package.json`);f=e.__toESM(f);const p=(0,c.compareVersions)(f.default.version,`≥`,`13.0.0`),m=(0,c.compareVersions)(f.default.version,`≥`,`15.0.0`),h=(0,c.compareVersions)(f.default.version,`≥`,`16.0.0`),g=(0,c.compareVersions)(f.default.version,`≥`,`15.3.0`),_=h?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),v=e=>{try{return(e.build?.require??(0,c.getProjectRequire)()).resolve(`@intlayer/swc`),!0}catch{return!1}},y=e=>{try{return(e.build?.require??(0,c.getProjectRequire)()).resolve(`@intlayer/babel`),!0}catch{return!1}},b=(e,t,r)=>{let i=(t.build?.require??(0,c.getProjectRequire)())?.resolve(e);return r?(0,c.normalizePath)(`./${(0,n.relative)(process.cwd(),i)}`):i},x=(e,r,i,s)=>{let{optimize:c}=e.build,u=e.build.importMode??e.dictionary?.importMode,{dictionariesDir:d,unmergedDictionariesDir:f,dynamicDictionariesDir:m,fetchDictionariesDir:h,mainDir:g}=e.system,{baseDir:_}=e.system,x=(0,o.getAppLogger)(e);if(c===!1||c===void 0&&!r||!p)return{};let S=v(e);if((0,a.runOnce)((0,n.join)(_,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[(0,o.colorize)(`Recommended: Install`,o.ANSIColors.GREY),(0,o.colorize)(`@intlayer/swc`,o.ANSIColors.GREY_LIGHT),(0,o.colorize)(`package to enable build optimization. See documentation: `,o.ANSIColors.GREY),(0,o.colorize)(`https://intlayer.org/docs/bundle-optimization`,o.ANSIColors.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),(0,a.runOnce)((0,n.join)(_,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(y(e)){let t=e.compiler?.enabled??!0;t===`build-only`&&(t=!s),x(t?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!S)return{};let C=(0,n.join)(g,`dictionaries.mjs`),w=(0,n.join)(g,`dynamic_dictionaries.mjs`),T=(0,n.join)(g,`unmerged_dictionaries.mjs`),E=(0,n.join)(g,`fetch_dictionaries.mjs`),D=[...(0,a.buildComponentFilesList)(e),C,T],O=(0,l.getDictionaries)(e),k={};return Object.values(O).forEach(e=>{k[e.key]=e.importMode??u??t.DefaultValues.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[b(`@intlayer/swc`,e,i),{dictionariesDir:d,dictionariesEntryPath:C,unmergedDictionariesEntryPath:T,unmergedDictionariesDir:f,dynamicDictionariesDir:m,dynamicDictionariesEntryPath:w,fetchDictionariesDir:h,fetchDictionariesEntryPath:E,importMode:u,filesList:D,replaceDictionaryEntry:!0,dictionaryModeMap:k}]]}}},S=()=>{let e=process.env.npm_lifecycle_event,t=process.env.npm_lifecycle_script??``;return{isDevCommand:e===`dev`||process.argv.some(e=>e===`dev`)||/(^|\s)(next\s+)?dev(\s|$)/.test(t),isBuildCommand:e===`build`||process.argv.some(e=>e===`build`)||/(^|\s)(next\s+)?build(\s|$)/.test(t),isStartCommand:e===`start`||process.argv.some(e=>e===`start`)||/(^|\s)(next\s+)?start(\s|$)/.test(t)}},C=(e={},t)=>{typeof e!=`object`&&(e={});let r=(0,s.getConfiguration)(t);(0,i.logConfigDetails)(t);let a=(0,o.getAppLogger)(r),l=t?.enableTurbopack??_;l&&e.webpack!==void 0&&a(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:f,isDevCommand:h}=S(),v={resolveAlias:(0,c.getAlias)({configuration:r,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},y=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],b=()=>{let t={};return m&&(t={...t,serverExternalPackages:y}),p&&!m&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:y}}),t=l?m&&g?{...t,turbopack:v}:{...t,experimental:{...t?.experimental??{},turbo:v}}:{...t,webpack:(t,i)=>{let{isServer:a,nextRuntime:o}=i;return typeof e.webpack==`function`&&(t=e.webpack(t,i)),t.externals===!1&&(t.externals=[]),t.externals.push({esbuild:`esbuild`,module:`module`,fs:`fs`,chokidar:`chokidar`,fsevents:`fsevents`}),t.module.rules.push({test:/\.node$/,loader:`node-loader`}),t.resolve.alias={...t.resolve.alias,...(0,c.getAlias)({configuration:r,formatter:e=>(0,n.resolve)(e)})},h&&a&&o===`nodejs`&&t.plugins.push(new u.IntlayerPlugin(r)),t}},t},C=x(r,f,l??!1,h);return(0,d.defu)((0,d.defu)(b(),C),e)},w=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:i,isStartCommand:a}=S();process.env.INTLAYER_IS_DEV_COMMAND=i?`true`:`false`;let o=(0,s.getConfiguration)(t),{mode:c}=o.build;return!a&&(i||n||c===`auto`)&&await(0,r.prepareIntlayer)(o,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60,env:n?`prod`:`dev`}),C(await e,t)};exports.withIntlayer=w,exports.withIntlayerSync=C;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`@intlayer/config/defaultValues`),n=require(`node:path`),r=require(`@intlayer/chokidar/build`),i=require(`@intlayer/chokidar/cli`),a=require(`@intlayer/chokidar/utils`),o=require(`@intlayer/config/colors`);o=e.__toESM(o);let s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`@intlayer/config/utils`),u=require(`@intlayer/dictionaries-entry`),d=require(`@intlayer/webpack`),f=require(`defu`),p=require(`next/package.json`);p=e.__toESM(p);const m=e=>{let t=p.default.version;try{t=(e.build?.require??(0,l.getProjectRequire)())(`next/package.json`).version}catch{}return{isGteNext13:(0,l.compareVersions)(t,`≥`,`13.0.0`),isGteNext15:(0,l.compareVersions)(t,`≥`,`15.0.0`),isGteNext16:(0,l.compareVersions)(t,`≥`,`16.0.0`),isTurbopackStable:(0,l.compareVersions)(t,`≥`,`15.3.0`)}},h=e=>{try{return(e.build?.require??(0,l.getProjectRequire)()).resolve(`@intlayer/swc`),!0}catch{return!1}},g=e=>{try{return(e.build?.require??(0,l.getProjectRequire)()).resolve(`@intlayer/babel`),!0}catch{return!1}},_=(e,t,r)=>{let i=(t.build?.require??(0,l.getProjectRequire)())?.resolve(e);return r?(0,l.normalizePath)(`./${(0,n.relative)(process.cwd(),i)}`):i},v=(e,r,i,c,l)=>{let{optimize:d}=e.build,f=e.build.importMode??e.dictionary?.importMode,{dictionariesDir:p,unmergedDictionariesDir:m,dynamicDictionariesDir:v,fetchDictionariesDir:y,mainDir:b}=e.system,{baseDir:x}=e.system,S=(0,s.getAppLogger)(e);if(d===!1||d===void 0&&!r||!l)return{};let C=h(e);if((0,a.runOnce)((0,n.join)(x,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{S(C?`Build optimization enabled`:[(0,s.colorize)(`Recommended: Install`,o.GREY),(0,s.colorize)(`@intlayer/swc`,o.GREY_LIGHT),(0,s.colorize)(`package to enable build optimization. See documentation:`,o.GREY),(0,s.colorize)(`https://intlayer.org/docs/bundle-optimization`,o.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),(0,a.runOnce)((0,n.join)(x,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(g(e)){let t=e.compiler?.enabled??!0;t===`build-only`&&(t=!c),S(t?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!C)return{};let w=(0,n.join)(b,`dictionaries.mjs`),T=(0,n.join)(b,`dynamic_dictionaries.mjs`),E=(0,n.join)(b,`unmerged_dictionaries.mjs`),D=(0,n.join)(b,`fetch_dictionaries.mjs`),O=[...(0,a.buildComponentFilesList)(e),w,E],k=(0,u.getDictionaries)(e),A={};return Object.values(k).forEach(e=>{A[e.key]=e.importMode??f??t.IMPORT_MODE}),{experimental:{swcPlugins:[[_(`@intlayer/swc`,e,i),{dictionariesDir:p,dictionariesEntryPath:w,unmergedDictionariesEntryPath:E,unmergedDictionariesDir:m,dynamicDictionariesDir:v,dynamicDictionariesEntryPath:T,fetchDictionariesDir:y,fetchDictionariesEntryPath:D,importMode:f,filesList:O,replaceDictionaryEntry:!0,dictionaryModeMap:A}]]}}},y=()=>{let e=process.env.npm_lifecycle_event,t=process.env.npm_lifecycle_script??``;return{isDevCommand:e===`dev`||process.argv.some(e=>e===`dev`)||/(^|\s)(next\s+)?dev(\s|$)/.test(t),isBuildCommand:e===`build`||process.argv.some(e=>e===`build`)||/(^|\s)(next\s+)?build(\s|$)/.test(t),isStartCommand:e===`start`||process.argv.some(e=>e===`start`)||/(^|\s)(next\s+)?start(\s|$)/.test(t)}},b=(e={},t)=>{typeof e!=`object`&&(e={});let r=(0,c.getConfiguration)(t);(0,i.logConfigDetails)(t);let a=(0,s.getAppLogger)(r),{isGteNext13:o,isGteNext15:u,isGteNext16:p,isTurbopackStable:h}=m(r),g=p?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),_=t?.enableTurbopack??g;_&&e.webpack!==void 0&&a(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:b,isDevCommand:x}=y(),S={resolveAlias:(0,l.getAlias)({configuration:r,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},C=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`,`recast`,`@intlayer/chokidar`,`@intlayer/webpack`],w=()=>{let t={env:{INTLAYER_EDITOR_ENABLED:r.editor?.enabled===!1?`false`:`true`}};return u&&(t={...t,serverExternalPackages:C}),o&&!u&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:C}}),t=_?u&&h?{...t,turbopack:S}:{...t,experimental:{...t?.experimental??{},turbo:S}}:{...t,webpack:(t,i)=>{let{isServer:a,nextRuntime:o}=i;typeof e.webpack==`function`&&(t=e.webpack(t,i)),t.externals===!1&&(t.externals=[]);let s=new Set([`esbuild`,`module`,`fs`,`chokidar`,`fsevents`,`recast`]),c=[`@intlayer/chokidar`,`@intlayer/webpack`];return t.externals.push(({request:e},t)=>{if(e&&(s.has(e)||c.some(t=>e===t||e.startsWith(`${t}/`))))return t(null,`commonjs ${e}`);t(null)}),t.module.rules.push({test:/\.node$/,loader:`node-loader`}),t.resolve.alias={...t.resolve.alias,...(0,l.getAlias)({configuration:r,formatter:e=>(0,n.resolve)(e)})},x&&a&&o===`nodejs`&&t.plugins.push(new d.IntlayerPlugin(r)),t}},t},T=v(r,b,_??!1,x,o);return(0,f.defu)((0,f.defu)(w(),T),e)},x=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:i,isStartCommand:a}=y();process.env.INTLAYER_IS_DEV_COMMAND=i?`true`:`false`;let o=(0,c.getConfiguration)(t),{mode:s}=o.build;return!a&&(i||n||s===`auto`)&&await(0,r.prepareIntlayer)(o,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60,env:n?`prod`:`dev`}),b(await e,t)};exports.withIntlayer=x,exports.withIntlayerSync=b;
2
2
  //# sourceMappingURL=withIntlayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","DefaultValues","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\nconst isGteNext13 = compareVersions(nextPackageJSON.version, '≥', '13.0.0');\nconst isGteNext15 = compareVersions(nextPackageJSON.version, '≥', '15.0.0');\nconst isGteNext16 = compareVersions(nextPackageJSON.version, '≥', '16.0.0');\nconst isTurbopackStable = compareVersions(\n nextPackageJSON.version,\n '≥',\n '15.3.0'\n);\n\nconst isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enable turbopack by default, and offer the possibility to disable it if --webpack flag is used\n !process.env.npm_lifecycle_script?.includes('--webpack')\n : // Next@15 use --turbopack flag, Next@14 use --turbo flag\n process.env.npm_lifecycle_script?.includes('--turbo');\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger('Build optimization enabled');\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation: ',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ??\n importMode ??\n DefaultValues.Dictionary.IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env.npm_lifecycle_event;\n const lifecycleScript = process.env.npm_lifecycle_script ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const logger = getAppLogger(intlayerConfig);\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n logger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n ];\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {};\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark these modules as externals\n config.externals.push({\n esbuild: 'esbuild',\n module: 'module',\n fs: 'fs',\n chokidar: 'chokidar',\n fsevents: 'fsevents',\n });\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"6hBAyBA,MAAM,GAAA,EAAA,EAAA,iBAA8BA,EAAAA,QAAgB,QAAS,IAAK,SAAS,CACrE,GAAA,EAAA,EAAA,iBAA8BA,EAAAA,QAAgB,QAAS,IAAK,SAAS,CACrE,GAAA,EAAA,EAAA,iBAA8BA,EAAAA,QAAgB,QAAS,IAAK,SAAS,CACrE,GAAA,EAAA,EAAA,iBACJA,EAAAA,QAAgB,QAChB,IACA,SACD,CAEK,EAAgC,EAElC,CAAC,QAAQ,IAAI,sBAAsB,SAAS,YAAY,CAExD,QAAQ,IAAI,sBAAsB,SAAS,UAAU,CAGnD,EAA2B,GAAmC,CAClE,GAAI,CAIF,OAFE,EAAe,OAAO,UAAA,EAAA,EAAA,oBAA8B,EACtC,QAAQ,gBAAgB,CACjC,QACI,CACX,MAAO,KAKL,EAAoC,GAAmC,CAC3E,GAAI,CAIF,OAFE,EAAe,OAAO,UAAA,EAAA,EAAA,oBAA8B,EACtC,QAAQ,kBAAkB,CACnC,QACI,CACX,MAAO,KAIL,GACJ,EACA,EACA,IACW,CAEX,IAAM,GADk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AgB,eAAc,kBAAmB,GAAkB,CAE3E,QAAQ,IAAI,wBAA0B,EAAe,OAAS,QAE9D,IAAM,GAAA,EAAA,EAAA,kBAAkC,EAAc,CAEhD,CAAE,QAAS,EAAe,MAkBhC,MAbI,CAAC,IAAmB,GAAgB,GAAkB,IAAS,SAEjE,MAAA,EAAA,EAAA,iBAAsB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GAChB,IAAK,EAAiB,OAAS,MAChC,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
1
+ {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger('Build optimization enabled');\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env.npm_lifecycle_event;\n const lifecycleScript = process.env.npm_lifecycle_script ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const logger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env.npm_lifecycle_script?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env.npm_lifecycle_script?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n logger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env: {\n INTLAYER_EDITOR_ENABLED:\n intlayerConfig.editor?.enabled === false ? 'false' : 'true',\n },\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (p) => request === p || request.startsWith(`${p}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"4lBA+BA,MAAM,EAAuB,GAAmC,CAC9D,IAAI,EAAcA,EAAAA,QAAgB,QAElC,GAAI,CAIF,GAFE,EAAe,OAAO,UAAA,EAAA,EAAA,oBAA8B,EAC1B,oBAAoB,CAC9B,aACZ,EAIR,MAAO,CACL,aAAA,EAAA,EAAA,iBAA6B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AM,EAEW,EAAc"}
@@ -1,2 +1,2 @@
1
- import{localeDetector as e}from"./localeDetector.mjs";import{getCanonicalPath as t,getLocalizedPath as n,getRewriteRules as r}from"@intlayer/core/localization";import i from"@intlayer/config/built";import{DefaultValues as a}from"@intlayer/config/client";import{getLocaleFromStorage as o,setLocaleInStorage as s}from"@intlayer/core/utils";import{NextResponse as c}from"next/server";const{internationalization:l,routing:u}=i??{},{locales:d,defaultLocale:f}=l??{},{basePath:p,mode:m,rewrite:h}=u??{},g=m??a.Routing.ROUTING_MODE,_=g===`no-prefix`||g===`search-params`,v=g===`prefix-all`,y=!_,b=r(h,`url`),x=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},S=(e,t)=>{if(g!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},C=(e,t,n)=>{let r=e.nextUrl.pathname,i=w(e);return _?T(e,i,r):D(e,i,E(r),r)},w=e=>o({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),T=(n,r,i)=>{let a=E(i);if(a){let e=t(i.slice(`/${a}`.length)||`/`,a,b),r=S(n.nextUrl.search,a);return N(n,r?`${e}${r}`:`${e}${n.nextUrl.search??``}`)}if(g===`search-params`){let a=new URLSearchParams(n.nextUrl.search).get(`locale`),o=d?.includes(a),s=r??(o?a:void 0)??r??e?.(n)??f;d?.includes(s)||(s=f);let c=t(i,s,b);if(a===s)return M(n,`${y?`/${s}${c}`:c}${n.nextUrl.search??``}`,s);let l=S(n.nextUrl.search,s);return N(n,l?`${i}${l}`:`${i}${n.nextUrl.search??``}`)}let o=r??e?.(n)??f;d?.includes(o)||(o=f);let s=t(i,o,b),c=y?`/${o}${s}`:s,l=S(n.nextUrl.search,o);return M(n,l?`${c}${l}`:`${c}${n.nextUrl.search??``}`,o)},E=e=>d.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),D=(e,t,n,r)=>n?k(e,n,r):x(e)?O(e,f,r):O(e,t,r),O=(r,i,a)=>{let o=i??e?.(r)??f;d.includes(o)||(o=f);let s=t(a,o,b),c=n(s,o,b),l=typeof c==`string`?c:c.path,u=j(o,l,p,S(r.nextUrl.search,o));return v||o!==f?N(r,u):M(r,y?`/${o}${s}`:s,o)},k=(e,r,i)=>{let a=i.slice(`/${r}`.length)||`/`,o=t(a,r,b),s=n(o,r,b),c=typeof s==`string`?s:s.path;if(typeof s!=`string`&&s.isRewritten&&c!==a)return N(e,j(r,c,p,S(e.nextUrl.search,r)));let l=y?`/${r}${o}`:o;if(!v&&r===f)return A(e,r,i);let u=e.nextUrl.search;return M(e,l+(u??``),r)},A=(e,t,r)=>{if(!v&&t===f){let i=n(r,t,b),a=typeof i==`string`?i:i.path,o=p.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),N(e,`${p}${o?``:`/`}${s}`+(S(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=S(e.nextUrl.search,t),a=y?`/${t}${r}`:r;return M(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},j=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(g===`no-prefix`||g===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},M=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t,a=new Headers(e.headers);s(n,{setHeader:(e,t)=>{a.set(e,t)}});let o=new URL(i,e.url),l=o.href===e.nextUrl.href?c.next({request:{headers:a}}):c.rewrite(o,{request:{headers:a}});return s(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},N=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return c.redirect(new URL(r,e.url))};export{C as intlayerProxy};
1
+ import{localeDetector as e}from"./localeDetector.mjs";import{getCanonicalPath as t,getLocalizedPath as n,getRewriteRules as r}from"@intlayer/core/localization";import i from"@intlayer/config/built";import{ROUTING_MODE as a}from"@intlayer/config/defaultValues";import{getLocaleFromStorage as o,setLocaleInStorage as s}from"@intlayer/core/utils";import{NextResponse as c}from"next/server";const{internationalization:l,routing:u}=i??{},{locales:d,defaultLocale:f}=l??{},{basePath:p,mode:m,rewrite:h}=u??{},g=m??a,_=g===`no-prefix`||g===`search-params`,v=g===`prefix-all`,y=!_,b=r(h,`url`),x=e=>{let t=e.headers.get(`purpose`),n=e.headers.get(`next-router-prefetch`),r=e.headers.get(`next-url`),i=e.headers.get(`x-nextjs-data`);return t===`prefetch`||n===`1`||!!r||!!i},S=(e,t)=>{if(g!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},C=(e,t,n)=>{let r=e.nextUrl.pathname,i=w(e);return _?T(e,i,r):D(e,i,E(r),r)},w=e=>o({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),T=(n,r,i)=>{let a=E(i);if(a){let e=t(i.slice(`/${a}`.length)||`/`,a,b),r=S(n.nextUrl.search,a);return N(n,r?`${e}${r}`:`${e}${n.nextUrl.search??``}`)}if(g===`search-params`){let a=new URLSearchParams(n.nextUrl.search).get(`locale`),o=d?.includes(a),s=r??(o?a:void 0)??r??e?.(n)??f;d?.includes(s)||(s=f);let c=t(i,s,b);if(a===s)return M(n,`${y?`/${s}${c}`:c}${n.nextUrl.search??``}`,s);let l=S(n.nextUrl.search,s);return N(n,l?`${i}${l}`:`${i}${n.nextUrl.search??``}`)}let o=r??e?.(n)??f;d?.includes(o)||(o=f);let s=t(i,o,b),c=y?`/${o}${s}`:s,l=S(n.nextUrl.search,o);return M(n,l?`${c}${l}`:`${c}${n.nextUrl.search??``}`,o)},E=e=>d.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),D=(e,t,n,r)=>n?k(e,n,r):x(e)?O(e,f,r):O(e,t,r),O=(r,i,a)=>{let o=i??e?.(r)??f;d.includes(o)||(o=f);let s=t(a,o,b),c=n(s,o,b),l=typeof c==`string`?c:c.path,u=j(o,l,p,S(r.nextUrl.search,o));return v||o!==f?N(r,u):M(r,y?`/${o}${s}`:s,o)},k=(e,r,i)=>{let a=i.slice(`/${r}`.length)||`/`,o=t(a,r,b),s=n(o,r,b),c=typeof s==`string`?s:s.path;if(typeof s!=`string`&&s.isRewritten&&c!==a)return N(e,j(r,c,p,S(e.nextUrl.search,r)));let l=y?`/${r}${o}`:o;if(!v&&r===f)return A(e,r,i);let u=e.nextUrl.search;return M(e,l+(u??``),r)},A=(e,t,r)=>{if(!v&&t===f){let i=n(r,t,b),a=typeof i==`string`?i:i.path,o=p.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),N(e,`${p}${o?``:`/`}${s}`+(S(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=S(e.nextUrl.search,t),a=y?`/${t}${r}`:r;return M(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},j=(e,t,n,r)=>{let i=t.startsWith(`/${e}`)?t.slice(`/${e}`.length)||`/`:t;if(g===`no-prefix`||g===`search-params`)return`${i}${r?`?${r}`:``}`;let a=t.startsWith(`/${e}`)?t:`${e}${t.startsWith(`/`)?``:`/`}${t}`;return`${n}${n.endsWith(`/`)?``:`/`}${a}`.replace(/\/+/g,`/`)},M=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t,a=new Headers(e.headers);s(n,{setHeader:(e,t)=>{a.set(e,t)}});let o=new URL(i,e.url),l=o.href===e.nextUrl.href?c.next({request:{headers:a}}):c.rewrite(o,{request:{headers:a}});return s(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},N=(e,t)=>{let n=e.nextUrl.search,r=n&&!t.includes(`?`)?`${t}${n}`:t;return c.redirect(new URL(r,e.url))};export{C as intlayerProxy};
2
2
  //# sourceMappingURL=intlayerProxy.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? DefaultValues.Routing.ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests can be identified by several headers:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js router prefetch)\n * - next-url: present (Next.js internal navigation)\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n const nextUrl = request.headers.get('next-url');\n const xNextjsData = request.headers.get('x-nextjs-data');\n\n return (\n purpose === 'prefetch' ||\n nextRouterPrefetch === '1' ||\n !!nextUrl ||\n !!xNextjsData\n );\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @returns - The redirect response.\n */\nconst redirectUrl = (request: NextRequest, newPath: string): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"6XA+CA,KAAM,CAAE,uBAAsB,WAAY,GAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQ,EAAc,QAAQ,aAC9C,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAi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,IAAI,IAAS,CACnD,EAAK,MAAM,IAAI,IAAS,OAAO,EAAI,IACnC,EAEJ,GAAI,IAAkB,aAAe,IAAkB,gBACrD,MAAO,GAAG,IAAoB,EAAS,IAAI,IAAW,KAIxD,IAAM,EAAuB,EAAK,WAAW,IAAI,IAAS,CACtD,EACA,GAAG,IAAS,EAAK,WAAW,IAAI,CAAG,GAAK,MAAM,IAQlD,MALgB,GAAG,IADW,EAAS,SAAS,IAAI,CACE,GAAK,MAAM,IAGvC,QAAQ,OAAQ,IAAI,EAU1C,GACJ,EACA,EACA,IACiB,CACjB,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAEvD,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,CACnD,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/B,EAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACF,EAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAO,EAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
1
+ {"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n} from '@intlayer/core/localization';\nimport { getLocaleFromStorage, setLocaleInStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { internationalization, routing } = configuration ?? {};\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite } = routing ?? {};\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n effectiveMode === 'no-prefix' || effectiveMode === 'search-params';\nconst prefixDefault = effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules = getRewriteRules(rewrite, 'url');\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests can be identified by several headers:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js router prefetch)\n * - next-url: present (Next.js internal navigation)\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n const nextUrl = request.headers.get('next-url');\n const xNextjsData = request.headers.get('x-nextjs-data');\n\n return (\n purpose === 'prefetch' ||\n nextRouterPrefetch === '1' ||\n !!nextUrl ||\n !!xNextjsData\n );\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (effectiveMode !== 'search-params') return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? `/${locale}${canonicalPath}`\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[]).find(\n (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!(locales as Locale[]).includes(locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? `/${locale}${canonicalPath}` : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n const internalUrl = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, pathname);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Redirect to remove prefix\n // We use canonicalPath because in no-prefix default mode, the URL is usually just the path\n // But wait, if we are in this function, the URL *has* a prefix.\n // We want to redirect to /about (localized for EN).\n\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const basePathTrailingSlash = (basePath as string).endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? '')\n );\n }\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // If no redirect needed, we rewrite to the internal canonical path\n const internalPath = internalPrefix\n ? `/${pathLocale}${canonicalPath}`\n : canonicalPath;\n\n const rewriteTarget = searchWithLocale\n ? `${internalPath}${searchWithLocale}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewriteTarget, pathLocale);\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = path.startsWith(`/${locale}`)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (effectiveMode === 'no-prefix' || effectiveMode === 'search-params') {\n return `${pathWithoutPrefix}${search ? `?${search}` : ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = path.startsWith(`/${locale}`)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathTrailingSlash = basePath.endsWith('/');\n const newPath = `${basePath}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n return cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @returns - The redirect response.\n */\nconst redirectUrl = (request: NextRequest, newPath: string): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n return NextResponse.redirect(new URL(pathWithSearch, request.url));\n};\n"],"mappings":"mYA+CA,KAAM,CAAE,uBAAsB,WAAY,GAAiB,EAAE,CACvD,CAAE,UAAS,iBAAkB,GAAwB,EAAE,CACvD,CAAE,WAAU,OAAM,WAAY,GAAW,EAAE,CAK3C,EAAgB,GAAQ,EACxB,EACJ,IAAkB,aAAe,IAAkB,gBAC/C,EAAgB,IAAkB,aAElC,EAAiB,CAAC,EAElB,EAAe,EAAgB,EAAS,MAAM,CAgB9C,EAAqB,GAAkC,CAC3D,IAAM,EAAU,EAAQ,QAAQ,IAAI,UAAU,CACxC,EAAqB,EAAQ,QAAQ,IAAI,uBAAuB,CAChE,EAAU,EAAQ,QAAQ,IAAI,WAAW,CACzC,EAAc,EAAQ,QAAQ,IAAI,gBAAgB,CAExD,OAC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AAM,IAQlD,MALgB,GAAG,IADW,EAAS,SAAS,IAAI,CACE,GAAK,MAAM,IAGvC,QAAQ,OAAQ,IAAI,EAU1C,GACJ,EACA,EACA,IACiB,CACjB,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAEvD,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,CACnD,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAY,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAIhD,EACJ,EAAU,OAAS,EAAQ,QAAQ,KAC/B,EAAa,KAAK,CAChB,QAAS,CACP,QAAS,EACV,CACF,CAAC,CACF,EAAa,QAAQ,EAAW,CAC9B,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOR,OALA,EAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAS,QAAQ,IAAI,EAAM,EAAM,EAEpC,CAAC,CACK,GAUH,GAAe,EAAsB,IAAkC,CAC3E,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAE7D,OAAO,EAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
@@ -1,2 +1,2 @@
1
- import{localeDetector as e}from"@intlayer/core/localization";import t from"@intlayer/config/built";import{DefaultValues as n}from"@intlayer/config/client";import{getLocaleFromStorage as r}from"@intlayer/core/utils";import{cookies as i,headers as a}from"next/headers.js";const o=async()=>{let o=t?.internationalization?.defaultLocale??n.Internationalization.DEFAULT_LOCALE,s=await a(),c=await i(),l=r({getCookie:e=>c.get(e)?.value??null,getHeader:e=>s.get(e)??null});if(l)return l;let u={};return s.forEach((e,t)=>{u[t]=e}),e(u)||o};export{o as getLocale};
1
+ import{localeDetector as e}from"@intlayer/core/localization";import t from"@intlayer/config/built";import{DEFAULT_LOCALE as n}from"@intlayer/config/defaultValues";import{getLocaleFromStorage as r}from"@intlayer/core/utils";import{cookies as i,headers as a}from"next/headers.js";const o=async()=>{let o=t?.internationalization?.defaultLocale??n,s=await a(),c=await i(),l=r({getCookie:e=>c.get(e)?.value??null,getHeader:e=>s.get(e)??null});if(l)return l;let u={};return s.forEach((e,t)=>{u[t]=e}),e(u)||o};export{o as getLocale};
2
2
  //# sourceMappingURL=getLocale.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.mjs","names":[],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"8QA0BA,MAAa,EAAY,SAA6B,CACpD,IAAM,EACJ,GAAe,sBAAsB,eACrC,EAAc,qBAAqB,eAG/B,EAAc,MAAM,GAAS,CAC7B,EAAc,MAAM,GAAS,CAE7B,EAAe,EAAqB,CACxC,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAE,OAAS,KAC7D,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAI,KACvD,CAAC,CAEF,GAAI,EAAc,OAAO,EAGzB,IAAM,EAA4C,EAAE,CASpD,OARA,EAAY,SAAS,EAAO,IAAQ,CAClC,EAAkB,GAAO,GACzB,CAEyB,EAAe,EAAkB,EAIrD"}
1
+ {"version":3,"file":"getLocale.mjs","names":[],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale =\n configuration?.internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorage({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":"sRA0BA,MAAa,EAAY,SAA6B,CACpD,IAAM,EACJ,GAAe,sBAAsB,eAAiB,EAGlD,EAAc,MAAM,GAAS,CAC7B,EAAc,MAAM,GAAS,CAE7B,EAAe,EAAqB,CACxC,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAE,OAAS,KAC7D,UAAY,GAAiB,EAAY,IAAI,EAAK,EAAI,KACvD,CAAC,CAEF,GAAI,EAAc,OAAO,EAGzB,IAAM,EAA4C,EAAE,CASpD,OARA,EAAY,SAAS,EAAO,IAAQ,CAClC,EAAkB,GAAO,GACzB,CAEyB,EAAe,EAAkB,EAIrD"}
@@ -1,2 +1,2 @@
1
- import{DefaultValues as e}from"@intlayer/config/client";import{join as t,relative as n,resolve as r}from"node:path";import{prepareIntlayer as i}from"@intlayer/chokidar/build";import{logConfigDetails as a}from"@intlayer/chokidar/cli";import{buildComponentFilesList as o,runOnce as s}from"@intlayer/chokidar/utils";import{ANSIColors as c,colorize as l,getAppLogger as u}from"@intlayer/config/logger";import{getConfiguration as d}from"@intlayer/config/node";import{compareVersions as f,getAlias as p,getProjectRequire as m,normalizePath as h}from"@intlayer/config/utils";import{getDictionaries as g}from"@intlayer/dictionaries-entry";import{IntlayerPlugin as _}from"@intlayer/webpack";import{defu as v}from"defu";import y from"next/package.json"with{type:"json"};const b=f(y.version,`≥`,`13.0.0`),x=f(y.version,`≥`,`15.0.0`),S=f(y.version,`≥`,`16.0.0`),C=f(y.version,`≥`,`15.3.0`),w=S?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),T=e=>{try{return(e.build?.require??m()).resolve(`@intlayer/swc`),!0}catch{return!1}},E=e=>{try{return(e.build?.require??m()).resolve(`@intlayer/babel`),!0}catch{return!1}},D=(e,t,r)=>{let i=(t.build?.require??m())?.resolve(e);return r?h(`./${n(process.cwd(),i)}`):i},O=(n,r,i,a)=>{let{optimize:d}=n.build,f=n.build.importMode??n.dictionary?.importMode,{dictionariesDir:p,unmergedDictionariesDir:m,dynamicDictionariesDir:h,fetchDictionariesDir:_,mainDir:v}=n.system,{baseDir:y}=n.system,x=u(n);if(d===!1||d===void 0&&!r||!b)return{};let S=T(n);if(s(t(y,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[l(`Recommended: Install`,c.GREY),l(`@intlayer/swc`,c.GREY_LIGHT),l(`package to enable build optimization. See documentation: `,c.GREY),l(`https://intlayer.org/docs/bundle-optimization`,c.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),s(t(y,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(E(n)){let e=n.compiler?.enabled??!0;e===`build-only`&&(e=!a),x(e?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!S)return{};let C=t(v,`dictionaries.mjs`),w=t(v,`dynamic_dictionaries.mjs`),O=t(v,`unmerged_dictionaries.mjs`),k=t(v,`fetch_dictionaries.mjs`),A=[...o(n),C,O],j=g(n),M={};return Object.values(j).forEach(t=>{M[t.key]=t.importMode??f??e.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[D(`@intlayer/swc`,n,i),{dictionariesDir:p,dictionariesEntryPath:C,unmergedDictionariesEntryPath:O,unmergedDictionariesDir:m,dynamicDictionariesDir:h,dynamicDictionariesEntryPath:w,fetchDictionariesDir:_,fetchDictionariesEntryPath:k,importMode:f,filesList:A,replaceDictionaryEntry:!0,dictionaryModeMap:M}]]}}},k=()=>{let e=process.env.npm_lifecycle_event,t=process.env.npm_lifecycle_script??``;return{isDevCommand:e===`dev`||process.argv.some(e=>e===`dev`)||/(^|\s)(next\s+)?dev(\s|$)/.test(t),isBuildCommand:e===`build`||process.argv.some(e=>e===`build`)||/(^|\s)(next\s+)?build(\s|$)/.test(t),isStartCommand:e===`start`||process.argv.some(e=>e===`start`)||/(^|\s)(next\s+)?start(\s|$)/.test(t)}},A=(e={},t)=>{typeof e!=`object`&&(e={});let n=d(t);a(t);let i=u(n),o=t?.enableTurbopack??w;o&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:s,isDevCommand:c}=k(),l={resolveAlias:p({configuration:n,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},f=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],m=()=>{let t={};return x&&(t={...t,serverExternalPackages:f}),b&&!x&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:f}}),t=o?x&&C?{...t,turbopack:l}:{...t,experimental:{...t?.experimental??{},turbo:l}}:{...t,webpack:(t,i)=>{let{isServer:a,nextRuntime:o}=i;return typeof e.webpack==`function`&&(t=e.webpack(t,i)),t.externals===!1&&(t.externals=[]),t.externals.push({esbuild:`esbuild`,module:`module`,fs:`fs`,chokidar:`chokidar`,fsevents:`fsevents`}),t.module.rules.push({test:/\.node$/,loader:`node-loader`}),t.resolve.alias={...t.resolve.alias,...p({configuration:n,formatter:e=>r(e)})},c&&a&&o===`nodejs`&&t.plugins.push(new _(n)),t}},t},h=O(n,s,o??!1,c);return v(v(m(),h),e)},j=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:r,isStartCommand:a}=k();process.env.INTLAYER_IS_DEV_COMMAND=r?`true`:`false`;let o=d(t),{mode:s}=o.build;return!a&&(r||n||s===`auto`)&&await i(o,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60,env:n?`prod`:`dev`}),A(await e,t)};export{j as withIntlayer,A as withIntlayerSync};
1
+ import{IMPORT_MODE as e}from"@intlayer/config/defaultValues";import{join as t,relative as n,resolve as r}from"node:path";import{prepareIntlayer as i}from"@intlayer/chokidar/build";import{logConfigDetails as a}from"@intlayer/chokidar/cli";import{buildComponentFilesList as o,runOnce as s}from"@intlayer/chokidar/utils";import*as c from"@intlayer/config/colors";import{colorize as l,getAppLogger as u}from"@intlayer/config/logger";import{getConfiguration as d}from"@intlayer/config/node";import{compareVersions as f,getAlias as p,getProjectRequire as m,normalizePath as h}from"@intlayer/config/utils";import{getDictionaries as g}from"@intlayer/dictionaries-entry";import{IntlayerPlugin as _}from"@intlayer/webpack";import{defu as v}from"defu";import y from"next/package.json"with{type:"json"};const b=e=>{let t=y.version;try{t=(e.build?.require??m())(`next/package.json`).version}catch{}return{isGteNext13:f(t,`≥`,`13.0.0`),isGteNext15:f(t,`≥`,`15.0.0`),isGteNext16:f(t,`≥`,`16.0.0`),isTurbopackStable:f(t,`≥`,`15.3.0`)}},x=e=>{try{return(e.build?.require??m()).resolve(`@intlayer/swc`),!0}catch{return!1}},S=e=>{try{return(e.build?.require??m()).resolve(`@intlayer/babel`),!0}catch{return!1}},C=(e,t,r)=>{let i=(t.build?.require??m())?.resolve(e);return r?h(`./${n(process.cwd(),i)}`):i},w=(n,r,i,a,d)=>{let{optimize:f}=n.build,p=n.build.importMode??n.dictionary?.importMode,{dictionariesDir:m,unmergedDictionariesDir:h,dynamicDictionariesDir:_,fetchDictionariesDir:v,mainDir:y}=n.system,{baseDir:b}=n.system,w=u(n);if(f===!1||f===void 0&&!r||!d)return{};let T=x(n);if(s(t(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{w(T?`Build optimization enabled`:[l(`Recommended: Install`,c.GREY),l(`@intlayer/swc`,c.GREY_LIGHT),l(`package to enable build optimization. See documentation:`,c.GREY),l(`https://intlayer.org/docs/bundle-optimization`,c.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),s(t(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(S(n)){let e=n.compiler?.enabled??!0;e===`build-only`&&(e=!a),w(e?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!T)return{};let E=t(y,`dictionaries.mjs`),D=t(y,`dynamic_dictionaries.mjs`),O=t(y,`unmerged_dictionaries.mjs`),k=t(y,`fetch_dictionaries.mjs`),A=[...o(n),E,O],j=g(n),M={};return Object.values(j).forEach(t=>{M[t.key]=t.importMode??p??e}),{experimental:{swcPlugins:[[C(`@intlayer/swc`,n,i),{dictionariesDir:m,dictionariesEntryPath:E,unmergedDictionariesEntryPath:O,unmergedDictionariesDir:h,dynamicDictionariesDir:_,dynamicDictionariesEntryPath:D,fetchDictionariesDir:v,fetchDictionariesEntryPath:k,importMode:p,filesList:A,replaceDictionaryEntry:!0,dictionaryModeMap:M}]]}}},T=()=>{let e=process.env.npm_lifecycle_event,t=process.env.npm_lifecycle_script??``;return{isDevCommand:e===`dev`||process.argv.some(e=>e===`dev`)||/(^|\s)(next\s+)?dev(\s|$)/.test(t),isBuildCommand:e===`build`||process.argv.some(e=>e===`build`)||/(^|\s)(next\s+)?build(\s|$)/.test(t),isStartCommand:e===`start`||process.argv.some(e=>e===`start`)||/(^|\s)(next\s+)?start(\s|$)/.test(t)}},E=(e={},t)=>{typeof e!=`object`&&(e={});let n=d(t);a(t);let i=u(n),{isGteNext13:o,isGteNext15:s,isGteNext16:c,isTurbopackStable:l}=b(n),f=c?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),m=t?.enableTurbopack??f;m&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:h,isDevCommand:g}=T(),y={resolveAlias:p({configuration:n,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},x=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`,`recast`,`@intlayer/chokidar`,`@intlayer/webpack`],S=()=>{let t={env:{INTLAYER_EDITOR_ENABLED:n.editor?.enabled===!1?`false`:`true`}};return s&&(t={...t,serverExternalPackages:x}),o&&!s&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:x}}),t=m?s&&l?{...t,turbopack:y}:{...t,experimental:{...t?.experimental??{},turbo:y}}:{...t,webpack:(t,i)=>{let{isServer:a,nextRuntime:o}=i;typeof e.webpack==`function`&&(t=e.webpack(t,i)),t.externals===!1&&(t.externals=[]);let s=new Set([`esbuild`,`module`,`fs`,`chokidar`,`fsevents`,`recast`]),c=[`@intlayer/chokidar`,`@intlayer/webpack`];return t.externals.push(({request:e},t)=>{if(e&&(s.has(e)||c.some(t=>e===t||e.startsWith(`${t}/`))))return t(null,`commonjs ${e}`);t(null)}),t.module.rules.push({test:/\.node$/,loader:`node-loader`}),t.resolve.alias={...t.resolve.alias,...p({configuration:n,formatter:e=>r(e)})},g&&a&&o===`nodejs`&&t.plugins.push(new _(n)),t}},t},C=w(n,h,m??!1,g,o);return v(v(S(),C),e)},D=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:r,isStartCommand:a}=T();process.env.INTLAYER_IS_DEV_COMMAND=r?`true`:`false`;let o=d(t),{mode:s}=o.build;return!a&&(r||n||s===`auto`)&&await i(o,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60,env:n?`prod`:`dev`}),E(await e,t)};export{D as withIntlayer,E as withIntlayerSync};
2
2
  //# sourceMappingURL=withIntlayer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.mjs","names":[],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\nconst isGteNext13 = compareVersions(nextPackageJSON.version, '≥', '13.0.0');\nconst isGteNext15 = compareVersions(nextPackageJSON.version, '≥', '15.0.0');\nconst isGteNext16 = compareVersions(nextPackageJSON.version, '≥', '16.0.0');\nconst isTurbopackStable = compareVersions(\n nextPackageJSON.version,\n '≥',\n '15.3.0'\n);\n\nconst isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enable turbopack by default, and offer the possibility to disable it if --webpack flag is used\n !process.env.npm_lifecycle_script?.includes('--webpack')\n : // Next@15 use --turbopack flag, Next@14 use --turbo flag\n process.env.npm_lifecycle_script?.includes('--turbo');\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger('Build optimization enabled');\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation: ',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ??\n importMode ??\n DefaultValues.Dictionary.IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env.npm_lifecycle_event;\n const lifecycleScript = process.env.npm_lifecycle_script ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const logger = getAppLogger(intlayerConfig);\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n logger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n ];\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {};\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark these modules as externals\n config.externals.push({\n esbuild: 'esbuild',\n module: 'module',\n fs: 'fs',\n chokidar: 'chokidar',\n fsevents: 'fsevents',\n });\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"wvBAyBA,MAAM,EAAc,EAAgB,EAAgB,QAAS,IAAK,SAAS,CACrE,EAAc,EAAgB,EAAgB,QAAS,IAAK,SAAS,CACrE,EAAc,EAAgB,EAAgB,QAAS,IAAK,SAAS,CACrE,EAAoB,EACxB,EAAgB,QAChB,IACA,SACD,CAEK,EAAgC,EAElC,CAAC,QAAQ,IAAI,sBAAsB,SAAS,YAAY,CAExD,QAAQ,IAAI,sBAAsB,SAAS,UAAU,CAGnD,EAA2B,GAAmC,CAClE,GAAI,CAIF,OAFE,EAAe,OAAO,SAAW,GAAmB,EACtC,QAAQ,gBAAgB,CACjC,QACI,CACX,M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,IAAmB,GAAgB,GAAkB,IAAS,SAEjE,MAAM,EAAgB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GAChB,IAAK,EAAiB,OAAS,MAChC,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
1
+ {"version":3,"file":"withIntlayer.mjs","names":[],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getProjectRequire,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger('Build optimization enabled');\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env.npm_lifecycle_event;\n const lifecycleScript = process.env.npm_lifecycle_script ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const logger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env.npm_lifecycle_script?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env.npm_lifecycle_script?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n logger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env: {\n INTLAYER_EDITOR_ENABLED:\n intlayerConfig.editor?.enabled === false ? 'false' : 'true',\n },\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (p) => request === p || request.startsWith(`${p}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"uxBA+BA,MAAM,EAAuB,GAAmC,CAC9D,IAAI,EAAc,EAAgB,QAElC,GAAI,CAIF,GAFE,EAAe,OAAO,SAAW,GAAmB,EAC1B,oBAAoB,CAC9B,aACZ,EAIR,MAAO,CACL,YAAa,EAAgB,EAAa,IAAK,SAAS,CACxD,YAAa,EAAgB,EAAa,IAAK,SAAS,CACxD,YAAa,EAAgB,EAAa,IAAK,SAAS,CACxD,kBAAmB,EAAgB,EAAa,IAAK,SAAS,CAC/D,EAIG,EAA2B,GAAmC,CAClE,GAAI,CAIF,OAFE,EAAe,OAAO,SAAW,GAAmB,EACtC,QAAQ,gBAAgB,CACjC,QACI,CACX,M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,EAAQ,EAAM,CAC7C,CAAC,CACH,CAGG,GAAgB,GAAY,IAAgB,UAE9C,EAAO,QAAQ,KAAK,IAAI,EAAe,EAAe,CAAC,CAGlD,GAEV,CAGI,GAGH,EAAmC,EACvC,EACA,EACA,GAAsB,GACtB,EACA,EACD,CAUD,OAFe,EANiC,EAC9C,GAAc,CACd,EACD,CAGuC,EAAW,EAoBxC,EAAe,MAC1B,EAA6B,EAAE,CAC/B,IAC4B,CAC5B,GAAM,CAAE,iBAAgB,eAAc,kBAAmB,GAAkB,CAE3E,QAAQ,IAAI,wBAA0B,EAAe,OAAS,QAE9D,IAAM,EAAiB,EAAiB,EAAc,CAEhD,CAAE,QAAS,EAAe,MAkBhC,MAbI,CAAC,IAAmB,GAAgB,GAAkB,IAAS,SAEjE,MAAM,EAAgB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GAChB,IAAK,EAAiB,OAAS,MAChC,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.d.ts","names":[],"sources":["../../../src/server/withIntlayer.ts"],"mappings":";;;;KAmQK,mBAAA,GAAsB,uBAAA;EACzB,eAAA;AAAA;;;;;AAcF;;;;;;;cAAa,gBAAA,aAA8B,OAAA,CAAQ,UAAA,GACjD,UAAA,GAAY,CAAA,EACZ,aAAA,GAAgB,mBAAA,KACf,UAAA,GAAa,CAAA;;;;;;;;;;;;;;;AA2KhB;cAAa,YAAA,aAAgC,OAAA,CAAQ,UAAA,GACnD,UAAA,GAAY,CAAA,GAAI,OAAA,CAAQ,CAAA,GACxB,aAAA,GAAgB,mBAAA,KACf,OAAA,CAAQ,UAAA,GAAa,CAAA"}
1
+ {"version":3,"file":"withIntlayer.d.ts","names":[],"sources":["../../../src/server/withIntlayer.ts"],"mappings":";;;;KA6QK,mBAAA,GAAsB,uBAAA;EACzB,eAAA;AAAA;;;;;AAcF;;;;;;;cAAa,gBAAA,aAA8B,OAAA,CAAQ,UAAA,GACjD,UAAA,GAAY,CAAA,EACZ,aAAA,GAAgB,mBAAA,KACf,UAAA,GAAa,CAAA;;;;;;;;;;;;;;;AAgNhB;cAAa,YAAA,aAAgC,OAAA,CAAQ,UAAA,GACnD,UAAA,GAAY,CAAA,GAAI,OAAA,CAAQ,CAAA,GACxB,aAAA,GAAgB,mBAAA,KACf,OAAA,CAAQ,UAAA,GAAa,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-intlayer",
3
- "version": "8.4.1",
3
+ "version": "8.4.3",
4
4
  "private": false,
5
5
  "description": "Simplify internationalization i18n in Next.js with context providers, hooks, locale detection, and multilingual content integration.",
6
6
  "keywords": [
@@ -124,15 +124,15 @@
124
124
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
125
125
  },
126
126
  "dependencies": {
127
- "@intlayer/chokidar": "8.4.1",
128
- "@intlayer/config": "8.4.1",
129
- "@intlayer/core": "8.4.1",
130
- "@intlayer/dictionaries-entry": "8.4.1",
131
- "@intlayer/types": "8.4.1",
132
- "@intlayer/webpack": "8.4.1",
127
+ "@intlayer/chokidar": "8.4.3",
128
+ "@intlayer/config": "8.4.3",
129
+ "@intlayer/core": "8.4.3",
130
+ "@intlayer/dictionaries-entry": "8.4.3",
131
+ "@intlayer/types": "8.4.3",
132
+ "@intlayer/webpack": "8.4.3",
133
133
  "defu": "6.1.4",
134
134
  "node-loader": "2.1.0",
135
- "react-intlayer": "8.4.1"
135
+ "react-intlayer": "8.4.3"
136
136
  },
137
137
  "devDependencies": {
138
138
  "@types/node": "25.5.0",