next-intlayer 8.1.6 → 8.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,25 +46,26 @@ With **per-locale content files**, **TypeScript autocompletion**, **tree-shakabl
46
46
 
47
47
  ## Keys benefits of Intlayer:
48
48
 
49
- | Feature | Description |
50
- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more. |
52
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content) |
53
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file) |
54
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript) |
55
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
56
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app) |
57
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code) |
58
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer) |
59
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
60
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file) |
61
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms) |
62
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization) |
63
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs) |
64
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill) |
65
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md) |
66
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension) |
67
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, and react-intl. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) |
49
+ | Feature | Description |
50
+ | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more. |
52
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content) |
53
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file) |
54
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/compiler.jpg?raw=true" alt="Feature" width="700"> | **Compiler**<br><br>The Intlayer Compiler extract automatically the content from the components and generate the dictionary files.<br><br> - [Compiler](https://intlayer.org/doc/compiler) |
55
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript) |
56
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
57
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app) |
58
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code) |
59
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer) |
60
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
61
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file) |
62
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms) |
63
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization) |
64
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs) |
65
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill) |
66
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md) |
67
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension) |
68
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, react-intl, vue-i18n. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) <br> - [Intlayer and vue-i18n](https://intlayer.org/blog/intlayer-with-vue-i18n) |
68
69
 
69
70
  ---
70
71
 
@@ -153,6 +154,8 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
153
154
  <li><a href="https://intlayer.org/doc/concept/how-works-intlayer" rel=''>How Intlayer Works</a></li>
154
155
  <li><a href="https://intlayer.org/doc/concept/configuration" rel=''>Configuration</a></li>
155
156
  <li><a href="https://intlayer.org/doc/concept/cli" rel=''>Intlayer CLI</a></li>
157
+ <li><a href="https://intlayer.org/doc/compiler" rel=''>Compiler</a></li>
158
+
156
159
  <li><a href="https://intlayer.org/doc/concept/editor" rel=''>Intlayer Editor</a></li>
157
160
  <li><a href="https://intlayer.org/doc/concept/cms" rel=''>Intlayer CMS</a></li>
158
161
  <li><a href="https://intlayer.org/doc/concept/content" rel=''>Dictionary</a>
@@ -179,17 +182,15 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
179
182
  <li><a href="https://intlayer.org/doc/environment/nextjs/15" rel=''>Next.js 15</a></li>
180
183
  <li><a href="https://intlayer.org/doc/environment/nextjs/14" rel=''>Next.js 14 (App Router)</a></li>
181
184
  <li><a href="https://intlayer.org/doc/environment/nextjs/next-with-Page-Router" rel=''>Next.js Page Router</a></li>
185
+ <li><a href="https://intlayer.org/doc/environment/nextjs/compiler" rel=''>Next.js using Compiler</a></li>
182
186
  </ul>
183
187
  </li>
184
188
  <li><a href="https://intlayer.org/doc/environment/create-react-app" rel=''>React CRA</a></li>
185
- <li><a href="https://intlayer.org/doc/environment/vite-and-react" rel=''>Vite + React</a>
186
- <ul>
187
- <li><a href="https://intlayer.org/doc/environment/vite-and-react/react-router-v7" rel=''>React-router-v7</a></li>
188
- <li><a href="https://intlayer.org/doc/environment/vite-and-react/tanstack-start" rel=''>Tanstack start</a></li>
189
- </ul>
190
- </li>
189
+ <li><a href="https://intlayer.org/doc/environment/vite-and-react" rel=''>Vite + React</a></li>
190
+ <li><a href="https://intlayer.org/doc/environment/vite-and-react" rel=''>Vite + React using Compiler</a></li>
191
+ <li><a href="https://intlayer.org/doc/environment/vite-and-react/compiler" rel=''>React-router-v7</a></li>
192
+ <li><a href="https://intlayer.org/doc/environment/vite-and-react/tanstack-start" rel=''>Tanstack start</a></li>
191
193
  <li><a href="https://intlayer.org/doc/environment/react-native-and-expo" rel=''>React Native</a></li>
192
- <li><a href="https://intlayer.org/doc/environment/lynx-and-react" rel=''>Lynx + React</a></li>
193
194
  <li><a href="https://intlayer.org/doc/environment/vite-and-svelte" rel=''>Vite + Svelte</a></li>
194
195
  <li><a href="https://intlayer.org/doc/environment/sveltekit" rel=''>SvelteKit</a></li>
195
196
  <li><a href="https://intlayer.org/doc/environment/vite-and-preact" rel=''>Vite + Preact</a></li>
@@ -197,8 +198,16 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
197
198
  <li><a href="https://intlayer.org/doc/environment/vite-and-nuxt" rel=''>Vite + Nuxt</a></li>
198
199
  <li><a href="https://intlayer.org/doc/environment/vite-and-solid" rel=''>Vite + Solid</a></li>
199
200
  <li><a href="https://intlayer.org/doc/environment/angular" rel=''>Angular</a></li>
200
- <li><a href="https://intlayer.org/doc/environment/express" rel=''>Express</a></li>
201
- <li><a href="https://intlayer.org/doc/environment/nest" rel=''>NestJS</a></li>
201
+ <li>
202
+ <a href="https://intlayer.org/doc/environment/express" rel=''>Backend</a>
203
+ <ul>
204
+ <li><a href="https://intlayer.org/doc/environment/express" rel=''>Express</a></li>
205
+ <li><a href="https://intlayer.org/doc/environment/nest" rel=''>NestJS</a></li>
206
+ <li><a href="https://intlayer.org/doc/environment/fastify" rel=''>Fastify</a></li>
207
+ <li><a href="https://intlayer.org/doc/environment/adonisjs" rel=''>AdonisJS</a></li>
208
+ <li><a href="https://intlayer.org/doc/environment/hono" rel=''>Hono</a></li>
209
+ </ul>
210
+ </li>
202
211
  </ul>
203
212
  </details>
204
213
 
@@ -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/config/built`);n=e.__toESM(n);let r=require(`@intlayer/core/localization`),i=require(`@intlayer/config/client`),a=require(`@intlayer/core/utils`),o=require(`next/server`);const{internationalization:s,routing:c}=n.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,r.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,t,n)=>{let i=w(n),a=t??u;if(i){let t=(0,r.getCanonicalPath)(n.slice(`/${i}`.length)||`/`,i,v),a=b(e.nextUrl.search,i);return M(e,a?`${t}${a}`:`${t}${e.nextUrl.search??``}`)}let o=(0,r.getCanonicalPath)(n,a,v);if(m===`search-params`){if(new URLSearchParams(e.nextUrl.search).get(`locale`)===a)return j(e,`${_?`/${a}${o}`:o}${e.nextUrl.search??``}`,a);let t=b(e.nextUrl.search,a);return M(e,t?`${n}${t}`:`${n}${e.nextUrl.search??``}`)}let s=_?`/${a}${o}`:o,c=b(e.nextUrl.search,a);return j(e,c?`${s}${c}`:`${s}${e.nextUrl.search??``}`,a)},w=e=>l.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),T=(e,t,n,r)=>n?D(e,t,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,n,i)=>{let a=n??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,r.getCanonicalPath)(i,a,v),s=(0,r.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=A(a,c,d,b(e.nextUrl.search,a));return g||a!==u?M(e,f):j(e,_?`/${a}${o}`:o,a)},D=(e,t,n,i)=>{let a=i.slice(`/${n}`.length)||`/`,o=(0,r.getCanonicalPath)(a,n,v);if(t&&t!==n)return M(e,O(e,o,t,d));let s=(0,r.getLocalizedPath)(o,n,v),c=typeof s==`string`?s:s.path;if(typeof s!=`string`&&s.isRewritten&&c!==a)return M(e,A(n,c,d,b(e.nextUrl.search,n)));let l=_?`/${n}${o}`:o;if(!g&&n===u)return k(e,n,i);let f=e.nextUrl.search;return j(e,l+(f??``),n)},O=(e,t,n,i)=>{let a=(0,r.getLocalizedPath)(t,n,v);return A(n,typeof a==`string`?a:a.path,i,b(e.nextUrl.search,n))},k=(e,t,n)=>{if(!g&&t===u){let i=(0,r.getLocalizedPath)(n,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),M(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${n}`:n;return j(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},A=(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,`/`)},j=(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=o.NextResponse.rewrite(new URL(i,e.url),{request:{headers:s}});return(0,a.setLocaleInStorage)(n,{setHeader:(e,t)=>{c.headers.set(e,t)}}),c},M=(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/config/built`);n=e.__toESM(n);let r=require(`@intlayer/core/localization`),i=require(`@intlayer/core/utils`),a=require(`@intlayer/config/client`),o=require(`next/server`);const{internationalization:s,routing:c}=n.default??{},{locales:l,defaultLocale:u}=s??{},{basePath:d,mode:f,rewrite:p}=c??{},m=f??a.DefaultValues.Routing.ROUTING_MODE,h=m===`no-prefix`||m===`search-params`,g=m===`prefix-all`,_=!h,v=(0,r.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,i.getLocaleFromStorage)({getCookie:t=>e.cookies.get(t)?.value??null,getHeader:t=>e.headers.get(t)??null}),C=(e,n,i)=>{let a=w(i);if(a){let t=(0,r.getCanonicalPath)(i.slice(`/${a}`.length)||`/`,a,v),n=b(e.nextUrl.search,a);return M(e,n?`${t}${n}`:`${t}${e.nextUrl.search??``}`)}if(m===`search-params`){let a=new URLSearchParams(e.nextUrl.search).get(`locale`),o=l?.includes(a),s=n??(o?a:void 0)??t.localeDetector?.(e)??u;l?.includes(s)||(s=u);let c=(0,r.getCanonicalPath)(i,s,v);if(a===s)return j(e,`${_?`/${s}${c}`:c}${e.nextUrl.search??``}`,s);let d=b(e.nextUrl.search,s);return M(e,d?`${i}${d}`:`${i}${e.nextUrl.search??``}`)}let o=n??t.localeDetector?.(e)??u;l?.includes(o)||(o=u);let s=(0,r.getCanonicalPath)(i,o,v),c=_?`/${o}${s}`:s,d=b(e.nextUrl.search,o);return j(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,t,n,r):y(e)?E(e,u,r):E(e,t,r),E=(e,n,i)=>{let a=n??t.localeDetector?.(e)??u;l.includes(a)||(a=u);let o=(0,r.getCanonicalPath)(i,a,v),s=(0,r.getLocalizedPath)(o,a,v),c=typeof s==`string`?s:s.path,f=A(a,c,d,b(e.nextUrl.search,a));return g||a!==u?M(e,f):j(e,_?`/${a}${o}`:o,a)},D=(e,t,n,i)=>{let a=i.slice(`/${n}`.length)||`/`,o=(0,r.getCanonicalPath)(a,n,v);if(t&&t!==n)return M(e,O(e,o,t,d));let s=(0,r.getLocalizedPath)(o,n,v),c=typeof s==`string`?s:s.path;if(typeof s!=`string`&&s.isRewritten&&c!==a)return M(e,A(n,c,d,b(e.nextUrl.search,n)));let l=_?`/${n}${o}`:o;if(!g&&n===u)return k(e,n,i);let f=e.nextUrl.search;return j(e,l+(f??``),n)},O=(e,t,n,i)=>{let a=(0,r.getLocalizedPath)(t,n,v);return A(n,typeof a==`string`?a:a.path,i,b(e.nextUrl.search,n))},k=(e,t,n)=>{if(!g&&t===u){let i=(0,r.getLocalizedPath)(n,t,v),a=typeof i==`string`?i:i.path,o=d.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),M(e,`${d}${o?``:`/`}${s}`+(b(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=b(e.nextUrl.search,t),a=_?`/${t}${n}`:n;return j(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},A=(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,`/`)},j=(e,t,n)=>{let r=e.nextUrl.search,a=r&&!t.includes(`?`)?`${t}${r}`:t;console.log(`[intlayerProxy] Rewriting to ${a} with locale ${n}`);let s=new Headers(e.headers);(0,i.setLocaleInStorage)(n,{setHeader:(e,t)=>{s.set(e,t)}});let c=new URL(a,e.url),l=c.href===e.nextUrl.href?o.NextResponse.next({request:{headers:s}}):o.NextResponse.rewrite(c,{request:{headers:s}});return(0,i.setLocaleInStorage)(n,{setHeader:(e,t)=>{l.headers.set(e,t)}}),l},M=(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';\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 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 const locale = localLocale ?? defaultLocale;\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 // Resolve the internal canonical path\n // If user visits /a-propos (no prefix), and we detect 'fr', we resolve to /about\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\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 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, localLocale, 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 localLocale: Locale | undefined,\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 if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\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 */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\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 response = NextResponse.rewrite(new URL(pathWithSearch, request.url), {\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 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,C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B,CACjB,IAAM,EAAS,EAAQ,QAAQ,OACzB,EACJ,GAAU,CAAC,EAAQ,SAAS,IAAI,CAAG,GAAG,IAAU,IAAW,EAEvD,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,EACnD,EAAA,EAAA,oBAAmB,EAAQ,CACzB,WAAY,EAAc,IAAkB,CAC1C,EAAe,IAAI,EAAM,EAAM,EAElC,CAAC,CAEF,IAAM,EAAWC,EAAAA,aAAa,QAAQ,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAE,CAC1E,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOF,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,EAC7D,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAC"}
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';\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 const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\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, localLocale, 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 localLocale: Locale | undefined,\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 if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\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 */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\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 console.log(\n `[intlayerProxy] Rewriting to ${pathWithSearch} with locale ${locale}`\n );\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,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,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`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`next/server`);const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers;a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.NextResponse.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.NextResponse.rewrite(new URL(l,n.url),{request:{headers:s}}):e.NextResponse.next({request:{headers:s}})};exports.multipleProxies=t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`next/server`);const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers(n.headers);a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.NextResponse.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.NextResponse.rewrite(new URL(l,n.url),{request:{headers:s}}):e.NextResponse.next({request:{headers:s}})};exports.multipleProxies=t;
2
2
  //# sourceMappingURL=multipleProxies.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push proxy headers to the array\n proxyHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the proxies\n const transmittedHeaders = new Headers();\n\n // Merge headers\n proxyHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the proxies\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the proxy headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"6IA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAG/B,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEKA,EAAAA,aAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIGA,EAAAA,aAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
1
+ {"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push proxy headers to the array\n proxyHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the proxies\n const transmittedHeaders = new Headers(req.headers);\n\n // Merge headers\n proxyHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the proxies\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the proxy headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"6IA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAAQ,EAAI,QAAQ,CAGnD,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAOA,EAAAA,aAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEKA,EAAAA,aAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIGA,EAAAA,aAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
@@ -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/utils`),a=require(`@intlayer/config/logger`),o=require(`@intlayer/config/node`),s=require(`@intlayer/config/utils`),c=require(`@intlayer/dictionaries-entry`),l=require(`@intlayer/webpack`),u=require(`defu`),d=require(`next/package.json`);d=e.__toESM(d);const f=(0,s.compareVersions)(d.default.version,`≥`,`13.0.0`),p=(0,s.compareVersions)(d.default.version,`≥`,`15.0.0`),m=(0,s.compareVersions)(d.default.version,`≥`,`16.0.0`),h=(0,s.compareVersions)(d.default.version,`≥`,`15.3.0`),g=m?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),_=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/swc`),!0}catch{return!1}},v=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/babel`),!0}catch{return!1}},y=(e,t,r)=>{let i=(t.build?.require??(0,s.getProjectRequire)())?.resolve(e);return r?(0,s.normalizePath)(`./${(0,n.relative)(process.cwd(),i)}`):i},b=(e,r,o,s)=>{let{optimize:l}=e.build,u=e.build.importMode??e.dictionary?.importMode,{dictionariesDir:d,unmergedDictionariesDir:p,dynamicDictionariesDir:m,fetchDictionariesDir:h,mainDir:g}=e.system,{baseDir:b}=e.content,x=(0,a.getAppLogger)(e);if(l===!1||l===void 0&&!r||!f)return{};let S=_(e);if((0,i.runOnce)((0,n.join)(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[(0,a.colorize)(`Recommended: Install`,a.ANSIColors.GREY),(0,a.colorize)(`@intlayer/swc`,a.ANSIColors.GREY_LIGHT),(0,a.colorize)(`package to enable build optimization. See documentation: `,a.ANSIColors.GREY),(0,a.colorize)(`https://intlayer.org/docs/en/bundle_optimization`,a.ANSIColors.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),(0,i.runOnce)((0,n.join)(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(v(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,i.getComponentTransformPatternSync)(e),C,T],O=(0,c.getDictionaries)(e),k={};return Object.values(O).forEach(e=>{k[e.key]=e.importMode??u??t.DefaultValues.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[y(`@intlayer/swc`,e,o),{dictionariesDir:d,dictionariesEntryPath:C,unmergedDictionariesEntryPath:T,unmergedDictionariesDir:p,dynamicDictionariesDir:m,dynamicDictionariesEntryPath:w,fetchDictionariesDir:h,fetchDictionariesEntryPath:E,importMode:u,filesList:D,replaceDictionaryEntry:!0,dictionaryModeMap:k}]]}}},x=()=>{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)}},S=(e={},t)=>{typeof e!=`object`&&(e={});let r=(0,o.getConfiguration)(t),i=(0,a.getAppLogger)(r),c=t?.enableTurbopack??g;c&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:d,isDevCommand:m}=x(),_={resolveAlias:(0,s.getAlias)({configuration:r,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},v=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],y=()=>{let t={};return p&&(t={...t,serverExternalPackages:v}),f&&!p&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:v}}),t=c?p&&h?{...t,turbopack:_}:{...t,experimental:{...t?.experimental??{},turbo:_}}:{...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,s.getAlias)({configuration:r,formatter:e=>(0,n.resolve)(e)})},m&&a&&o===`nodejs`&&t.plugins.push(new l.IntlayerPlugin(r)),t}},t},S=b(r,d,c??!1,m);return(0,u.defu)((0,u.defu)(y(),S),e)},C=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:i}=x();process.env.INTLAYER_IS_DEV_COMMAND=i?`true`:`false`;let a=(0,o.getConfiguration)(t),{mode:s}=a.build;return(i||n||s===`auto`)&&await(0,r.prepareIntlayer)(a,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60}),S(await e,t)};exports.withIntlayer=C,exports.withIntlayerSync=S;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`node:path`),n=require(`@intlayer/chokidar/build`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/config/client`),a=require(`@intlayer/config/logger`),o=require(`@intlayer/config/node`),s=require(`@intlayer/config/utils`),c=require(`@intlayer/dictionaries-entry`),l=require(`@intlayer/webpack`),u=require(`defu`),d=require(`next/package.json`);d=e.__toESM(d);const f=(0,s.compareVersions)(d.default.version,`≥`,`13.0.0`),p=(0,s.compareVersions)(d.default.version,`≥`,`15.0.0`),m=(0,s.compareVersions)(d.default.version,`≥`,`16.0.0`),h=(0,s.compareVersions)(d.default.version,`≥`,`15.3.0`),g=m?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),_=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/swc`),!0}catch{return!1}},v=e=>{try{return(e.build?.require??(0,s.getProjectRequire)()).resolve(`@intlayer/babel`),!0}catch{return!1}},y=(e,n,r)=>{let i=(n.build?.require??(0,s.getProjectRequire)())?.resolve(e);return r?(0,s.normalizePath)(`./${(0,t.relative)(process.cwd(),i)}`):i},b=(e,n,o,s)=>{let{optimize:l}=e.build,u=e.build.importMode??e.dictionary?.importMode,{dictionariesDir:d,unmergedDictionariesDir:p,dynamicDictionariesDir:m,fetchDictionariesDir:h,mainDir:g}=e.system,{baseDir:b}=e.content,x=(0,a.getAppLogger)(e);if(l===!1||l===void 0&&!n||!f)return{};let S=_(e);if((0,r.runOnce)((0,t.join)(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[(0,a.colorize)(`Recommended: Install`,a.ANSIColors.GREY),(0,a.colorize)(`@intlayer/swc`,a.ANSIColors.GREY_LIGHT),(0,a.colorize)(`package to enable build optimization. See documentation: `,a.ANSIColors.GREY),(0,a.colorize)(`https://intlayer.org/docs/en/bundle_optimization`,a.ANSIColors.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),(0,r.runOnce)((0,t.join)(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(v(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,t.join)(g,`dictionaries.mjs`),w=(0,t.join)(g,`dynamic_dictionaries.mjs`),T=(0,t.join)(g,`unmerged_dictionaries.mjs`),E=(0,t.join)(g,`fetch_dictionaries.mjs`),D=[...(0,r.getComponentTransformPatternSync)(e),C,T],O=(0,c.getDictionaries)(e),k={};return Object.values(O).forEach(e=>{k[e.key]=e.importMode??u??i.DefaultValues.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[y(`@intlayer/swc`,e,o),{dictionariesDir:d,dictionariesEntryPath:C,unmergedDictionariesEntryPath:T,unmergedDictionariesDir:p,dynamicDictionariesDir:m,dynamicDictionariesEntryPath:w,fetchDictionariesDir:h,fetchDictionariesEntryPath:E,importMode:u,filesList:D,replaceDictionaryEntry:!0,dictionaryModeMap:k}]]}}},x=()=>{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)}},S=(e={},n)=>{typeof e!=`object`&&(e={});let r=(0,o.getConfiguration)(n),i=(0,a.getAppLogger)(r),c=n?.enableTurbopack??g;c&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:d,isDevCommand:m}=x(),_={resolveAlias:(0,s.getAlias)({configuration:r,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},v=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],y=()=>{let n={};return p&&(n={...n,serverExternalPackages:v}),f&&!p&&(n={...n,experimental:{...n?.experimental??{},serverComponentsExternalPackages:v}}),n=c?p&&h?{...n,turbopack:_}:{...n,experimental:{...n?.experimental??{},turbo:_}}:{...n,webpack:(n,i)=>{let{isServer:a,nextRuntime:o}=i;return typeof e.webpack==`function`&&(n=e.webpack(n,i)),n.externals===!1&&(n.externals=[]),n.externals.push({esbuild:`esbuild`,module:`module`,fs:`fs`,chokidar:`chokidar`,fsevents:`fsevents`}),n.module.rules.push({test:/\.node$/,loader:`node-loader`}),n.resolve.alias={...n.resolve.alias,...(0,s.getAlias)({configuration:r,formatter:e=>(0,t.resolve)(e)})},m&&a&&o===`nodejs`&&n.plugins.push(new l.IntlayerPlugin(r)),n}},n},S=b(r,d,c??!1,m);return(0,u.defu)((0,u.defu)(y(),S),e)},C=async(e={},t)=>{let{isBuildCommand:r,isDevCommand:i,isStartCommand:a}=x();process.env.INTLAYER_IS_DEV_COMMAND=i?`true`:`false`;let s=(0,o.getConfiguration)(t),{mode:c}=s.build;return!a&&(i||r||c===`auto`)&&await(0,n.prepareIntlayer)(s,{clean:r,cacheTimeoutMs:r?1e3*30:1e3*60*60}),S(await e,t)};exports.withIntlayer=C,exports.withIntlayerSync=S;
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 {\n getComponentTransformPatternSync,\n runOnce,\n} 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 { Dictionary, IntlayerConfig } from '@intlayer/types';\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.content;\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/en/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 = getComponentTransformPatternSync(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 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 } = 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 (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 });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"yfA0BA,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,GADkB,EAAe,OAAO,UAAA,EAAA,EAAA,oBAA8B,GAChC,QAAQ,EAAW,CAO/D,OALI,GAEF,EAAA,EAAA,eAAqB,MAAA,EAAA,EAAA,UAAc,QAAQ,KAAK,CAAE,EAAmB,GAAG,CAG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B,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GACjB,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
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 {\n getComponentTransformPatternSync,\n runOnce,\n} 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 { Dictionary, IntlayerConfig } from '@intlayer/types';\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.content;\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/en/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 = getComponentTransformPatternSync(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 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 });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"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,EAAO,UAAY,EAAE,EAIvB,EAAO,UAAU,KAAK,CACpB,QAAS,UACT,OAAQ,SACR,GAAI,KACJ,SAAU,WACV,SAAU,WACX,CAAC,CAGF,EAAO,OAAO,MAAM,KAAK,CACvB,KAAM,UACN,OAAQ,cACT,CAAC,CAIF,EAAO,QAAQ,MAAQ,CACrB,GAAG,EAAO,QAAQ,MAClB,IAAA,EAAA,EAAA,UAAY,CACV,cAAe,EACf,UAAY,IAAA,EAAA,EAAA,SAA0B,EAAM,CAC7C,CAAC,CACH,CAGG,GAAgB,GAAY,IAAgB,UAE9C,EAAO,QAAQ,KAAK,IAAIC,EAAAA,eAAe,EAAe,CAAC,CAGlD,GAEV,CAGI,GAGH,EAAmC,EACvC,EACA,EACA,GAAsB,GACtB,EACD,CAUD,OAAA,EAAA,EAAA,OAAA,EAAA,EAAA,MAPE,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,GAAA,EAAA,EAAA,kBAAkC,EAAc,CAEhD,CAAE,QAAS,EAAe,MAiBhC,MAZI,CAAC,IAAmB,GAAgB,GAAkB,IAAS,SAEjE,MAAA,EAAA,EAAA,iBAAsB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GACjB,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
@@ -1,2 +1,2 @@
1
- import{localeDetector as e}from"./localeDetector.mjs";import t from"@intlayer/config/built";import{getCanonicalPath as n,getLocalizedPath as r,getRewriteRules as i}from"@intlayer/core/localization";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}=t??{},{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=i(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=(e,t,r)=>{let i=E(r),a=t??f;if(i){let t=n(r.slice(`/${i}`.length)||`/`,i,b),a=S(e.nextUrl.search,i);return P(e,a?`${t}${a}`:`${t}${e.nextUrl.search??``}`)}let o=n(r,a,b);if(g===`search-params`){if(new URLSearchParams(e.nextUrl.search).get(`locale`)===a)return N(e,`${y?`/${a}${o}`:o}${e.nextUrl.search??``}`,a);let t=S(e.nextUrl.search,a);return P(e,t?`${r}${t}`:`${r}${e.nextUrl.search??``}`)}let s=y?`/${a}${o}`:o,c=S(e.nextUrl.search,a);return N(e,c?`${s}${c}`:`${s}${e.nextUrl.search??``}`,a)},E=e=>d.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),D=(e,t,n,r)=>n?k(e,t,n,r):x(e)?O(e,f,r):O(e,t,r),O=(t,i,a)=>{let o=i??e?.(t)??f;d.includes(o)||(o=f);let s=n(a,o,b),c=r(s,o,b),l=typeof c==`string`?c:c.path,u=M(o,l,p,S(t.nextUrl.search,o));return v||o!==f?P(t,u):N(t,y?`/${o}${s}`:s,o)},k=(e,t,i,a)=>{let o=a.slice(`/${i}`.length)||`/`,s=n(o,i,b);if(t&&t!==i)return P(e,A(e,s,t,p));let c=r(s,i,b),l=typeof c==`string`?c:c.path;if(typeof c!=`string`&&c.isRewritten&&l!==o)return P(e,M(i,l,p,S(e.nextUrl.search,i)));let u=y?`/${i}${s}`:s;if(!v&&i===f)return j(e,i,a);let d=e.nextUrl.search;return N(e,u+(d??``),i)},A=(e,t,n,i)=>{let a=r(t,n,b);return M(n,typeof a==`string`?a:a.path,i,S(e.nextUrl.search,n))},j=(e,t,n)=>{if(!v&&t===f){let i=r(n,t,b),a=typeof i==`string`?i:i.path,o=p.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),P(e,`${p}${o?``:`/`}${s}`+(S(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=S(e.nextUrl.search,t),a=y?`/${t}${n}`:n;return N(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},M=(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,`/`)},N=(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=c.rewrite(new URL(i,e.url),{request:{headers:a}});return s(n,{setHeader:(e,t)=>{o.headers.set(e,t)}}),o},P=(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 t from"@intlayer/config/built";import{getCanonicalPath as n,getLocalizedPath as r,getRewriteRules as i}from"@intlayer/core/localization";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}=t??{},{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=i(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=(t,r,i)=>{let a=E(i);if(a){let e=n(i.slice(`/${a}`.length)||`/`,a,b),r=S(t.nextUrl.search,a);return P(t,r?`${e}${r}`:`${e}${t.nextUrl.search??``}`)}if(g===`search-params`){let a=new URLSearchParams(t.nextUrl.search).get(`locale`),o=d?.includes(a),s=r??(o?a:void 0)??e?.(t)??f;d?.includes(s)||(s=f);let c=n(i,s,b);if(a===s)return N(t,`${y?`/${s}${c}`:c}${t.nextUrl.search??``}`,s);let l=S(t.nextUrl.search,s);return P(t,l?`${i}${l}`:`${i}${t.nextUrl.search??``}`)}let o=r??e?.(t)??f;d?.includes(o)||(o=f);let s=n(i,o,b),c=y?`/${o}${s}`:s,l=S(t.nextUrl.search,o);return N(t,l?`${c}${l}`:`${c}${t.nextUrl.search??``}`,o)},E=e=>d.find(t=>e.startsWith(`/${t}/`)||e===`/${t}`),D=(e,t,n,r)=>n?k(e,t,n,r):x(e)?O(e,f,r):O(e,t,r),O=(t,i,a)=>{let o=i??e?.(t)??f;d.includes(o)||(o=f);let s=n(a,o,b),c=r(s,o,b),l=typeof c==`string`?c:c.path,u=M(o,l,p,S(t.nextUrl.search,o));return v||o!==f?P(t,u):N(t,y?`/${o}${s}`:s,o)},k=(e,t,i,a)=>{let o=a.slice(`/${i}`.length)||`/`,s=n(o,i,b);if(t&&t!==i)return P(e,A(e,s,t,p));let c=r(s,i,b),l=typeof c==`string`?c:c.path;if(typeof c!=`string`&&c.isRewritten&&l!==o)return P(e,M(i,l,p,S(e.nextUrl.search,i)));let u=y?`/${i}${s}`:s;if(!v&&i===f)return j(e,i,a);let d=e.nextUrl.search;return N(e,u+(d??``),i)},A=(e,t,n,i)=>{let a=r(t,n,b);return M(n,typeof a==`string`?a:a.path,i,S(e.nextUrl.search,n))},j=(e,t,n)=>{if(!v&&t===f){let i=r(n,t,b),a=typeof i==`string`?i:i.path,o=p.endsWith(`/`),s=a;return s.startsWith(`/`)&&(s=s.slice(1)),P(e,`${p}${o?``:`/`}${s}`+(S(e.nextUrl.search,t)??e.nextUrl.search??``))}let i=S(e.nextUrl.search,t),a=y?`/${t}${n}`:n;return N(e,i?`${a}${i}`:`${a}${e.nextUrl.search??``}`,t)},M=(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,`/`)},N=(e,t,n)=>{let r=e.nextUrl.search,i=r&&!t.includes(`?`)?`${t}${r}`:t;console.log(`[intlayerProxy] Rewriting to ${i} with locale ${n}`);let 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},P=(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';\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 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 const locale = localLocale ?? defaultLocale;\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 // Resolve the internal canonical path\n // If user visits /a-propos (no prefix), and we detect 'fr', we resolve to /about\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (effectiveMode === 'search-params') {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\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 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, localLocale, 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 localLocale: Locale | undefined,\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 if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\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 */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\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 response = NextResponse.rewrite(new URL(pathWithSearch, request.url), {\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 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,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,CACz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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,EAAW,EAAa,QAAQ,IAAI,IAAI,EAAgB,EAAQ,IAAI,CAAE,CAC1E,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAOF,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,EAC7D,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 { 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';\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 const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\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, localLocale, 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 localLocale: Locale | undefined,\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 if (localLocale && localLocale !== pathLocale) {\n // Cookie mismatch: Redirect to the correct locale using the Canonical Path as the source\n const newPath = handleCookieLocaleMismatch(\n request,\n canonicalPath, // Pass /about\n localLocale,\n basePath as string\n );\n return redirectUrl(request, newPath);\n }\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 */\nconst handleCookieLocaleMismatch = (\n request: NextRequest,\n canonicalPath: string,\n localLocale: Locale,\n basePath: string\n): string => {\n // Translate canonical path (/about) to target locale path (/es/acerca)\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n localLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n return constructPath(\n localLocale,\n targetLocalizedPath,\n basePath,\n appendLocaleSearchIfNeeded(request.nextUrl.search, localLocale)\n );\n};\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 console.log(\n `[intlayerProxy] Rewriting to ${pathWithSearch} with locale ${locale}`\n );\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,EAAiB,CAAC,EAElB,EAAe,EAAgB,EAAS,MAAM,CAgB9C,EA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,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{NextResponse as e}from"next/server";const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers;a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.rewrite(new URL(l,n.url),{request:{headers:s}}):e.next({request:{headers:s}})};export{t as multipleProxies};
1
+ import{NextResponse as e}from"next/server";const t=t=>async(n,r,i)=>{let a=[];for(let e of t){let t=await e(n,r,i);if(!t.ok)return t;a.push(t.headers)}let o=new Headers,s=new Headers(n.headers);a.forEach(e=>{for(let[t,n]of e.entries())if(o.append(t,n),t.startsWith(`x-middleware-request-`)){let e=t.replace(`x-middleware-request-`,``);s.append(e,n)}});let c=o.get(`x-middleware-request-redirect`);if(c)return e.redirect(new URL(c,n.url),{status:307});let l=o.get(`x-middleware-rewrite`);return l?e.rewrite(new URL(l,n.url),{request:{headers:s}}):e.next({request:{headers:s}})};export{t as multipleProxies};
2
2
  //# sourceMappingURL=multipleProxies.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"multipleProxies.mjs","names":[],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push proxy headers to the array\n proxyHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the proxies\n const transmittedHeaders = new Headers();\n\n // Merge headers\n proxyHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the proxies\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the proxy headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"2CA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAG/B,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAO,EAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEK,EAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIG,EAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
1
+ {"version":3,"file":"multipleProxies.mjs","names":[],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, merges headers, and correctly handles\n * redirects and rewrites.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Array to store proxy headers\n const proxyHeader: Headers[] = [];\n\n // Loop through proxy functions\n for (const proxy of proxies) {\n // Execute proxy function and await the result\n const result = await proxy(req, event, response);\n\n // Check if the result is not okay and return it\n if (!result.ok) {\n return result;\n }\n\n // Push proxy headers to the array\n proxyHeader.push(result.headers);\n }\n\n // Merge all the headers to check if there is a redirection or rewrite\n const mergedHeaders = new Headers();\n\n // Merge all the custom headers added by the proxies\n const transmittedHeaders = new Headers(req.headers);\n\n // Merge headers\n proxyHeader.forEach((header) => {\n for (const [key, value] of header.entries()) {\n mergedHeaders.append(key, value);\n\n // check if it's a custom header added by one of the proxies\n if (key.startsWith('x-middleware-request-')) {\n // remove the prefix to get the original key\n const fixedKey = key.replace('x-middleware-request-', '');\n\n // add the original key to the transmitted headers\n transmittedHeaders.append(fixedKey, value);\n }\n }\n });\n\n // Look for the 'x-middleware-request-redirect' header\n const redirect = mergedHeaders.get('x-middleware-request-redirect');\n\n // If a redirection is required based on the proxy headers\n if (redirect) {\n // Perform the redirection\n return NextResponse.redirect(new URL(redirect, req.url), {\n status: 307, // Temporary redirect\n });\n }\n\n // Look for the 'x-middleware-rewrite' header\n const rewrite = mergedHeaders.get('x-middleware-rewrite');\n if (rewrite) {\n // Perform the rewrite\n return NextResponse.rewrite(new URL(rewrite, req.url), {\n request: {\n headers: transmittedHeaders,\n },\n });\n }\n\n // Default: continue to next proxy\n return NextResponse.next({\n request: {\n headers: transmittedHeaders,\n },\n });\n };\n"],"mappings":"2CA+BA,MAAa,EAET,GAMF,MAAO,EAAkB,EAAwB,IAA4B,CAE3E,IAAM,EAAyB,EAAE,CAGjC,IAAK,IAAM,KAAS,EAAS,CAE3B,IAAM,EAAS,MAAM,EAAM,EAAK,EAAO,EAAS,CAGhD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,EAAY,KAAK,EAAO,QAAQ,CAIlC,IAAM,EAAgB,IAAI,QAGpB,EAAqB,IAAI,QAAQ,EAAI,QAAQ,CAGnD,EAAY,QAAS,GAAW,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,SAAS,CAIzC,GAHA,EAAc,OAAO,EAAK,EAAM,CAG5B,EAAI,WAAW,wBAAwB,CAAE,CAE3C,IAAM,EAAW,EAAI,QAAQ,wBAAyB,GAAG,CAGzD,EAAmB,OAAO,EAAU,EAAM,GAG9C,CAGF,IAAM,EAAW,EAAc,IAAI,gCAAgC,CAGnE,GAAI,EAEF,OAAO,EAAa,SAAS,IAAI,IAAI,EAAU,EAAI,IAAI,CAAE,CACvD,OAAQ,IACT,CAAC,CAIJ,IAAM,EAAU,EAAc,IAAI,uBAAuB,CAWzD,OAVI,EAEK,EAAa,QAAQ,IAAI,IAAI,EAAS,EAAI,IAAI,CAAE,CACrD,QAAS,CACP,QAAS,EACV,CACF,CAAC,CAIG,EAAa,KAAK,CACvB,QAAS,CACP,QAAS,EACV,CACF,CAAC"}
@@ -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{getComponentTransformPatternSync as a,runOnce as o}from"@intlayer/chokidar/utils";import{ANSIColors as s,colorize as c,getAppLogger as l}from"@intlayer/config/logger";import{getConfiguration as u}from"@intlayer/config/node";import{compareVersions as d,getAlias as f,getProjectRequire as p,normalizePath as m}from"@intlayer/config/utils";import{getDictionaries as h}from"@intlayer/dictionaries-entry";import{IntlayerPlugin as g}from"@intlayer/webpack";import{defu as _}from"defu";import v from"next/package.json"with{type:"json"};const y=d(v.version,`≥`,`13.0.0`),b=d(v.version,`≥`,`15.0.0`),x=d(v.version,`≥`,`16.0.0`),S=d(v.version,`≥`,`15.3.0`),C=x?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),w=e=>{try{return(e.build?.require??p()).resolve(`@intlayer/swc`),!0}catch{return!1}},T=e=>{try{return(e.build?.require??p()).resolve(`@intlayer/babel`),!0}catch{return!1}},E=(e,t,r)=>{let i=(t.build?.require??p())?.resolve(e);return r?m(`./${n(process.cwd(),i)}`):i},D=(n,r,i,u)=>{let{optimize:d}=n.build,f=n.build.importMode??n.dictionary?.importMode,{dictionariesDir:p,unmergedDictionariesDir:m,dynamicDictionariesDir:g,fetchDictionariesDir:_,mainDir:v}=n.system,{baseDir:b}=n.content,x=l(n);if(d===!1||d===void 0&&!r||!y)return{};let S=w(n);if(o(t(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[c(`Recommended: Install`,s.GREY),c(`@intlayer/swc`,s.GREY_LIGHT),c(`package to enable build optimization. See documentation: `,s.GREY),c(`https://intlayer.org/docs/en/bundle_optimization`,s.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),o(t(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(T(n)){let e=n.compiler?.enabled??!0;e===`build-only`&&(e=!u),x(e?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!S)return{};let C=t(v,`dictionaries.mjs`),D=t(v,`dynamic_dictionaries.mjs`),O=t(v,`unmerged_dictionaries.mjs`),k=t(v,`fetch_dictionaries.mjs`),A=[...a(n),C,O],j=h(n),M={};return Object.values(j).forEach(t=>{M[t.key]=t.importMode??f??e.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[E(`@intlayer/swc`,n,i),{dictionariesDir:p,dictionariesEntryPath:C,unmergedDictionariesEntryPath:O,unmergedDictionariesDir:m,dynamicDictionariesDir:g,dynamicDictionariesEntryPath:D,fetchDictionariesDir:_,fetchDictionariesEntryPath:k,importMode:f,filesList:A,replaceDictionaryEntry:!0,dictionaryModeMap:M}]]}}},O=()=>{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)}},k=(e={},t)=>{typeof e!=`object`&&(e={});let n=u(t),i=l(n),a=t?.enableTurbopack??C;a&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:o,isDevCommand:s}=O(),c={resolveAlias:f({configuration:n,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},d=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],p=()=>{let t={};return b&&(t={...t,serverExternalPackages:d}),y&&!b&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:d}}),t=a?b&&S?{...t,turbopack:c}:{...t,experimental:{...t?.experimental??{},turbo:c}}:{...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,...f({configuration:n,formatter:e=>r(e)})},s&&a&&o===`nodejs`&&t.plugins.push(new g(n)),t}},t},m=D(n,o,a??!1,s);return _(_(p(),m),e)},A=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:r}=O();process.env.INTLAYER_IS_DEV_COMMAND=r?`true`:`false`;let a=u(t),{mode:o}=a.build;return(r||n||o===`auto`)&&await i(a,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60}),k(await e,t)};export{A as withIntlayer,k as withIntlayerSync};
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{getComponentTransformPatternSync as a,runOnce as o}from"@intlayer/chokidar/utils";import{ANSIColors as s,colorize as c,getAppLogger as l}from"@intlayer/config/logger";import{getConfiguration as u}from"@intlayer/config/node";import{compareVersions as d,getAlias as f,getProjectRequire as p,normalizePath as m}from"@intlayer/config/utils";import{getDictionaries as h}from"@intlayer/dictionaries-entry";import{IntlayerPlugin as g}from"@intlayer/webpack";import{defu as _}from"defu";import v from"next/package.json"with{type:"json"};const y=d(v.version,`≥`,`13.0.0`),b=d(v.version,`≥`,`15.0.0`),x=d(v.version,`≥`,`16.0.0`),S=d(v.version,`≥`,`15.3.0`),C=x?!process.env.npm_lifecycle_script?.includes(`--webpack`):process.env.npm_lifecycle_script?.includes(`--turbo`),w=e=>{try{return(e.build?.require??p()).resolve(`@intlayer/swc`),!0}catch{return!1}},T=e=>{try{return(e.build?.require??p()).resolve(`@intlayer/babel`),!0}catch{return!1}},E=(e,t,r)=>{let i=(t.build?.require??p())?.resolve(e);return r?m(`./${n(process.cwd(),i)}`):i},D=(n,r,i,u)=>{let{optimize:d}=n.build,f=n.build.importMode??n.dictionary?.importMode,{dictionariesDir:p,unmergedDictionariesDir:m,dynamicDictionariesDir:g,fetchDictionariesDir:_,mainDir:v}=n.system,{baseDir:b}=n.content,x=l(n);if(d===!1||d===void 0&&!r||!y)return{};let S=w(n);if(o(t(b,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>{x(S?`Build optimization enabled`:[c(`Recommended: Install`,s.GREY),c(`@intlayer/swc`,s.GREY_LIGHT),c(`package to enable build optimization. See documentation: `,s.GREY),c(`https://intlayer.org/docs/en/bundle_optimization`,s.GREY_LIGHT)])},{cacheTimeoutMs:1e3*30}),o(t(b,`.intlayer`,`cache`,`intlayer-compiler-plugin-enabled.lock`),()=>{if(T(n)){let e=n.compiler?.enabled??!0;e===`build-only`&&(e=!u),x(e?`Intlayer compiler enabled`:`Intlayer compiler disabled`)}},{cacheTimeoutMs:1e3*30}),!S)return{};let C=t(v,`dictionaries.mjs`),D=t(v,`dynamic_dictionaries.mjs`),O=t(v,`unmerged_dictionaries.mjs`),k=t(v,`fetch_dictionaries.mjs`),A=[...a(n),C,O],j=h(n),M={};return Object.values(j).forEach(t=>{M[t.key]=t.importMode??f??e.Dictionary.IMPORT_MODE}),{experimental:{swcPlugins:[[E(`@intlayer/swc`,n,i),{dictionariesDir:p,dictionariesEntryPath:C,unmergedDictionariesEntryPath:O,unmergedDictionariesDir:m,dynamicDictionariesDir:g,dynamicDictionariesEntryPath:D,fetchDictionariesDir:_,fetchDictionariesEntryPath:k,importMode:f,filesList:A,replaceDictionaryEntry:!0,dictionaryModeMap:M}]]}}},O=()=>{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)}},k=(e={},t)=>{typeof e!=`object`&&(e={});let n=u(t),i=l(n),a=t?.enableTurbopack??C;a&&e.webpack!==void 0&&i(`Turbopack is enabled but a custom webpack config is present. It will be ignored.`);let{isBuildCommand:o,isDevCommand:s}=O(),c={resolveAlias:f({configuration:n,formatter:e=>`./${e}`}),rules:{"*.node":{as:`*.node`,loaders:[`node-loader`]}}},d=[`esbuild`,`module`,`fs`,`chokidar`,`fsevents`],p=()=>{let t={};return b&&(t={...t,serverExternalPackages:d}),y&&!b&&(t={...t,experimental:{...t?.experimental??{},serverComponentsExternalPackages:d}}),t=a?b&&S?{...t,turbopack:c}:{...t,experimental:{...t?.experimental??{},turbo:c}}:{...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,...f({configuration:n,formatter:e=>r(e)})},s&&a&&o===`nodejs`&&t.plugins.push(new g(n)),t}},t},m=D(n,o,a??!1,s);return _(_(p(),m),e)},A=async(e={},t)=>{let{isBuildCommand:n,isDevCommand:r,isStartCommand:a}=O();process.env.INTLAYER_IS_DEV_COMMAND=r?`true`:`false`;let o=u(t),{mode:s}=o.build;return!a&&(r||n||s===`auto`)&&await i(o,{clean:n,cacheTimeoutMs:n?1e3*30:1e3*60*60}),k(await e,t)};export{A as withIntlayer,k 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 {\n getComponentTransformPatternSync,\n runOnce,\n} 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 { Dictionary, IntlayerConfig } from '@intlayer/types';\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.content;\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/en/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 = getComponentTransformPatternSync(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 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 } = 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 (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 });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"usBA0BA,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,MAAO,KAKL,EAAoC,GAAmC,CAC3E,GAAI,CAIF,OAFE,EAAe,OAAO,SAAW,GAAmB,EACtC,QAAQ,kBAAkB,CACnC,QACI,CACX,MAAO,KAIL,GACJ,EACA,EACA,IACW,CAEX,IAAM,GADkB,EAAe,OAAO,SAAW,GAAmB,GAChC,QAAQ,EAAW,CAO/D,OALI,EAEK,EAAc,KAAK,EAAS,QAAQ,KAAK,CAAE,EAAmB,GAAG,CAGnE,G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E,CAE9B,MAAO,EACR,CACF,CAGM,CACP,GAAG,EACH,SAAU,EAA4B,IAA8B,CAElE,GAAM,CAAE,WAAU,eAAgB,EA4ClC,OAzCI,OAAO,EAAW,SAAY,aAChC,EAAS,EAAW,QAAQ,EAAQ,EAAQ,EAK1C,EAAO,YAAc,KACvB,EAAO,UAAY,EAAE,EAIvB,EAAO,UAAU,KAAK,CACpB,QAAS,UACT,OAAQ,SACR,GAAI,KACJ,SAAU,WACV,SAAU,WACX,CAAC,CAGF,EAAO,OAAO,MAAM,KAAK,CACvB,KAAM,UACN,OAAQ,cACT,CAAC,CAIF,EAAO,QAAQ,MAAQ,CACrB,GAAG,EAAO,QAAQ,MAClB,GAAG,EAAS,CACV,cAAe,EACf,UAAY,GAAkB,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,EACD,CAUD,OAFe,EANiC,EAC9C,GAAc,CACd,EACD,CAGuC,EAAW,EAoBxC,EAAe,MAC1B,EAA6B,EAAE,CAC/B,IAC4B,CAC5B,GAAM,CAAE,iBAAgB,gBAAiB,GAAkB,CAE3D,QAAQ,IAAI,wBAA0B,EAAe,OAAS,QAE9D,IAAM,EAAiB,EAAiB,EAAc,CAEhD,CAAE,QAAS,EAAe,MAiBhC,OAZI,GAAgB,GAAkB,IAAS,SAE7C,MAAM,EAAgB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GACjB,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 {\n getComponentTransformPatternSync,\n runOnce,\n} 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 { Dictionary, IntlayerConfig } from '@intlayer/types';\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.content;\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/en/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 = getComponentTransformPatternSync(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 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 });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":"usBA0BA,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,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Ac,CAEhD,CAAE,QAAS,EAAe,MAiBhC,MAZI,CAAC,IAAmB,GAAgB,GAAkB,IAAS,SAEjE,MAAM,EAAgB,EAAgB,CACpC,MAAO,EACP,eAAgB,EACZ,IAAO,GACP,IAAO,GAAK,GACjB,CAAC,CAKG,EAFoB,MAAM,EAEW,EAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-intlayer",
3
- "version": "8.1.6",
3
+ "version": "8.1.8",
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": [
@@ -107,7 +107,6 @@
107
107
  "./package.json"
108
108
  ],
109
109
  "scripts": {
110
- "_prepublish": "cp -f ../../README.md ./README.md",
111
110
  "build": "tsdown --config tsdown.config.ts",
112
111
  "build:ci": "tsdown --config tsdown.config.ts",
113
112
  "clean": "rimraf ./dist .turbo",
@@ -116,7 +115,7 @@
116
115
  "format:fix": "biome format --write .",
117
116
  "lint": "biome lint .",
118
117
  "lint:fix": "biome lint --write .",
119
- "prepublish": "echo prepublish temporally disabled to avoid rewrite readme",
118
+ "prepublish": "cp -f ../../README.md ./README.md",
120
119
  "publish": "bun publish || true",
121
120
  "publish:canary": "bun publish --access public --tag canary || true",
122
121
  "publish:latest": "bun publish --access public --tag latest || true",
@@ -125,15 +124,15 @@
125
124
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
126
125
  },
127
126
  "dependencies": {
128
- "@intlayer/chokidar": "8.1.6",
129
- "@intlayer/config": "8.1.6",
130
- "@intlayer/core": "8.1.6",
131
- "@intlayer/dictionaries-entry": "8.1.6",
132
- "@intlayer/types": "8.1.6",
133
- "@intlayer/webpack": "8.1.6",
127
+ "@intlayer/chokidar": "8.1.8",
128
+ "@intlayer/config": "8.1.8",
129
+ "@intlayer/core": "8.1.8",
130
+ "@intlayer/dictionaries-entry": "8.1.8",
131
+ "@intlayer/types": "8.1.8",
132
+ "@intlayer/webpack": "8.1.8",
134
133
  "defu": "6.1.4",
135
134
  "node-loader": "2.1.0",
136
- "react-intlayer": "8.1.6"
135
+ "react-intlayer": "8.1.8"
137
136
  },
138
137
  "devDependencies": {
139
138
  "@types/node": "25.3.0",