@intlayer/babel 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`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:fs`),t=require(`node:path`);require(`@babel/generator`);let n=require(`@intlayer/chokidar/cli`),r=require(`@intlayer/core/utils`);const i=(e,n=`comp-`)=>{let r=(0,t.basename)(e,(0,t.extname)(e));return r===`index`&&(r=(0,t.basename)((0,t.dirname)(e))),`${n}${r.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}`},a=n=>{let r=n;for(;;){let n=(0,t.join)(r,`package.json`);if((0,e.existsSync)(n))try{let t=JSON.parse((0,e.readFileSync)(n,`utf-8`));if(t.dependencies?.[`next-intlayer`]||t.devDependencies?.[`next-intlayer`])return`next-intlayer`;if(t.dependencies?.[`react-intlayer`]||t.devDependencies?.[`react-intlayer`])return`react-intlayer`;if(t.dependencies?.[`preact-intlayer`]||t.devDependencies?.[`preact-intlayer`])return`preact-intlayer`}catch{}let i=(0,t.dirname)(r);if(i===r)break;r=i}return`react-intlayer`},o=(e,t)=>{let n=e;for(;t.isParenthesizedExpression(n);)n=n.expression;return n},s=(e,t)=>{let n=e.node;if(!t.isBlockStatement(n.body)){let e=o(n.body,t);return t.isJSXElement(e)||t.isJSXFragment(e)}let r=!1;return e.traverse({Function(e){e.skip()},ReturnStatement(e){if(e.node.argument){let n=o(e.node.argument,t);(t.isJSXElement(n)||t.isJSXFragment(n))&&(r=!0)}}}),r},c=(e,t)=>{let n=e.getFunctionParent();if(!n)return null;let r=n;for(;r;){if(s(r,t))return r;r=r.getFunctionParent()}return n},l=e=>{let{types:o}=e;return{name:`babel-plugin-intlayer-extract`,pre(){this._extractedContent={},this._existingKeys=new Set,this._isIncluded=!0,this._hasJSX=!1,this._hasUseIntlayerImport=!1,this._useIntlayerLocalName=`useIntlayer`,this._hasGetIntlayerImport=!1,this._getIntlayerLocalName=`getIntlayer`,this._contentVarName=`content`,this._isClient=!1,this._hasTopLevelContent=!1;let e=this.file.opts.filename;if(!this.opts.packageName){let n=e?(0,t.dirname)(e):process.cwd();this.opts.packageName=a(n)}if(!(this.opts.enabled??!0)){this._isIncluded=!1;return}if(this.opts.filesList&&e){let t=e.replace(/\\/g,`/`);this._isIncluded=this.opts.filesList.some(e=>e.replace(/\\/g,`/`)===t)}e&&(this._dictionaryKey=i(e,this.opts.prefix))},visitor:{ImportDeclaration(e,t){if(t._isIncluded)for(let n of e.node.specifiers){if(!o.isImportSpecifier(n))continue;let e=o.isIdentifier(n.imported)?n.imported.name:n.imported.value;e===`useIntlayer`&&(t._hasUseIntlayerImport=!0,t._useIntlayerLocalName=n.local.name),e===`getIntlayer`&&(t._hasGetIntlayerImport=!0,t._getIntlayerLocalName=n.local.name)}},JSXElement(e,t){t._isIncluded&&(t._hasJSX=!0)},Program:{enter(e,t){if(!t._isIncluded)return;t._isClient=e.node.directives.some(e=>e.value.value===`use client`);let n=!1;e.traverse({VariableDeclarator(e){o.isIdentifier(e.node.id)&&e.node.id.name===`content`&&(n=!0)}}),t._contentVarName=n?`_compContent`:`content`},exit(e,t){if(!t._isIncluded||!t._dictionaryKey)return;let i=[],a=new Set,l=t.opts.shouldExtract??n.shouldExtract,d=e=>{let n=c(e,o);n?a.add(n):t._hasTopLevelContent=!0};if(e.traverse({JSXText(e){let n=e.node.value;if(l(n)){let a=n.replace(/\s+/g,` `).trim(),o=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===a);o||(o=(0,r.generateKey)(a,t._existingKeys),t._existingKeys.add(o),t._extractedContent[o]=a),i.push({path:e,key:o,isAttribute:!1}),d(e)}},JSXAttribute(e){let a=e.node.name;if(!o.isJSXIdentifier(a))return;let s=a.name===`key`;if(!n.ATTRIBUTES_TO_EXTRACT.includes(a.name)&&!s)return;let c=e.node.value,u=null;if(o.isStringLiteral(c)?u=c.value:o.isJSXExpressionContainer(c)&&o.isStringLiteral(c.expression)&&(u=c.expression.value),u&&l(u)){let n=u.trim(),a=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===n);a||(a=(0,r.generateKey)(n,t._existingKeys),t._existingKeys.add(a),t._extractedContent[a]=n),i.push({path:e,key:a,isAttribute:!0}),d(e)}},StringLiteral(e){let n=e.parentPath;if(n.isJSXAttribute()||n.isImportDeclaration()||n.isExportDeclaration()||n.isImportSpecifier()||n.isObjectProperty()&&e.key===`key`||n.isMemberExpression()&&e.key===`property`)return;if(n.isCallExpression()){let e=n.node.callee;if(o.isMemberExpression(e)&&o.isIdentifier(e.object)&&e.object.name===`console`||o.isIdentifier(e)&&(e.name===t._useIntlayerLocalName||e.name===t._getIntlayerLocalName||e.name===`require`)||e.type===`Import`)return}let a=e.node.value;if(l(a)){let n=a.trim(),o=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===n);o||(o=(0,r.generateKey)(n,t._existingKeys),t._existingKeys.add(o),t._extractedContent[o]=n),i.push({path:e,key:o,isAttribute:!1}),d(e)}}}),i.length===0)return;for(let{path:e,key:n,isAttribute:r}of i){let i=!1,a=!1,l=e.scope.getBinding(t._contentVarName);if(l&&o.isVariableDeclarator(l.path.node)&&o.isCallExpression(l.path.node.init)&&o.isIdentifier(l.path.node.init.callee)&&(l.path.node.init.callee.name===t._useIntlayerLocalName?(i=!0,a=!0):l.path.node.init.callee.name===t._getIntlayerLocalName&&(i=!1,a=!0)),!a){let t=c(e,o);t&&(i=s(t,o))}if(r){let r=o.optionalMemberExpression(o.identifier(t._contentVarName),o.stringLiteral(n),!0,!0);e.node.value=o.jsxExpressionContainer(i?o.optionalMemberExpression(r,o.identifier(`value`),!1,!0):r)}else if(e.isJSXText())e.replaceWith(o.jsxExpressionContainer(o.optionalMemberExpression(o.identifier(t._contentVarName),o.stringLiteral(n),!0,!0)));else{let r=o.optionalMemberExpression(o.identifier(t._contentVarName),o.stringLiteral(n),!0,!0);e.replaceWith(i?o.optionalMemberExpression(r,o.identifier(`value`),!1,!0):r)}}t.opts.onExtract&&t._dictionaryKey&&t.opts.onExtract({dictionaryKey:t._dictionaryKey,filePath:t.file.opts.filename,content:{...t._extractedContent},locale:t.opts.defaultLocale});let f=!1,p=!1;for(let e of a){let n=u(e,t,o);n===`hook`&&(f=!0),n===`core`&&(p=!0)}if(t._hasTopLevelContent){p=!0;let n=t._contentVarName,r=t._dictionaryKey,i=t._getIntlayerLocalName,a=0,s=e.node.body;for(;a<s.length&&(o.isImportDeclaration(s[a])||o.isExpressionStatement(s[a])&&o.isStringLiteral(s[a].expression));)a++;e.node.body.splice(a,0,o.variableDeclaration(`const`,[o.variableDeclarator(o.identifier(n),o.callExpression(o.identifier(i),[o.stringLiteral(r)]))]))}if(f||p){let n=t.opts.packageName??`react-intlayer`;n===`next-intlayer`&&!t._isClient&&(n=`${n}/server`);let r=0,i=e.node.body;for(;r<i.length&&o.isExpressionStatement(i[r])&&o.isStringLiteral(i[r].expression);)r++;f&&!t._hasUseIntlayerImport&&i.splice(r++,0,o.importDeclaration([o.importSpecifier(o.identifier(`useIntlayer`),o.identifier(`useIntlayer`))],o.stringLiteral(n))),p&&!t._hasGetIntlayerImport&&i.splice(r,0,o.importDeclaration([o.importSpecifier(o.identifier(`getIntlayer`),o.identifier(`getIntlayer`))],o.stringLiteral(`intlayer`)))}}}}}},u=(e,t,n)=>{let r=e.node,i=t._contentVarName,a=t._dictionaryKey,o=s(e,n);if(!n.isBlockStatement(r.body)){let e=o?t._useIntlayerLocalName:t._getIntlayerLocalName,s=n.variableDeclaration(`const`,[n.variableDeclarator(n.identifier(i),n.callExpression(n.identifier(e),[n.stringLiteral(a)]))]);return r.body=n.blockStatement([s,n.returnStatement(r.body)]),o?`hook`:`core`}let c=o?t._useIntlayerLocalName:t._getIntlayerLocalName;return r.body.body.some(e=>n.isVariableDeclaration(e)&&e.declarations.some(e=>n.isIdentifier(e.id)&&e.id.name===i))||r.body.body.unshift(n.variableDeclaration(`const`,[n.variableDeclarator(n.identifier(i),n.callExpression(n.identifier(c),[n.stringLiteral(a)]))])),o?`hook`:`core`};exports.intlayerExtractBabelPlugin=l;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`);let t=require(`node:child_process`),n=require(`node:fs`),r=require(`node:path`),i=require(`@babel/generator`);i=e.__toESM(i);let a=require(`@intlayer/chokidar/cli`),o=require(`@intlayer/config/client`),s=require(`@intlayer/config/node`),c=require(`@intlayer/core/utils`);const l=i.default.default??i.default,u=(e,t=`comp-`)=>{let n=(0,r.basename)(e,(0,r.extname)(e));return n===`index`&&(n=(0,r.basename)((0,r.dirname)(e))),`${t}${n.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}`},d=e=>{let t=e;for(;;){let e=(0,r.join)(t,`package.json`);if((0,n.existsSync)(e))try{let t=JSON.parse((0,n.readFileSync)(e,`utf-8`));if(t.dependencies?.[`next-intlayer`]||t.devDependencies?.[`next-intlayer`])return`next-intlayer`;if(t.dependencies?.[`react-intlayer`]||t.devDependencies?.[`react-intlayer`])return`react-intlayer`;if(t.dependencies?.[`preact-intlayer`]||t.devDependencies?.[`preact-intlayer`])return`preact-intlayer`}catch{}let i=(0,r.dirname)(t);if(i===t)break;t=i}return`react-intlayer`},f=(e,t)=>{let n=e;for(;t.isParenthesizedExpression(n);)n=n.expression;return n},p=(e,t)=>{let n=e.node;if(!t.isBlockStatement(n.body)){let e=f(n.body,t);return t.isJSXElement(e)||t.isJSXFragment(e)}let r=!1;return e.traverse({Function(e){e.skip()},ReturnStatement(e){if(e.node.argument){let n=f(e.node.argument,t);(t.isJSXElement(n)||t.isJSXFragment(n))&&(r=!0)}}}),r},m=(e,t)=>{let n=e.getFunctionParent();if(!n)return null;let r=n;for(;r;){if(p(r,t))return r;r=r.getFunctionParent()}return n},h=e=>{let{types:i}=e,f=(0,s.getConfiguration)(),h=(0,o.getAppLogger)(f);return{name:`babel-plugin-intlayer-extract`,pre(){this._extractedContent={},this._existingKeys=new Set,this._isIncluded=!0,this._hasJSX=!1,this._hasUseIntlayerImport=!1,this._useIntlayerLocalName=`useIntlayer`,this._hasGetIntlayerImport=!1,this._getIntlayerLocalName=`getIntlayer`,this._contentVarName=`content`,this._isClient=!1,this._hasTopLevelContent=!1,this._extractionTargets=[],this._functionsToInject=new Set;let e=this.file.opts.filename;if(!this.opts.packageName){let t=e?(0,r.dirname)(e):process.cwd();this.opts.packageName=d(t)}if(!(this.opts.enabled??!0)){this._isIncluded=!1;return}if(this.opts.filesList&&e){let t=e.replace(/\\/g,`/`);this._isIncluded=this.opts.filesList.some(e=>e.replace(/\\/g,`/`)===t)}e&&(this._dictionaryKey=u(e,this.opts.prefix))},visitor:{ImportDeclaration(e,t){if(t._isIncluded)for(let n of e.node.specifiers){if(!i.isImportSpecifier(n))continue;let e=i.isIdentifier(n.imported)?n.imported.name:n.imported.value;e===`useIntlayer`&&(t._hasUseIntlayerImport=!0,t._useIntlayerLocalName=n.local.name),e===`getIntlayer`&&(t._hasGetIntlayerImport=!0,t._getIntlayerLocalName=n.local.name)}},JSXElement(e,t){t._isIncluded&&(t._hasJSX=!0)},JSXText(e,t){if(!t._isIncluded||!t._dictionaryKey)return;let n=t.opts.shouldExtract??a.shouldExtract,r=e.node.value;if(n(r)){let n=r.replace(/\s+/g,` `).trim(),a=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===n);a||(a=(0,c.generateKey)(n,t._existingKeys),t._existingKeys.add(a),t._extractedContent[a]=n),t._extractionTargets.push({path:e,key:a,isAttribute:!1});let o=m(e,i);o?t._functionsToInject.add(o):t._hasTopLevelContent=!0}},JSXAttribute(e,t){if(!t._isIncluded||!t._dictionaryKey)return;let n=t.opts.shouldExtract??a.shouldExtract,r=e.node.name;if(!i.isJSXIdentifier(r))return;let o=r.name===`key`;if(!a.ATTRIBUTES_TO_EXTRACT.includes(r.name)&&!o)return;let s=e.node.value,l=null;if(i.isStringLiteral(s)?l=s.value:i.isJSXExpressionContainer(s)&&i.isStringLiteral(s.expression)&&(l=s.expression.value),l&&n(l)){let n=l.trim(),r=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===n);r||(r=(0,c.generateKey)(n,t._existingKeys),t._existingKeys.add(r),t._extractedContent[r]=n),t._extractionTargets.push({path:e,key:r,isAttribute:!0});let a=m(e,i);a?t._functionsToInject.add(a):t._hasTopLevelContent=!0}},StringLiteral(e,t){if(!t._isIncluded||!t._dictionaryKey)return;let n=t.opts.shouldExtract??a.shouldExtract,r=e.parentPath;if(r.isJSXAttribute()||r.isImportDeclaration()||r.isExportDeclaration()||r.isImportSpecifier()||r.isObjectProperty()&&e.key===`key`||r.isMemberExpression()&&e.key===`property`)return;if(r.isCallExpression()){let e=r.node.callee;if(i.isMemberExpression(e)&&i.isIdentifier(e.object)&&e.object.name===`console`||i.isIdentifier(e)&&(e.name===t._useIntlayerLocalName||e.name===t._getIntlayerLocalName||e.name===`require`)||e.type===`Import`)return}let o=e.node.value;if(n(o)){let n=o.trim(),r=Object.keys(t._extractedContent).find(e=>t._extractedContent[e]===n);r||(r=(0,c.generateKey)(n,t._existingKeys),t._existingKeys.add(r),t._extractedContent[r]=n),t._extractionTargets.push({path:e,key:r,isAttribute:!1});let a=m(e,i);a?t._functionsToInject.add(a):t._hasTopLevelContent=!0}},Program:{enter(e,t){if(!t._isIncluded)return;t._isClient=e.node.directives.some(e=>e.value.value===`use client`);let n=!1;e.traverse({VariableDeclarator(e){i.isIdentifier(e.node.id)&&e.node.id.name===`content`&&(n=!0)}}),t._contentVarName=n?`_compContent`:`content`},exit(e,s){if(!s._isIncluded||!s._dictionaryKey)return;let c=s._extractionTargets,u=s._functionsToInject;if(c.length===0)return;for(let{path:e,key:t,isAttribute:n}of c){let r=!1,a=!1,o=e.scope.getBinding(s._contentVarName);if(o&&i.isVariableDeclarator(o.path.node)&&i.isCallExpression(o.path.node.init)&&i.isIdentifier(o.path.node.init.callee)&&(o.path.node.init.callee.name===s._useIntlayerLocalName?(r=!0,a=!0):o.path.node.init.callee.name===s._getIntlayerLocalName&&(r=!1,a=!0)),!a){let t=m(e,i);t&&(r=p(t,i))}if(n){let n=i.optionalMemberExpression(i.identifier(s._contentVarName),i.stringLiteral(t),!0,!0);e.node.value=i.jsxExpressionContainer(r?i.optionalMemberExpression(n,i.identifier(`value`),!1,!0):n)}else if(e.isJSXText())e.replaceWith(i.jsxExpressionContainer(i.optionalMemberExpression(i.identifier(s._contentVarName),i.stringLiteral(t),!0,!0)));else{let n=i.optionalMemberExpression(i.identifier(s._contentVarName),i.stringLiteral(t),!0,!0);e.replaceWith(r?i.optionalMemberExpression(n,i.identifier(`value`),!1,!0):n)}}s.opts.onExtract&&s._dictionaryKey&&s.opts.onExtract({dictionaryKey:s._dictionaryKey,filePath:s.file.opts.filename,content:{...s._extractedContent},locale:s.opts.defaultLocale});let d=!1,_=!1;for(let e of u){let t=g(e,s,i);t===`hook`&&(d=!0),t===`core`&&(_=!0)}if(s._hasTopLevelContent){_=!0;let t=s._contentVarName,n=s._dictionaryKey,r=s._getIntlayerLocalName,a=0,o=e.node.body;for(;a<o.length&&(i.isImportDeclaration(o[a])||i.isExpressionStatement(o[a])&&i.isStringLiteral(o[a].expression));)a++;e.node.body.splice(a,0,i.variableDeclaration(`const`,[i.variableDeclarator(i.identifier(t),i.callExpression(i.identifier(r),[i.stringLiteral(n)]))]))}if(d||_){let t=s.opts.packageName??`react-intlayer`;t===`next-intlayer`&&!s._isClient&&(t=`${t}/server`);let n=0,r=e.node.body;for(;n<r.length&&i.isExpressionStatement(r[n])&&i.isStringLiteral(r[n].expression);)n++;d&&!s._hasUseIntlayerImport&&r.splice(n++,0,i.importDeclaration([i.importSpecifier(i.identifier(`useIntlayer`),i.identifier(`useIntlayer`))],i.stringLiteral(t))),_&&!s._hasGetIntlayerImport&&r.splice(n,0,i.importDeclaration([i.importSpecifier(i.identifier(`getIntlayer`),i.identifier(`getIntlayer`))],i.stringLiteral(`intlayer`)))}if(s.opts.saveComponents&&s.file.opts.filename)try{let i=l(e.node,{retainLines:!0}).code;(0,n.writeFileSync)(s.file.opts.filename,i,`utf-8`);let c=f.content?.baseDir??process.cwd(),u=(0,r.relative)(c,s.file.opts.filename);h(`${(0,o.colorize)(`Compiler:`,o.ANSIColors.GREY_DARK)} Saved component: ${(0,o.colorizePath)(u)}`,{level:`info`});let d=(0,a.detectFormatCommand)(f);if(d)try{(0,t.execSync)(d.replace(`{{file}}`,s.file.opts.filename),{stdio:`ignore`,cwd:c})}catch(e){h(`Extractor formatting error: ${String(e)}`,{level:`error`})}}catch(e){h(`Extractor plugin error: ${String(e)}`,{level:`error`})}}}}}},g=(e,t,n)=>{let r=e.node,i=t._contentVarName,a=t._dictionaryKey,o=p(e,n);if(!n.isBlockStatement(r.body)){let e=o?t._useIntlayerLocalName:t._getIntlayerLocalName,s=n.variableDeclaration(`const`,[n.variableDeclarator(n.identifier(i),n.callExpression(n.identifier(e),[n.stringLiteral(a)]))]);return r.body=n.blockStatement([s,n.returnStatement(r.body)]),o?`hook`:`core`}let s=o?t._useIntlayerLocalName:t._getIntlayerLocalName;return r.body.body.some(e=>n.isVariableDeclaration(e)&&e.declarations.some(e=>n.isIdentifier(e.id)&&e.id.name===i))||r.body.body.unshift(n.variableDeclaration(`const`,[n.variableDeclarator(n.identifier(i),n.callExpression(n.identifier(s),[n.stringLiteral(a)]))])),o?`hook`:`core`};exports.intlayerExtractBabelPlugin=h;
2
2
  //# sourceMappingURL=babel-plugin-intlayer-extract.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["defaultShouldExtract","ATTRIBUTES_TO_EXTRACT"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { basename, dirname, extname, join } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport generator from '@babel/generator';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n shouldExtract as defaultShouldExtract,\n} from '@intlayer/chokidar/cli';\nimport { generateKey } from '@intlayer/core/utils';\n\n// Set this to true to enable debug logs\nconst DEBUG_LOG = false;\n\ntype ExtractedContent = Record<string, string>;\n\n/**\n * Extracted content result from a file transformation\n */\nexport type ExtractResult = {\n /** Dictionary key derived from the file path */\n dictionaryKey: string;\n /** File path that was processed */\n filePath: string;\n /** Extracted content key-value pairs */\n content: ExtractedContent;\n /** Default locale used */\n locale: string;\n};\n\n/**\n * Options for the extraction Babel plugin\n */\nexport type ExtractPluginOptions = {\n /**\n * The default locale for the extracted content\n */\n defaultLocale?: string;\n /**\n * The package to import useIntlayer from\n * @default 'react-intlayer'\n */\n packageName?: string;\n /**\n * Files list to traverse. If provided, only files in this list will be processed.\n */\n filesList?: string[];\n /**\n * Custom function to determine if a string should be extracted\n */\n shouldExtract?: (text: string) => boolean;\n /**\n * Callback function called when content is extracted from a file.\n * This allows the compiler to capture the extracted content and write it to files.\n * The dictionary will be updated: new keys added, unused keys removed.\n */\n onExtract?: (result: ExtractResult) => void;\n\n /**\n * Whether the extraction compiler is enabled.\n * If false, the plugin will not process the file.\n */\n enabled?: boolean;\n\n /**\n * Prefix for the extracted dictionary keys.\n */\n prefix?: string;\n};\n\ntype State = PluginPass & {\n opts: ExtractPluginOptions;\n /** Extracted content from this file */\n _extractedContent?: ExtractedContent;\n /** Set of existing keys to avoid duplicates */\n _existingKeys?: Set<string>;\n /** The dictionary key for this file */\n _dictionaryKey?: string;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n /** Whether this file has JSX (React component) */\n _hasJSX?: boolean;\n /** Whether we already have useIntlayer imported */\n _hasUseIntlayerImport?: boolean;\n /** The local name for useIntlayer (in case it's aliased) */\n _useIntlayerLocalName?: string;\n /** Whether we already have getIntlayer imported */\n _hasGetIntlayerImport?: boolean;\n /** The local name for getIntlayer (in case it's aliased) */\n _getIntlayerLocalName?: string;\n /** The variable name to use for content (content or _compContent if content is already used) */\n _contentVarName?: string;\n /** Whether the file has 'use client' directive */\n _isClient?: boolean;\n /** Whether there is extracted content at the top level (not in a function) */\n _hasTopLevelContent?: boolean;\n};\nconst extractDictionaryKeyFromPath = (\n filePath: string,\n prefix = 'comp-'\n): string => {\n const ext = extname(filePath);\n let baseName = basename(filePath, ext);\n if (baseName === 'index') baseName = basename(dirname(filePath));\n return `${prefix}${baseName\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase()}`;\n};\n\nconst detectPackageName = (dir: string): string => {\n let currentDir = dir;\n while (true) {\n const pkgPath = join(currentDir, 'package.json');\n\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n\n if (\n pkg.dependencies?.['next-intlayer'] ||\n pkg.devDependencies?.['next-intlayer']\n ) {\n return 'next-intlayer';\n }\n\n if (\n pkg.dependencies?.['react-intlayer'] ||\n pkg.devDependencies?.['react-intlayer']\n ) {\n return 'react-intlayer';\n }\n\n if (\n pkg.dependencies?.['preact-intlayer'] ||\n pkg.devDependencies?.['preact-intlayer']\n ) {\n return 'preact-intlayer';\n }\n } catch {}\n }\n const parentDir = dirname(currentDir);\n\n if (parentDir === currentDir) break;\n currentDir = parentDir;\n }\n return 'react-intlayer';\n};\n\nconst unwrapParentheses = (\n node: BabelTypes.Node,\n t: typeof BabelTypes\n): BabelTypes.Node => {\n let current = node;\n while (t.isParenthesizedExpression(current)) {\n current = current.expression;\n }\n return current;\n};\n\nconst isReactComponent = (\n funcPath: NodePath<BabelTypes.Function>,\n t: typeof BabelTypes\n): boolean => {\n const node = funcPath.node;\n if (!t.isBlockStatement(node.body)) {\n const unwrapped = unwrapParentheses(node.body, t);\n return t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped);\n }\n let returnsJSX = false;\n funcPath.traverse({\n Function(p) {\n p.skip();\n },\n ReturnStatement(p) {\n if (p.node.argument) {\n const unwrapped = unwrapParentheses(p.node.argument, t);\n\n if (t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped)) {\n returnsJSX = true;\n }\n }\n },\n });\n return returnsJSX;\n};\n\nconst findTargetFunction = (\n startPath: NodePath<any>,\n t: typeof BabelTypes\n): NodePath<BabelTypes.Function> | null => {\n const closestFunc =\n startPath.getFunctionParent() as NodePath<BabelTypes.Function> | null;\n if (!closestFunc) return null;\n\n let currentFunc: NodePath<BabelTypes.Function> | null = closestFunc;\n while (currentFunc) {\n if (isReactComponent(currentFunc, t)) {\n return currentFunc;\n }\n currentFunc =\n currentFunc.getFunctionParent() as NodePath<BabelTypes.Function> | null;\n }\n return closestFunc;\n};\n\nexport const intlayerExtractBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-extract',\n\n pre() {\n this._extractedContent = {};\n this._existingKeys = new Set();\n this._isIncluded = true;\n this._hasJSX = false;\n this._hasUseIntlayerImport = false;\n this._useIntlayerLocalName = 'useIntlayer';\n this._hasGetIntlayerImport = false;\n this._getIntlayerLocalName = 'getIntlayer';\n this._contentVarName = 'content';\n this._isClient = false;\n this._hasTopLevelContent = false;\n\n const filename = this.file.opts.filename;\n\n if (!this.opts.packageName) {\n const searchDir = filename ? dirname(filename) : process.cwd();\n this.opts.packageName = detectPackageName(searchDir);\n }\n\n // Check if extraction is enabled\n const isEnabled = this.opts.enabled ?? true;\n\n if (!isEnabled) {\n this._isIncluded = false;\n return;\n }\n\n if (this.opts.filesList && filename) {\n const normalizedFilename = filename.replace(/\\\\/g, '/');\n this._isIncluded = this.opts.filesList.some(\n (f) => f.replace(/\\\\/g, '/') === normalizedFilename\n );\n }\n\n if (filename)\n this._dictionaryKey = extractDictionaryKeyFromPath(\n filename,\n this.opts.prefix\n );\n },\n\n visitor: {\n ImportDeclaration(path, state) {\n if (!state._isIncluded) return;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n if (importedName === 'useIntlayer') {\n state._hasUseIntlayerImport = true;\n state._useIntlayerLocalName = spec.local.name;\n }\n\n if (importedName === 'getIntlayer') {\n state._hasGetIntlayerImport = true;\n state._getIntlayerLocalName = spec.local.name;\n }\n }\n },\n\n JSXElement(_path, state) {\n if (!state._isIncluded) return;\n state._hasJSX = true;\n },\n\n Program: {\n enter(programPath, state) {\n if (!state._isIncluded) return;\n\n // Check for 'use client' directive\n state._isClient = programPath.node.directives.some(\n (d) => d.value.value === 'use client'\n );\n\n let contentVarUsed = false;\n programPath.traverse({\n VariableDeclarator(varPath) {\n if (\n t.isIdentifier(varPath.node.id) &&\n varPath.node.id.name === 'content'\n )\n contentVarUsed = true;\n },\n });\n state._contentVarName = contentVarUsed ? '_compContent' : 'content';\n },\n\n exit(programPath, state) {\n if (!state._isIncluded || !state._dictionaryKey) return;\n\n const extractionTargets: {\n path: NodePath<any>;\n key: string;\n isAttribute: boolean;\n }[] = [];\n const functionsToInject = new Set<NodePath<BabelTypes.Function>>();\n const shouldExtract =\n state.opts.shouldExtract ?? defaultShouldExtract;\n\n const addTarget = (path: NodePath<any>) => {\n const func = findTargetFunction(path, t);\n\n if (func) {\n functionsToInject.add(func);\n } else {\n state._hasTopLevelContent = true;\n }\n };\n\n // Pass 1: Identification (Read only)\n programPath.traverse({\n JSXText(path) {\n const rawText = path.node.value;\n\n if (shouldExtract(rawText)) {\n const text = rawText.replace(/\\s+/g, ' ').trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === text\n );\n\n if (!key) {\n key = generateKey(text, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = text;\n }\n\n extractionTargets.push({ path, key, isAttribute: false });\n addTarget(path);\n }\n },\n JSXAttribute(path) {\n const attrName = path.node.name;\n\n if (!t.isJSXIdentifier(attrName)) return;\n const isKey = attrName.name === 'key';\n\n if (!ATTRIBUTES_TO_EXTRACT.includes(attrName.name) && !isKey)\n return;\n\n const value = path.node.value;\n let text: string | null = null;\n\n if (t.isStringLiteral(value)) text = value.value;\n else if (\n t.isJSXExpressionContainer(value) &&\n t.isStringLiteral(value.expression)\n )\n text = value.expression.value;\n\n if (text && shouldExtract(text)) {\n const cleanText = text.trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === cleanText\n );\n\n if (!key) {\n key = generateKey(cleanText, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = cleanText;\n }\n\n extractionTargets.push({ path, key, isAttribute: true });\n addTarget(path);\n }\n },\n StringLiteral(path) {\n const parent = path.parentPath;\n\n if (\n parent.isJSXAttribute() ||\n parent.isImportDeclaration() ||\n parent.isExportDeclaration() ||\n parent.isImportSpecifier()\n )\n return;\n\n if (parent.isObjectProperty() && path.key === 'key') return;\n\n if (parent.isMemberExpression() && path.key === 'property')\n return;\n\n if (parent.isCallExpression()) {\n const callee = (parent.node as BabelTypes.CallExpression)\n .callee;\n\n if (\n (t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console') ||\n (t.isIdentifier(callee) &&\n (callee.name === state._useIntlayerLocalName ||\n callee.name === state._getIntlayerLocalName ||\n callee.name === 'require')) ||\n callee.type === 'Import'\n )\n return;\n }\n\n const text = path.node.value;\n\n if (shouldExtract(text)) {\n const cleanText = text.trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === cleanText\n );\n\n if (!key) {\n key = generateKey(cleanText, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = cleanText;\n }\n\n extractionTargets.push({ path, key, isAttribute: false });\n addTarget(path);\n }\n },\n });\n\n if (extractionTargets.length === 0) return;\n\n // Pass 2: Extraction (Modification)\n for (const { path, key, isAttribute } of extractionTargets) {\n let isHook = false;\n let hookDecided = false;\n\n const binding = path.scope.getBinding(state._contentVarName!);\n\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isCallExpression(binding.path.node.init) &&\n t.isIdentifier(binding.path.node.init.callee)\n ) {\n if (\n binding.path.node.init.callee.name ===\n state._useIntlayerLocalName\n ) {\n isHook = true;\n hookDecided = true;\n } else if (\n binding.path.node.init.callee.name ===\n state._getIntlayerLocalName\n ) {\n isHook = false;\n hookDecided = true;\n }\n }\n\n if (!hookDecided) {\n const func = findTargetFunction(path, t);\n\n if (func) {\n isHook = isReactComponent(func, t);\n }\n }\n\n if (isAttribute) {\n const member = t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n );\n path.node.value = t.jsxExpressionContainer(\n isHook\n ? t.optionalMemberExpression(\n member,\n t.identifier('value'),\n false,\n true\n )\n : member\n );\n } else if (path.isJSXText()) {\n path.replaceWith(\n t.jsxExpressionContainer(\n t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n )\n )\n );\n } else {\n const member = t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n );\n path.replaceWith(\n isHook\n ? t.optionalMemberExpression(\n member,\n t.identifier('value'),\n false,\n true\n )\n : member\n );\n }\n }\n\n // Report\n\n if (state.opts.onExtract && state._dictionaryKey) {\n state.opts.onExtract({\n dictionaryKey: state._dictionaryKey,\n filePath: state.file.opts.filename!,\n content: { ...state._extractedContent! },\n locale: state.opts.defaultLocale!,\n });\n }\n\n // Pass 3: Injection\n let needsUseIntlayer = false;\n let needsGetIntlayer = false;\n\n for (const funcPath of functionsToInject) {\n const type = injectHook(funcPath, state, t);\n\n if (type === 'hook') needsUseIntlayer = true;\n\n if (type === 'core') needsGetIntlayer = true;\n }\n\n if (state._hasTopLevelContent) {\n needsGetIntlayer = true;\n const contentVarName = state._contentVarName!;\n const dictionaryKey = state._dictionaryKey!;\n const coreName = state._getIntlayerLocalName!;\n\n // Find injection position (after imports)\n let pos = 0;\n const body = programPath.node.body;\n while (\n pos < body.length &&\n (t.isImportDeclaration(body[pos]) ||\n (t.isExpressionStatement(body[pos]) &&\n t.isStringLiteral(\n (body[pos] as BabelTypes.ExpressionStatement).expression\n )))\n )\n pos++;\n\n programPath.node.body.splice(\n pos,\n 0,\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(coreName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ])\n );\n }\n\n // Pass 4: Imports\n\n if (needsUseIntlayer || needsGetIntlayer) {\n let hookPkg = state.opts.packageName ?? 'react-intlayer';\n const corePkg = 'intlayer';\n\n // Handle next-intlayer server/client split\n\n if (hookPkg === 'next-intlayer' && !state._isClient) {\n hookPkg = `${hookPkg}/server`;\n }\n\n let pos = 0;\n const body = programPath.node.body;\n while (\n pos < body.length &&\n t.isExpressionStatement(body[pos]) &&\n t.isStringLiteral(\n (body[pos] as BabelTypes.ExpressionStatement).expression\n )\n )\n pos++;\n\n if (needsUseIntlayer && !state._hasUseIntlayerImport) {\n body.splice(\n pos++,\n 0,\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('useIntlayer'),\n t.identifier('useIntlayer')\n ),\n ],\n t.stringLiteral(hookPkg)\n )\n );\n }\n\n if (needsGetIntlayer && !state._hasGetIntlayerImport) {\n body.splice(\n pos,\n 0,\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('getIntlayer'),\n t.identifier('getIntlayer')\n ),\n ],\n t.stringLiteral(corePkg)\n )\n );\n }\n }\n\n if (DEBUG_LOG) {\n console.log(\n '[babel-plugin-intlayer-extract] Transformed:',\n state.file.opts.filename\n );\n\n console.log(\n generator(programPath.node, { retainLines: true }).code\n );\n }\n },\n },\n },\n };\n};\n\nconst injectHook = (\n path: NodePath<BabelTypes.Function>,\n state: State,\n t: typeof BabelTypes\n): 'hook' | 'core' => {\n const node = path.node;\n const contentVarName = state._contentVarName!;\n const dictionaryKey = state._dictionaryKey!;\n const returnsJSX = isReactComponent(path, t);\n\n if (!t.isBlockStatement(node.body)) {\n const hookName = returnsJSX\n ? state._useIntlayerLocalName!\n : state._getIntlayerLocalName!;\n const hookCall = t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(hookName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ]);\n node.body = t.blockStatement([\n hookCall,\n t.returnStatement(node.body as BabelTypes.Expression),\n ]);\n return returnsJSX ? 'hook' : 'core';\n }\n\n const hookName = returnsJSX\n ? state._useIntlayerLocalName!\n : state._getIntlayerLocalName!;\n const hasHook = node.body.body.some(\n (s) =>\n t.isVariableDeclaration(s) &&\n s.declarations.some(\n (d) => t.isIdentifier(d.id) && d.id.name === contentVarName\n )\n );\n\n if (!hasHook) {\n node.body.body.unshift(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(hookName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ])\n );\n }\n\n return returnsJSX ? 'hook' : 'core';\n};\n"],"mappings":"qQAiGA,MAAM,GACJ,EACA,EAAS,UACE,CAEX,IAAI,GAAA,EAAA,EAAA,UAAoB,GAAA,EAAA,EAAA,SADJ,EAAS,CACS,CAEtC,OADI,IAAa,UAAS,GAAA,EAAA,EAAA,WAAA,EAAA,EAAA,SAA4B,EAAS,CAAC,EACzD,GAAG,IAAS,EAChB,QAAQ,kBAAmB,QAAQ,CACnC,QAAQ,UAAW,IAAI,CACvB,aAAa,IAGZ,EAAqB,GAAwB,CACjD,IAAI,EAAa,EACjB,OAAa,CACX,IAAM,GAAA,EAAA,EAAA,MAAe,EAAY,eAAe,CAEhD,IAAA,EAAA,EAAA,YAAe,EAAQ,CACrB,GAAI,CACF,IAAM,EAAM,KAAK,OAAA,EAAA,EAAA,cAAmB,EAAS,QAAQ,CAAC,CAEtD,GACE,EAAI,eAAe,kBACnB,EAAI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EAAO,EAAK,KACZ,EAAiB,EAAM,gBACvB,EAAgB,EAAM,eACtB,EAAa,EAAiB,EAAM,EAAE,CAE5C,GAAI,CAAC,EAAE,iBAAiB,EAAK,KAAK,CAAE,CAClC,IAAM,EAAW,EACb,EAAM,sBACN,EAAM,sBACJ,EAAW,EAAE,oBAAoB,QAAS,CAC9C,EAAE,mBACA,EAAE,WAAW,EAAe,CAC5B,EAAE,eAAe,EAAE,WAAW,EAAS,CAAE,CACvC,EAAE,cAAc,EAAc,CAC/B,CAAC,CACH,CACF,CAAC,CAKF,MAJA,GAAK,KAAO,EAAE,eAAe,CAC3B,EACA,EAAE,gBAAgB,EAAK,KAA8B,CACtD,CAAC,CACK,EAAa,OAAS,OAG/B,IAAM,EAAW,EACb,EAAM,sBACN,EAAM,sBAsBV,OArBgB,EAAK,KAAK,KAAK,KAC5B,GACC,EAAE,sBAAsB,EAAE,EAC1B,EAAE,aAAa,KACZ,GAAM,EAAE,aAAa,EAAE,GAAG,EAAI,EAAE,GAAG,OAAS,EAC9C,CACJ,EAGC,EAAK,KAAK,KAAK,QACb,EAAE,oBAAoB,QAAS,CAC7B,EAAE,mBACA,EAAE,WAAW,EAAe,CAC5B,EAAE,eAAe,EAAE,WAAW,EAAS,CAAE,CACvC,EAAE,cAAc,EAAc,CAC/B,CAAC,CACH,CACF,CAAC,CACH,CAGI,EAAa,OAAS"}
1
+ {"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["_generate","defaultShouldExtract","ATTRIBUTES_TO_EXTRACT","ANSIColors"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, extname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport _generate from '@babel/generator';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n shouldExtract as defaultShouldExtract,\n detectFormatCommand,\n} from '@intlayer/chokidar/cli';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/client';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { generateKey } from '@intlayer/core/utils';\n\nconst generate = ((_generate as any).default ?? _generate) as typeof _generate;\n\n// Set this to true to enable debug logs\nconst DEBUG_LOG = false;\n\ntype ExtractedContent = Record<string, string>;\n\n/**\n * Extracted content result from a file transformation\n */\nexport type ExtractResult = {\n /** Dictionary key derived from the file path */\n dictionaryKey: string;\n /** File path that was processed */\n filePath: string;\n /** Extracted content key-value pairs */\n content: ExtractedContent;\n /** Default locale used */\n locale: string;\n};\n\n/**\n * Options for the extraction Babel plugin\n */\nexport type ExtractPluginOptions = {\n /**\n * The default locale for the extracted content\n */\n defaultLocale?: string;\n /**\n * The package to import useIntlayer from\n * @default 'react-intlayer'\n */\n packageName?: string;\n /**\n * Files list to traverse. If provided, only files in this list will be processed.\n */\n filesList?: string[];\n /**\n * Custom function to determine if a string should be extracted\n */\n shouldExtract?: (text: string) => boolean;\n /**\n * Callback function called when content is extracted from a file.\n * This allows the compiler to capture the extracted content and write it to files.\n * The dictionary will be updated: new keys added, unused keys removed.\n */\n onExtract?: (result: ExtractResult) => void;\n\n /**\n * Whether the extraction compiler is enabled.\n * If false, the plugin will not process the file.\n */\n enabled?: boolean;\n\n /**\n * Prefix for the extracted dictionary keys.\n */\n prefix?: string;\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents?: boolean;\n};\n\ntype State = PluginPass & {\n opts: ExtractPluginOptions;\n /** Extracted content from this file */\n _extractedContent?: ExtractedContent;\n /** Set of existing keys to avoid duplicates */\n _existingKeys?: Set<string>;\n /** The dictionary key for this file */\n _dictionaryKey?: string;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n /** Whether this file has JSX (React component) */\n _hasJSX?: boolean;\n /** Whether we already have useIntlayer imported */\n _hasUseIntlayerImport?: boolean;\n /** The local name for useIntlayer (in case it's aliased) */\n _useIntlayerLocalName?: string;\n /** Whether we already have getIntlayer imported */\n _hasGetIntlayerImport?: boolean;\n /** The local name for getIntlayer (in case it's aliased) */\n _getIntlayerLocalName?: string;\n /** The variable name to use for content (content or _compContent if content is already used) */\n _contentVarName?: string;\n /** Whether the file has 'use client' directive */\n _isClient?: boolean;\n /** Whether there is extracted content at the top level (not in a function) */\n _hasTopLevelContent?: boolean;\n /** Targets to extract and modify */\n _extractionTargets?: {\n path: NodePath<any>;\n key: string;\n isAttribute: boolean;\n }[];\n /** Functions to inject the hook/core logic into */\n _functionsToInject?: Set<NodePath<BabelTypes.Function>>;\n};\nconst extractDictionaryKeyFromPath = (\n filePath: string,\n prefix = 'comp-'\n): string => {\n const ext = extname(filePath);\n let baseName = basename(filePath, ext);\n if (baseName === 'index') baseName = basename(dirname(filePath));\n return `${prefix}${baseName\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase()}`;\n};\n\nconst detectPackageName = (dir: string): string => {\n let currentDir = dir;\n while (true) {\n const pkgPath = join(currentDir, 'package.json');\n\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n\n if (\n pkg.dependencies?.['next-intlayer'] ||\n pkg.devDependencies?.['next-intlayer']\n ) {\n return 'next-intlayer';\n }\n\n if (\n pkg.dependencies?.['react-intlayer'] ||\n pkg.devDependencies?.['react-intlayer']\n ) {\n return 'react-intlayer';\n }\n\n if (\n pkg.dependencies?.['preact-intlayer'] ||\n pkg.devDependencies?.['preact-intlayer']\n ) {\n return 'preact-intlayer';\n }\n } catch {}\n }\n const parentDir = dirname(currentDir);\n\n if (parentDir === currentDir) break;\n currentDir = parentDir;\n }\n return 'react-intlayer';\n};\n\nconst unwrapParentheses = (\n node: BabelTypes.Node,\n t: typeof BabelTypes\n): BabelTypes.Node => {\n let current = node;\n\n while (t.isParenthesizedExpression(current)) {\n current = current.expression;\n }\n\n return current;\n};\n\nconst isReactComponent = (\n funcPath: NodePath<BabelTypes.Function>,\n t: typeof BabelTypes\n): boolean => {\n const node = funcPath.node;\n\n if (!t.isBlockStatement(node.body)) {\n const unwrapped = unwrapParentheses(node.body, t);\n return t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped);\n }\n\n let returnsJSX = false;\n\n funcPath.traverse({\n Function(p) {\n p.skip();\n },\n ReturnStatement(p) {\n if (p.node.argument) {\n const unwrapped = unwrapParentheses(p.node.argument, t);\n\n if (t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped)) {\n returnsJSX = true;\n }\n }\n },\n });\n return returnsJSX;\n};\n\nconst findTargetFunction = (\n startPath: NodePath<any>,\n t: typeof BabelTypes\n): NodePath<BabelTypes.Function> | null => {\n const closestFunc =\n startPath.getFunctionParent() as NodePath<BabelTypes.Function> | null;\n if (!closestFunc) return null;\n\n let currentFunc: NodePath<BabelTypes.Function> | null = closestFunc;\n while (currentFunc) {\n if (isReactComponent(currentFunc, t)) {\n return currentFunc;\n }\n currentFunc =\n currentFunc.getFunctionParent() as NodePath<BabelTypes.Function> | null;\n }\n return closestFunc;\n};\n\nexport const intlayerExtractBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n const config = getConfiguration();\n const appLogger = getAppLogger(config);\n\n return {\n name: 'babel-plugin-intlayer-extract',\n\n pre() {\n this._extractedContent = {};\n this._existingKeys = new Set();\n this._isIncluded = true;\n this._hasJSX = false;\n this._hasUseIntlayerImport = false;\n this._useIntlayerLocalName = 'useIntlayer';\n this._hasGetIntlayerImport = false;\n this._getIntlayerLocalName = 'getIntlayer';\n this._contentVarName = 'content';\n this._isClient = false;\n this._hasTopLevelContent = false;\n this._extractionTargets = [];\n this._functionsToInject = new Set();\n\n const filename = this.file.opts.filename;\n\n if (!this.opts.packageName) {\n const searchDir = filename ? dirname(filename) : process.cwd();\n this.opts.packageName = detectPackageName(searchDir);\n }\n\n // Check if extraction is enabled\n const isEnabled = this.opts.enabled ?? true;\n\n if (!isEnabled) {\n this._isIncluded = false;\n return;\n }\n\n if (this.opts.filesList && filename) {\n const normalizedFilename = filename.replace(/\\\\/g, '/');\n this._isIncluded = this.opts.filesList.some(\n (f) => f.replace(/\\\\/g, '/') === normalizedFilename\n );\n }\n\n if (filename)\n this._dictionaryKey = extractDictionaryKeyFromPath(\n filename,\n this.opts.prefix\n );\n },\n visitor: {\n ImportDeclaration(path, state) {\n if (!state._isIncluded) return;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n if (importedName === 'useIntlayer') {\n state._hasUseIntlayerImport = true;\n state._useIntlayerLocalName = spec.local.name;\n }\n\n if (importedName === 'getIntlayer') {\n state._hasGetIntlayerImport = true;\n state._getIntlayerLocalName = spec.local.name;\n }\n }\n },\n\n JSXElement(_path, state) {\n if (!state._isIncluded) return;\n state._hasJSX = true;\n },\n\n JSXText(path, state) {\n if (!state._isIncluded || !state._dictionaryKey) return;\n const shouldExtract = state.opts.shouldExtract ?? defaultShouldExtract;\n const rawText = path.node.value;\n\n if (shouldExtract(rawText)) {\n const text = rawText.replace(/\\s+/g, ' ').trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === text\n );\n\n if (!key) {\n key = generateKey(text, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = text;\n }\n\n state._extractionTargets!.push({ path, key, isAttribute: false });\n const func = findTargetFunction(path, t);\n if (func) {\n state._functionsToInject!.add(func);\n } else {\n state._hasTopLevelContent = true;\n }\n }\n },\n\n JSXAttribute(path, state) {\n if (!state._isIncluded || !state._dictionaryKey) return;\n const shouldExtract = state.opts.shouldExtract ?? defaultShouldExtract;\n const attrName = path.node.name;\n\n if (!t.isJSXIdentifier(attrName)) return;\n const isKey = attrName.name === 'key';\n\n if (!ATTRIBUTES_TO_EXTRACT.includes(attrName.name) && !isKey) return;\n\n const value = path.node.value;\n let text: string | null = null;\n\n if (t.isStringLiteral(value)) text = value.value;\n else if (\n t.isJSXExpressionContainer(value) &&\n t.isStringLiteral(value.expression)\n )\n text = value.expression.value;\n\n if (text && shouldExtract(text)) {\n const cleanText = text.trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === cleanText\n );\n\n if (!key) {\n key = generateKey(cleanText, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = cleanText;\n }\n\n state._extractionTargets!.push({ path, key, isAttribute: true });\n const func = findTargetFunction(path, t);\n if (func) {\n state._functionsToInject!.add(func);\n } else {\n state._hasTopLevelContent = true;\n }\n }\n },\n\n StringLiteral(path, state) {\n if (!state._isIncluded || !state._dictionaryKey) return;\n const shouldExtract = state.opts.shouldExtract ?? defaultShouldExtract;\n const parent = path.parentPath;\n\n if (\n parent.isJSXAttribute() ||\n parent.isImportDeclaration() ||\n parent.isExportDeclaration() ||\n parent.isImportSpecifier()\n )\n return;\n\n if (parent.isObjectProperty() && path.key === 'key') return;\n\n if (parent.isMemberExpression() && path.key === 'property') return;\n\n if (parent.isCallExpression()) {\n const callee = (parent.node as BabelTypes.CallExpression).callee;\n\n if (\n (t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console') ||\n (t.isIdentifier(callee) &&\n (callee.name === state._useIntlayerLocalName ||\n callee.name === state._getIntlayerLocalName ||\n callee.name === 'require')) ||\n callee.type === 'Import'\n )\n return;\n }\n\n const text = path.node.value;\n\n if (shouldExtract(text)) {\n const cleanText = text.trim();\n let key = Object.keys(state._extractedContent!).find(\n (k) => state._extractedContent![k] === cleanText\n );\n\n if (!key) {\n key = generateKey(cleanText, state._existingKeys!);\n state._existingKeys!.add(key);\n state._extractedContent![key] = cleanText;\n }\n\n state._extractionTargets!.push({ path, key, isAttribute: false });\n const func = findTargetFunction(path, t);\n if (func) {\n state._functionsToInject!.add(func);\n } else {\n state._hasTopLevelContent = true;\n }\n }\n },\n\n Program: {\n enter(programPath, state) {\n if (!state._isIncluded) return;\n\n // Check for 'use client' directive\n state._isClient = programPath.node.directives.some(\n (d) => d.value.value === 'use client'\n );\n\n let contentVarUsed = false;\n programPath.traverse({\n VariableDeclarator(varPath) {\n if (\n t.isIdentifier(varPath.node.id) &&\n varPath.node.id.name === 'content'\n )\n contentVarUsed = true;\n },\n });\n state._contentVarName = contentVarUsed ? '_compContent' : 'content';\n },\n\n exit(programPath, state) {\n if (!state._isIncluded || !state._dictionaryKey) return;\n\n const extractionTargets = state._extractionTargets!;\n const functionsToInject = state._functionsToInject!;\n\n if (extractionTargets.length === 0) return;\n\n // Extraction (Modification)\n for (const { path, key, isAttribute } of extractionTargets) {\n let isHook = false;\n let hookDecided = false;\n\n const binding = path.scope.getBinding(state._contentVarName!);\n\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isCallExpression(binding.path.node.init) &&\n t.isIdentifier(binding.path.node.init.callee)\n ) {\n if (\n binding.path.node.init.callee.name ===\n state._useIntlayerLocalName\n ) {\n isHook = true;\n hookDecided = true;\n } else if (\n binding.path.node.init.callee.name ===\n state._getIntlayerLocalName\n ) {\n isHook = false;\n hookDecided = true;\n }\n }\n\n if (!hookDecided) {\n const func = findTargetFunction(path, t);\n\n if (func) {\n isHook = isReactComponent(func, t);\n }\n }\n\n if (isAttribute) {\n const member = t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n );\n path.node.value = t.jsxExpressionContainer(\n isHook\n ? t.optionalMemberExpression(\n member,\n t.identifier('value'),\n false,\n true\n )\n : member\n );\n } else if (path.isJSXText()) {\n path.replaceWith(\n t.jsxExpressionContainer(\n t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n )\n )\n );\n } else {\n const member = t.optionalMemberExpression(\n t.identifier(state._contentVarName!),\n t.stringLiteral(key),\n true,\n true\n );\n path.replaceWith(\n isHook\n ? t.optionalMemberExpression(\n member,\n t.identifier('value'),\n false,\n true\n )\n : member\n );\n }\n }\n\n // Report\n\n if (state.opts.onExtract && state._dictionaryKey) {\n state.opts.onExtract({\n dictionaryKey: state._dictionaryKey,\n filePath: state.file.opts.filename!,\n content: { ...state._extractedContent! },\n locale: state.opts.defaultLocale!,\n });\n }\n\n // Pass 3: Injection\n let needsUseIntlayer = false;\n let needsGetIntlayer = false;\n\n for (const funcPath of functionsToInject) {\n const type = injectHook(funcPath, state, t);\n\n if (type === 'hook') needsUseIntlayer = true;\n\n if (type === 'core') needsGetIntlayer = true;\n }\n\n if (state._hasTopLevelContent) {\n needsGetIntlayer = true;\n const contentVarName = state._contentVarName!;\n const dictionaryKey = state._dictionaryKey!;\n const coreName = state._getIntlayerLocalName!;\n\n // Find injection position (after imports)\n let pos = 0;\n const body = programPath.node.body;\n while (\n pos < body.length &&\n (t.isImportDeclaration(body[pos]) ||\n (t.isExpressionStatement(body[pos]) &&\n t.isStringLiteral(\n (body[pos] as BabelTypes.ExpressionStatement).expression\n )))\n )\n pos++;\n\n programPath.node.body.splice(\n pos,\n 0,\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(coreName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ])\n );\n }\n\n // Pass 4: Imports\n\n if (needsUseIntlayer || needsGetIntlayer) {\n let hookPkg = state.opts.packageName ?? 'react-intlayer';\n const corePkg = 'intlayer';\n\n // Handle next-intlayer server/client split\n\n if (hookPkg === 'next-intlayer' && !state._isClient) {\n hookPkg = `${hookPkg}/server`;\n }\n\n let pos = 0;\n const body = programPath.node.body;\n while (\n pos < body.length &&\n t.isExpressionStatement(body[pos]) &&\n t.isStringLiteral(\n (body[pos] as BabelTypes.ExpressionStatement).expression\n )\n )\n pos++;\n\n if (needsUseIntlayer && !state._hasUseIntlayerImport) {\n body.splice(\n pos++,\n 0,\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('useIntlayer'),\n t.identifier('useIntlayer')\n ),\n ],\n t.stringLiteral(hookPkg)\n )\n );\n }\n\n if (needsGetIntlayer && !state._hasGetIntlayerImport) {\n body.splice(\n pos,\n 0,\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('getIntlayer'),\n t.identifier('getIntlayer')\n ),\n ],\n t.stringLiteral(corePkg)\n )\n );\n }\n }\n\n if (state.opts.saveComponents && state.file.opts.filename) {\n try {\n const transformedCode = generate(programPath.node, {\n retainLines: true,\n }).code;\n\n writeFileSync(state.file.opts.filename, transformedCode, 'utf-8');\n\n const basedir = config.content?.baseDir ?? process.cwd();\n const relativePath = relative(basedir, state.file.opts.filename);\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Saved component: ${colorizePath(relativePath)}`,\n { level: 'info' }\n );\n\n const formatCommand = detectFormatCommand(config);\n\n if (formatCommand) {\n try {\n execSync(\n formatCommand.replace('{{file}}', state.file.opts.filename),\n {\n stdio: 'ignore', // Use 'ignore' to prevent format output from cluttering the extraction process console\n cwd: basedir,\n }\n );\n } catch (error) {\n appLogger(`Extractor formatting error: ${String(error)}`, {\n level: 'error',\n });\n }\n }\n } catch (err: any) {\n appLogger(`Extractor plugin error: ${String(err)}`, {\n level: 'error',\n });\n }\n }\n\n if (DEBUG_LOG) {\n const basedir = config.content?.baseDir ?? process.cwd();\n const relativePath = state.file.opts.filename\n ? relative(basedir, state.file.opts.filename)\n : 'unknown';\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Transformed: ${colorizePath(relativePath)}\\n${generate(programPath.node, { retainLines: false }).code}`,\n { level: 'debug' }\n );\n }\n },\n },\n },\n };\n};\n\nconst injectHook = (\n path: NodePath<BabelTypes.Function>,\n state: State,\n t: typeof BabelTypes\n): 'hook' | 'core' => {\n const node = path.node;\n const contentVarName = state._contentVarName!;\n const dictionaryKey = state._dictionaryKey!;\n const returnsJSX = isReactComponent(path, t);\n\n if (!t.isBlockStatement(node.body)) {\n const hookName = returnsJSX\n ? state._useIntlayerLocalName!\n : state._getIntlayerLocalName!;\n\n const hookCall = t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(hookName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ]);\n\n node.body = t.blockStatement([\n hookCall,\n t.returnStatement(node.body as BabelTypes.Expression),\n ]);\n\n return returnsJSX ? 'hook' : 'core';\n }\n\n const hookName = returnsJSX\n ? state._useIntlayerLocalName!\n : state._getIntlayerLocalName!;\n\n const hasHook = node.body.body.some(\n (s) =>\n t.isVariableDeclaration(s) &&\n s.declarations.some(\n (d) => t.isIdentifier(d.id) && d.id.name === contentVarName\n )\n );\n\n if (!hasHook) {\n node.body.body.unshift(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(contentVarName),\n t.callExpression(t.identifier(hookName), [\n t.stringLiteral(dictionaryKey),\n ])\n ),\n ])\n );\n }\n\n return returnsJSX ? 'hook' : 'core';\n};\n"],"mappings":"sYAoBA,MAAM,EAAaA,EAAAA,QAAkB,SAAWA,EAAAA,QAqG1C,GACJ,EACA,EAAS,UACE,CAEX,IAAI,GAAA,EAAA,EAAA,UAAoB,GAAA,EAAA,EAAA,SADJ,EAAS,CACS,CAEtC,OADI,IAAa,UAAS,GAAA,EAAA,EAAA,WAAA,EAAA,EAAA,SAA4B,EAAS,CAAC,EACzD,GAAG,IAAS,EAChB,QAAQ,kBAAmB,QAAQ,CACnC,QAAQ,UAAW,IAAI,CACvB,aAAa,IAGZ,EAAqB,GAAwB,CACjD,IAAI,EAAa,EACjB,OAAa,CACX,IAAM,GAAA,EAAA,EAAA,MAAe,EAAY,eAAe,CAEhD,IAAA,EAAA,EAAA,YAAe,EAAQ,CACrB,GAAI,CACF,IAAM,EAAM,KAAK,OAAA,EAAA,EAAA,cAAmB,EAAS,QAAQ,CAAC,CAEtD,GACE,EAAI,eAAe,kBACnB,EAAI,kBAAkB,iBAEtB,MAAO,g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AM,EAAO,EAAK,KACZ,EAAiB,EAAM,gBACvB,EAAgB,EAAM,eACtB,EAAa,EAAiB,EAAM,EAAE,CAE5C,GAAI,CAAC,EAAE,iBAAiB,EAAK,KAAK,CAAE,CAClC,IAAM,EAAW,EACb,EAAM,sBACN,EAAM,sBAEJ,EAAW,EAAE,oBAAoB,QAAS,CAC9C,EAAE,mBACA,EAAE,WAAW,EAAe,CAC5B,EAAE,eAAe,EAAE,WAAW,EAAS,CAAE,CACvC,EAAE,cAAc,EAAc,CAC/B,CAAC,CACH,CACF,CAAC,CAOF,MALA,GAAK,KAAO,EAAE,eAAe,CAC3B,EACA,EAAE,gBAAgB,EAAK,KAA8B,CACtD,CAAC,CAEK,EAAa,OAAS,OAG/B,IAAM,EAAW,EACb,EAAM,sBACN,EAAM,sBAuBV,OArBgB,EAAK,KAAK,KAAK,KAC5B,GACC,EAAE,sBAAsB,EAAE,EAC1B,EAAE,aAAa,KACZ,GAAM,EAAE,aAAa,EAAE,GAAG,EAAI,EAAE,GAAG,OAAS,EAC9C,CACJ,EAGC,EAAK,KAAK,KAAK,QACb,EAAE,oBAAoB,QAAS,CAC7B,EAAE,mBACA,EAAE,WAAW,EAAe,CAC5B,EAAE,eAAe,EAAE,WAAW,EAAS,CAAE,CACvC,EAAE,cAAc,EAAc,CAC/B,CAAC,CACH,CACF,CAAC,CACH,CAGI,EAAa,OAAS"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/utils`);const r=[`intlayer`,`@intlayer/core`,`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`svelte-intlayer`,`vue-intlayer`,`angular-intlayer`,`preact-intlayer`,`solid-intlayer`],i=[`useIntlayer`,`getIntlayer`],a=[`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`preact-intlayer`,`vue-intlayer`,`solid-intlayer`,`svelte-intlayer`,`angular-intlayer`],o={getIntlayer:`getDictionary`,useIntlayer:`useDictionary`},s={useIntlayer:`useDictionaryDynamic`},c=(e,n)=>{let r=(0,t.getFileHash)(e);return n.identifier(`_${r}`)},l=(t,r,i,a,o,s)=>{let c=(0,e.join)(r,`${o}.json`);s===`fetch`&&(c=(0,e.join)(a,`${o}.mjs`)),s===`dynamic`&&(c=(0,e.join)(i,`${o}.mjs`));let l=(0,e.relative)((0,e.dirname)(t),c);return l=(0,n.normalizePath)(l),!l.startsWith(`./`)&&!l.startsWith(`../`)&&(l=`./${l}`),l},u=e=>{let{types:n}=e;return{name:`babel-plugin-intlayer-transform`,pre(){if(this._newStaticImports=new Map,this._newDynamicImports=new Map,this._isIncluded=!0,this._hasValidImport=!1,this._isDictEntry=!1,this._useDynamicHelpers=!1,this.opts.optimize===!1){this._isIncluded=!1;return}let e=this.file.opts.filename;if(this.opts.filesList&&e&&!this.opts.filesList.includes(e)){this._isIncluded=!1;return}},visitor:{Program:{enter(e,t){let r=t.file.opts.filename;t.opts.replaceDictionaryEntry&&r===t.opts.dictionariesEntryPath&&(t._isDictEntry=!0,e.traverse({ImportDeclaration(e){e.remove()},VariableDeclarator(e){n.isObjectExpression(e.node.init)&&(e.node.init.properties=[])}}))},exit(e,u){if(u._isDictEntry||!u._isIncluded)return;let d=!1;if(e.traverse({CallExpression(e){let t=e.node.callee;if(!n.isIdentifier(t)||t.name!==`useIntlayer`)return;let r=e.node.arguments[0];if(!r||!n.isStringLiteral(r))return;let i=r.value,a=u.opts.dictionaryModeMap?.[i];(a===`dynamic`||a===`fetch`)&&(d=!0)}}),e.traverse({ImportDeclaration(e){let t=e.node.source.value;if(r.includes(t)){u._hasValidImport=!0;for(let r of e.node.specifiers){if(!n.isImportSpecifier(r))continue;let e=n.isIdentifier(r.imported)?r.imported.name:r.imported.value,i=u.opts.importMode,c=(i===`dynamic`||i===`fetch`||d)&&a.includes(t);c&&(u._useDynamicHelpers=!0);let l;l=c?{...o,...s}:o;let f=l[e];f&&(r.imported=n.identifier(f))}}},CallExpression(e){let r=e.node.callee;if(!n.isIdentifier(r)||!i.includes(r.name))return;u._hasValidImport=!0;let a=e.node.arguments[0];if(!a||!n.isStringLiteral(a))return;let o=a.value,s=u.opts.importMode,l=r.name===`useIntlayer`,d=!!u._useDynamicHelpers,f=`static`,p=u.opts.dictionaryModeMap?.[o];l&&d?p?f=p:s===`dynamic`?f=`dynamic`:s===`fetch`&&(f=`fetch`):l&&!d&&(p===`dynamic`||p===`fetch`)&&(f=p);let m;if(f===`fetch`){let r=u._newDynamicImports?.get(o);if(!r){let e=(0,t.getFileHash)(o);r=n.identifier(`_${e}_fetch`),u._newDynamicImports?.set(o,r)}m=r,e.node.arguments=[n.identifier(m.name),...e.node.arguments]}else if(f===`dynamic`){let r=u._newDynamicImports?.get(o);if(!r){let e=(0,t.getFileHash)(o);r=n.identifier(`_${e}_dyn`),u._newDynamicImports?.set(o,r)}m=r,e.node.arguments=[n.identifier(m.name),...e.node.arguments]}else{let t=u._newStaticImports?.get(o);t||(t=c(o,n),u._newStaticImports?.set(o,t)),m=t,e.node.arguments[0]=n.identifier(m.name)}}}),!u._hasValidImport)return;let f=u.file.opts.filename,p=u.opts.dictionariesDir,m=u.opts.dynamicDictionariesDir,h=u.opts.fetchDictionariesDir,g=[];for(let[e,t]of u._newStaticImports){let r=l(f,p,m,h,e,`static`),i=n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r));i.attributes=[n.importAttribute(n.identifier(`type`),n.stringLiteral(`json`))],g.push(i)}for(let[e,t]of u._newDynamicImports){let r=l(f,p,m,h,e,t.name.endsWith(`_fetch`)?`fetch`:`dynamic`);g.push(n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r)))}if(!g.length)return;let _=e.get(`body`),v=0;for(let e of _){let t=e.node;if(n.isExpressionStatement(t)&&n.isStringLiteral(t.expression)&&!t.expression.value.startsWith(`import`)&&!t.expression.value.startsWith(`require`))v+=1;else break}e.node.body.splice(v,0,...g)}}}}};exports.intlayerOptimizeBabelPlugin=u;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/utils`);const r=[`intlayer`,`@intlayer/core`,`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`svelte-intlayer`,`vue-intlayer`,`angular-intlayer`,`preact-intlayer`,`solid-intlayer`],i=[`useIntlayer`,`getIntlayer`],a=[`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`preact-intlayer`,`vue-intlayer`,`solid-intlayer`,`svelte-intlayer`,`angular-intlayer`],o={getIntlayer:`getDictionary`,useIntlayer:`useDictionary`},s={useIntlayer:`useDictionaryDynamic`},c=(e,n)=>{let r=(0,t.getFileHash)(e);return n.identifier(`_${r}`)},l=(t,r,i,a,o,s)=>{let c=(0,e.join)(r,`${o}.json`);s===`fetch`&&(c=(0,e.join)(a,`${o}.mjs`)),s===`dynamic`&&(c=(0,e.join)(i,`${o}.mjs`));let l=(0,e.relative)((0,e.dirname)(t),c);return l=(0,n.normalizePath)(l),!l.startsWith(`./`)&&!l.startsWith(`../`)&&(l=`./${l}`),l},u=e=>{let{types:n}=e;return{name:`babel-plugin-intlayer-transform`,pre(){if(this._newStaticImports=new Map,this._newDynamicImports=new Map,this._callerMap=new Map,this._isIncluded=!0,this._hasValidImport=!1,this._isDictEntry=!1,this._useDynamicHelpers=!1,this.opts.optimize===!1){this._isIncluded=!1;return}let e=this.file.opts.filename;if(this.opts.filesList&&e&&!this.opts.filesList.includes(e)){this._isIncluded=!1;return}},visitor:{Program:{enter(e,t){let r=t.file.opts.filename;t.opts.replaceDictionaryEntry&&r===t.opts.dictionariesEntryPath&&(t._isDictEntry=!0,e.traverse({ImportDeclaration(e){e.remove()},VariableDeclarator(e){n.isObjectExpression(e.node.init)&&(e.node.init.properties=[])}}))},exit(e,u){if(u._isDictEntry||!u._isIncluded)return;let d=!1;if(e.traverse({CallExpression(e){let t=e.node.callee;if(!n.isIdentifier(t)||u._callerMap?.get(t.name)!==`useIntlayer`)return;let r=e.node.arguments[0],i;if(r&&n.isStringLiteral(r)?i=r.value:r&&n.isTemplateLiteral(r)&&r.expressions.length===0&&r.quasis.length===1&&(i=r.quasis[0].value.cooked??r.quasis[0].value.raw),!i)return;let a=u.opts.dictionaryModeMap?.[i];(a===`dynamic`||a===`fetch`)&&(d=!0)}}),e.traverse({ImportDeclaration(e){let t=e.node.source.value;if(r.includes(t)){u._hasValidImport=!0;for(let r of e.node.specifiers){if(!n.isImportSpecifier(r))continue;let e=n.isIdentifier(r.imported)?r.imported.name:r.imported.value;i.includes(e)&&u._callerMap?.set(r.local.name,e);let c=u.opts.importMode,l=(c===`dynamic`||c===`fetch`||d)&&a.includes(t);l&&(u._useDynamicHelpers=!0);let f;f=l?{...o,...s}:o;let p=f[e];p&&(r.imported=n.identifier(p))}}},CallExpression(e){let r=e.node.callee;if(!n.isIdentifier(r))return;let i=u._callerMap?.get(r.name);if(!i)return;u._hasValidImport=!0;let a=e.node.arguments[0],o;if(a&&n.isStringLiteral(a)?o=a.value:a&&n.isTemplateLiteral(a)&&a.expressions.length===0&&a.quasis.length===1&&(o=a.quasis[0].value.cooked??a.quasis[0].value.raw),!o)return;let s=u.opts.importMode,l=i===`useIntlayer`,d=!!u._useDynamicHelpers,f=`static`,p=u.opts.dictionaryModeMap?.[o];l&&d?p?f=p:s===`dynamic`?f=`dynamic`:s===`fetch`&&(f=`fetch`):l&&!d&&(p===`dynamic`||p===`fetch`)&&(f=p);let m;if(f===`fetch`){let r=u._newDynamicImports?.get(o);if(!r){let e=(0,t.getFileHash)(o);r=n.identifier(`_${e}_fetch`),u._newDynamicImports?.set(o,r)}m=r,e.node.arguments=[n.identifier(m.name),...e.node.arguments]}else if(f===`dynamic`){let r=u._newDynamicImports?.get(o);if(!r){let e=(0,t.getFileHash)(o);r=n.identifier(`_${e}_dyn`),u._newDynamicImports?.set(o,r)}m=r,e.node.arguments=[n.identifier(m.name),...e.node.arguments]}else{let t=u._newStaticImports?.get(o);t||(t=c(o,n),u._newStaticImports?.set(o,t)),m=t,e.node.arguments[0]=n.identifier(m.name)}}}),!u._hasValidImport)return;let f=u.file.opts.filename,p=u.opts.dictionariesDir,m=u.opts.dynamicDictionariesDir,h=u.opts.fetchDictionariesDir,g=[];for(let[e,t]of u._newStaticImports){let r=l(f,p,m,h,e,`static`),i=n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r));i.attributes=[n.importAttribute(n.identifier(`type`),n.stringLiteral(`json`))],g.push(i)}for(let[e,t]of u._newDynamicImports){let r=l(f,p,m,h,e,t.name.endsWith(`_fetch`)?`fetch`:`dynamic`);g.push(n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r)))}if(!g.length)return;let _=e.get(`body`),v=0;for(let e of _){let t=e.node;if(n.isExpressionStatement(t)&&n.isStringLiteral(t.expression)&&!t.expression.value.startsWith(`import`)&&!t.expression.value.startsWith(`require`))v+=1;else break}e.node.body.splice(v,0,...g)}}}}};exports.intlayerOptimizeBabelPlugin=u;
2
2
  //# sourceMappingURL=babel-plugin-intlayer-optimize.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar/utils';\nimport { normalizePath } from '@intlayer/config/utils';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n] as const;\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch';\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<string, 'static' | 'dynamic' | 'fetch'>;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n};\n\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, BabelTypes.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, BabelTypes.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n};\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (\n key: string,\n t: typeof BabelTypes\n): BabelTypes.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch'\n): string => {\n let relativePath = join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n relativePath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n relativePath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n let rel = relative(dirname(fromFile), relativePath);\n\n // Fix windows path\n rel = normalizePath(rel);\n\n // Fix relative path\n if (!rel.startsWith('./') && !rel.startsWith('../')) {\n rel = `./${rel}`;\n }\n\n return rel;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer\n * packages into optimized dictionary access patterns, automatically importing the required\n * dictionary files based on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer\n * import { getIntlayer } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Live Mode (`importMode = \"live\"`)\n *\n * Uses live-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"live\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"live\" value, the plugin will fallback to the dynamic impor\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename;\n if (this.opts.filesList && filename) {\n const isIncluded = this.opts.filesList.includes(filename);\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename;\n\n // Check if this is the correct file to transform\n\n if (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n\n // Traverse the program to surgically remove/edit specific parts\n programPath.traverse({\n // Remove all import statements (cleaning up 'sssss.json')\n ImportDeclaration(path) {\n path.remove();\n },\n\n // Find the variable definition and empty the object\n VariableDeclarator(path) {\n // We look for: const x = { ... }\n\n if (t.isObjectExpression(path.node.init)) {\n // Set the object properties to an empty array: {}\n path.node.init.properties = [];\n }\n },\n });\n\n // (Optional) Stop other plugins from processing this file further if needed\n // programPath.stop();\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n // Manual traversal to process imports and call expressions\n // This runs AFTER all other plugins' visitors have completed\n\n // Pre-pass to determine if we should use dynamic helpers\n let fileHasDynamicCall = false;\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n if (callee.name !== 'useIntlayer') return;\n\n const arg = path.node.arguments[0];\n\n if (!arg || !t.isStringLiteral(arg)) return;\n\n const key = arg.value;\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n fileHasDynamicCall = true;\n }\n },\n });\n\n programPath.traverse({\n /* Inspect every intlayer import */\n ImportDeclaration(path) {\n const src = path.node.source.value;\n\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n // ⚠️ We now key off *imported* name, *not* local name.\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers.\n const shouldUseDynamicHelpers =\n (importMode === 'dynamic' ||\n importMode === 'fetch' ||\n fileHasDynamicCall) &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseDynamicHelpers) {\n // Use dynamic helpers for useIntlayer when dynamic mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else {\n // Use static helpers by default\n helperMap = STATIC_IMPORT_FUNCTION as Record<string, string>;\n }\n\n const newIdentifier = helperMap[importedName];\n\n // Only rewrite when we actually have a mapping for the imported\n // specifier (ignore unrelated named imports).\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n },\n\n /* Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n if (!CALLER_LIST.includes(callee.name as any)) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn't import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n\n if (!arg || !t.isStringLiteral(arg)) return; // must be literal\n\n const key = arg.value;\n const importMode = state.opts.importMode;\n const isUseIntlayer = callee.name === 'useIntlayer';\n const useDynamicHelpers = Boolean(state._useDynamicHelpers);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'\n let perCallMode: 'static' | 'dynamic' | 'fetch' = 'static';\n\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (isUseIntlayer && useDynamicHelpers) {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'fetch') {\n perCallMode = 'fetch';\n }\n } else if (isUseIntlayer && !useDynamicHelpers) {\n // If dynamic helpers are NOT active (global mode is static),\n // we STILL might want to force dynamic/live for this specific call\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n let ident: BabelTypes.Identifier;\n\n if (perCallMode === 'fetch') {\n // Use fetch dictionaries entry (live mode for selected keys)\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_fetch`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Helper: first argument is the dictionary entry, second is the key\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else if (perCallMode === 'dynamic') {\n // Use dynamic dictionaries entry\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_dyn`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Dynamic helper: first argument is the dictionary, second is the key.\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else {\n // Use static imports for getIntlayer or useIntlayer when not using dynamic helpers\n let staticIdent = state._newStaticImports?.get(key);\n\n if (!staticIdent) {\n staticIdent = makeIdent(key, t);\n state._newStaticImports?.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with iden\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n });\n\n // Early-out if we touched nothing\n\n if (!state._hasValidImport) return;\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const fetchDictionariesDir = state.opts.fetchDictionariesDir;\n const imports: BabelTypes.ImportDeclaration[] = [];\n\n // Generate static JSON imports (getIntlayer always uses JSON dictionaries)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static'\n );\n\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n // Add 'type: json' attribute for JSON files\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic/fetch imports (for useIntlayer when using dynamic/live helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const modeForThisIdent: 'dynamic' | 'fetch' = ident.name.endsWith(\n '_fetch'\n )\n ? 'fetch'\n : 'dynamic';\n\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n modeForThisIdent\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get(\n 'body'\n ) as NodePath<BabelTypes.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n !stmt.expression.value.startsWith('import') &&\n !stmt.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, ...imports);\n },\n },\n },\n };\n};\n"],"mappings":"oNAMA,MAAM,EAAe,CACnB,WACA,iBACA,iBACA,wBACA,wBACA,gBACA,uBACA,uBACA,kBACA,eACA,mBACA,kBACA,iBACD,CAEK,EAAc,CAAC,cAAe,cAAc,CAK5C,EAAuB,CAC3B,iBACA,wBACA,wBACA,gBACA,uBACA,uBACA,kBACA,eACA,iBACA,kBACA,mBACD,CAEK,EAAyB,CAC7B,YAAa,gBACb,YAAa,gBACd,CAEK,EAA0B,CAC9B,YAAa,uBACd,CAiFK,GACJ,EACA,IAC0B,CAC1B,IAAM,GAAA,EAAA,EAAA,aAAmB,EAAI,CAC7B,OAAO,EAAE,WAAW,IAAI,IAAO,EAG3B,GACJ,EACA,EACA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AM,CAAC,EAAK,KAAU,EAAM,kBAAoB,CACnD,IAAM,EAAM,EACV,EACA,EACA,EACA,EACA,EACA,SACD,CAEK,EAAwB,EAAE,kBAC9B,CAAC,EAAE,uBAAuB,EAAE,WAAW,EAAM,KAAK,CAAC,CAAC,CACpD,EAAE,cAAc,EAAI,CACrB,CAGD,EAAsB,WAAa,CACjC,EAAE,gBAAgB,EAAE,WAAW,OAAO,CAAE,EAAE,cAAc,OAAO,CAAC,CACjE,CAED,EAAQ,KAAK,EAAsB,CAIrC,IAAK,GAAM,CAAC,EAAK,KAAU,EAAM,mBAAqB,CAOpD,IAAM,EAAM,EACV,EACA,EACA,EACA,EACA,EAX4C,EAAM,KAAK,SACvD,SACD,CACG,QACA,UASH,CACD,EAAQ,KACN,EAAE,kBACA,CAAC,EAAE,uBAAuB,EAAE,WAAW,EAAM,KAAK,CAAC,CAAC,CACpD,EAAE,cAAc,EAAI,CACrB,CACF,CAGH,GAAI,CAAC,EAAQ,OAAQ,OAGrB,IAAM,EAAY,EAAY,IAC5B,OACD,CACG,EAAY,EAChB,IAAK,IAAM,KAAY,EAAW,CAChC,IAAM,EAAO,EAAS,KAEtB,GACE,EAAE,sBAAsB,EAAK,EAC7B,EAAE,gBAAgB,EAAK,WAAW,EAClC,CAAC,EAAK,WAAW,MAAM,WAAW,SAAS,EAC3C,CAAC,EAAK,WAAW,MAAM,WAAW,UAAU,CAE5C,GAAa,OAEb,MAIJ,EAAY,KAAK,KAAK,OAAO,EAAW,EAAG,GAAG,EAAQ,EAEzD,CACF,CACF"}
1
+ {"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar/utils';\nimport { normalizePath } from '@intlayer/config/utils';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n] as const;\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch';\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<string, 'static' | 'dynamic' | 'fetch'>;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n};\n\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, BabelTypes.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, BabelTypes.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** map from local identifier name to the imported intlayer func name ('useIntlayer' | 'getIntlayer') */\n _callerMap?: Map<string, (typeof CALLER_LIST)[number]>;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n};\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (\n key: string,\n t: typeof BabelTypes\n): BabelTypes.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch'\n): string => {\n let relativePath = join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n relativePath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n relativePath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n let rel = relative(dirname(fromFile), relativePath);\n\n // Fix windows path\n rel = normalizePath(rel);\n\n // Fix relative path\n if (!rel.startsWith('./') && !rel.startsWith('../')) {\n rel = `./${rel}`;\n }\n\n return rel;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer\n * packages into optimized dictionary access patterns, automatically importing the required\n * dictionary files based on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer\n * import { getIntlayer } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Live Mode (`importMode = \"live\"`)\n *\n * Uses live-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"live\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"live\" value, the plugin will fallback to the dynamic impor\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._callerMap = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename;\n if (this.opts.filesList && filename) {\n const isIncluded = this.opts.filesList.includes(filename);\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename;\n\n // Check if this is the correct file to transform\n\n if (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n\n // Traverse the program to surgically remove/edit specific parts\n programPath.traverse({\n // Remove all import statements (cleaning up 'sssss.json')\n ImportDeclaration(path) {\n path.remove();\n },\n\n // Find the variable definition and empty the object\n VariableDeclarator(path) {\n // We look for: const x = { ... }\n\n if (t.isObjectExpression(path.node.init)) {\n // Set the object properties to an empty array: {}\n path.node.init.properties = [];\n }\n },\n });\n\n // (Optional) Stop other plugins from processing this file further if needed\n // programPath.stop();\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n // Manual traversal to process imports and call expressions\n // This runs AFTER all other plugins' visitors have completed\n\n // Pre-pass to determine if we should use dynamic helpers\n let fileHasDynamicCall = false;\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (originalImportedName !== 'useIntlayer') return;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return;\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n fileHasDynamicCall = true;\n }\n },\n });\n\n programPath.traverse({\n /* Inspect every intlayer import */\n ImportDeclaration(path) {\n const src = path.node.source.value;\n\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n if (CALLER_LIST.includes(importedName as any)) {\n state._callerMap?.set(\n spec.local.name,\n importedName as (typeof CALLER_LIST)[number]\n );\n }\n\n const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers.\n const shouldUseDynamicHelpers =\n (importMode === 'dynamic' ||\n importMode === 'fetch' ||\n fileHasDynamicCall) &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseDynamicHelpers) {\n // Use dynamic helpers for useIntlayer when dynamic mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else {\n // Use static helpers by default\n helperMap = STATIC_IMPORT_FUNCTION as Record<string, string>;\n }\n\n const newIdentifier = helperMap[importedName];\n\n // Only rewrite when we actually have a mapping for the imported\n // specifier (ignore unrelated named imports).\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n },\n\n /* Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (!originalImportedName) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn't import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return; // must be a static literal\n const importMode = state.opts.importMode;\n const isUseIntlayer = originalImportedName === 'useIntlayer';\n const useDynamicHelpers = Boolean(state._useDynamicHelpers);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'\n let perCallMode: 'static' | 'dynamic' | 'fetch' = 'static';\n\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (isUseIntlayer && useDynamicHelpers) {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'fetch') {\n perCallMode = 'fetch';\n }\n } else if (isUseIntlayer && !useDynamicHelpers) {\n // If dynamic helpers are NOT active (global mode is static),\n // we STILL might want to force dynamic/live for this specific call\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n let ident: BabelTypes.Identifier;\n\n if (perCallMode === 'fetch') {\n // Use fetch dictionaries entry (live mode for selected keys)\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_fetch`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Helper: first argument is the dictionary entry, second is the key\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else if (perCallMode === 'dynamic') {\n // Use dynamic dictionaries entry\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getFileHash(key);\n dynamicIdent = t.identifier(`_${hash}_dyn`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Dynamic helper: first argument is the dictionary, second is the key.\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else {\n // Use static imports for getIntlayer or useIntlayer when not using dynamic helpers\n let staticIdent = state._newStaticImports?.get(key);\n\n if (!staticIdent) {\n staticIdent = makeIdent(key, t);\n state._newStaticImports?.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with iden\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n });\n\n // Early-out if we touched nothing\n\n if (!state._hasValidImport) return;\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const fetchDictionariesDir = state.opts.fetchDictionariesDir;\n const imports: BabelTypes.ImportDeclaration[] = [];\n\n // Generate static JSON imports (getIntlayer always uses JSON dictionaries)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static'\n );\n\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n // Add 'type: json' attribute for JSON files\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic/fetch imports (for useIntlayer when using dynamic/live helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const modeForThisIdent: 'dynamic' | 'fetch' = ident.name.endsWith(\n '_fetch'\n )\n ? 'fetch'\n : 'dynamic';\n\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n modeForThisIdent\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get(\n 'body'\n ) as NodePath<BabelTypes.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n !stmt.expression.value.startsWith('import') &&\n !stmt.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, ...imports);\n },\n },\n },\n };\n};\n"],"mappings":"oNAMA,MAAM,EAAe,CACnB,WACA,iBACA,iBACA,wBACA,wBACA,gBACA,uBACA,uBACA,kBACA,eACA,mBACA,kBACA,iBACD,CAEK,EAAc,CAAC,cAAe,cAAc,CAK5C,EAAuB,CAC3B,iBACA,wBACA,wBACA,gBACA,uBACA,uBACA,kBACA,eACA,iBACA,kBACA,mBACD,CAEK,EAAyB,CAC7B,YAAa,gBACb,YAAa,gBACd,CAEK,EAA0B,CAC9B,YAAa,uBACd,CAmFK,GACJ,EACA,IAC0B,CAC1B,IAAM,GAAA,EAAA,EAAA,aAAmB,EAAI,CAC7B,OAAO,EAAE,WAAW,IAAI,IAAO,EAG3B,GACJ,EACA,EACA,EACA,EACA,EACA,IACW,CACX,IAAI,GAAA,EAAA,EAAA,MAAoB,EAAiB,GAAG,EAAI,OAAO,CAEnD,IAAe,UACjB,GAAA,EAAA,EAAA,MAAoB,EAAsB,GAAG,EAAI,MAAM,EAGrD,IAAe,YACjB,GAAA,EAAA,EAAA,MAAoB,EAAwB,GAAG,EAAI,MAAM,EAG3D,IAAI,GAAA,EAAA,EAAA,WAAA,EAAA,EAAA,SAAuB,EAAS,CAAE,EAAa,CAUnD,MAPA,IAAA,EAAA,EAAA,eAAoB,EAAI,CAGpB,CAAC,EAAI,WAAW,KAAK,EAAI,CAAC,EAAI,WAAW,MAAM,GACjD,EAAM,KAAK,KAGN,GAqFI,EAA+B,GAEpB,CACtB,GAAM,CAAE,MAAO,GAAM,EAErB,MAAO,CACL,KAAM,kCAEN,KAAM,CAUJ,GATA,KAAK,kBAAoB,IAAI,IAC7B,KAAK,mBAAqB,IAAI,IAC9B,KAAK,WAAa,IAAI,IACtB,KAAK,YAAc,GACnB,KAAK,gBAAkB,GACvB,KAAK,aA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D,EAAE,cAAc,EAAI,CACrB,CAGD,EAAsB,WAAa,CACjC,EAAE,gBAAgB,EAAE,WAAW,OAAO,CAAE,EAAE,cAAc,OAAO,CAAC,CACjE,CAED,EAAQ,KAAK,EAAsB,CAIrC,IAAK,GAAM,CAAC,EAAK,KAAU,EAAM,mBAAqB,CAOpD,IAAM,EAAM,EACV,EACA,EACA,EACA,EACA,EAX4C,EAAM,KAAK,SACvD,SACD,CACG,QACA,UASH,CACD,EAAQ,KACN,EAAE,kBACA,CAAC,EAAE,uBAAuB,EAAE,WAAW,EAAM,KAAK,CAAC,CAAC,CACpD,EAAE,cAAc,EAAI,CACrB,CACF,CAGH,GAAI,CAAC,EAAQ,OAAQ,OAGrB,IAAM,EAAY,EAAY,IAC5B,OACD,CACG,EAAY,EAChB,IAAK,IAAM,KAAY,EAAW,CAChC,IAAM,EAAO,EAAS,KAEtB,GACE,EAAE,sBAAsB,EAAK,EAC7B,EAAE,gBAAgB,EAAK,WAAW,EAClC,CAAC,EAAK,WAAW,MAAM,WAAW,SAAS,EAC3C,CAAC,EAAK,WAAW,MAAM,WAAW,UAAU,CAE5C,GAAa,OAEb,MAIJ,EAAY,KAAK,KAAK,OAAO,EAAW,EAAG,GAAG,EAAQ,EAEzD,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:fs`),t=require(`node:path`),n=require(`node:fs/promises`),r=require(`@intlayer/chokidar/build`),i=require(`@intlayer/config/client`),a=require(`@intlayer/config/node`);const o=(o=process.env.INTLAYER_IS_DEV_COMMAND)=>{let s=(0,a.getConfiguration)(),{baseDir:c}=s.content,l=(0,t.join)(c,s.compiler?.outputDir??`compiler`),u=async t=>{try{if(!(0,e.existsSync)(t))return null;let r=await(0,n.readFile)(t,`utf-8`);if(!r||r.trim()===``)return null;let i=JSON.parse(r);return Array.isArray(i)?i[0]??null:i}catch(r){return(0,e.existsSync)(t)&&(await(0,n.readFile)(t,`utf-8`)).trim()!==``&&console.warn(`[intlayer] Warning: Failed to read existing dictionary at ${t}. It might be corrupt. Translations may be lost. Error:`,r),null}},d=(e,t,n)=>{let r={},i=t?.content,a=Object.keys(e).sort();for(let t of a){let a=e[t],o=i?.[t];o&&o.nodeType===`translation`&&o.translation?r[t]={...o,nodeType:`translation`,translation:{...o.translation,[n]:o.translation[n]??a}}:r[t]={nodeType:`translation`,translation:{[n]:a}}}return r},f=async e=>{let{dictionaryKey:n,content:i,locale:a}=e;try{let e=await u((0,t.join)(l,`${n}.content.json`)),o=d(i,e,a),f={...e,key:n,content:o,filePath:(0,t.join)((0,t.relative)(c,l),`${n}.content.json`)},p=await(0,r.writeContentDeclaration)(f,s,{newDictionariesPath:(0,t.relative)(c,l)});await(0,r.buildDictionary)([{...f,filePath:(0,t.relative)(c,p.path)}],s)}catch(e){if(console.error(`[intlayer] Failed to process extracted content for ${n}:`,e),e instanceof SyntaxError&&e.message.includes(`Unexpected end of JSON input`)){let t=e.message.match(/^(.*\.json):\s*Unexpected end of JSON input/);if(t){let e=t[1];try{let t=require(`fs`).readFileSync(e,`utf-8`);console.error(`[intlayer] Content of the corrupted file (${e}):\n"${t}"`)}catch(t){console.error(`[intlayer] Could not read corrupted file ${e}`,t)}}}}},p=String(o)===`true`,m=s.compiler?.enabled===`build-only`?!p:s.compiler?.enabled??!0,h=(0,i.getAppLogger)(s);return s.compiler?.enabled===`build-only`&&p&&h(`${(0,i.colorize)(`Compiler:`,i.ANSIColors.GREY_DARK)} i18n function is not inserted in the code in dev mode to optimize build time. (to test i18n in dev mode set compiler.enabled to true)`),{enabled:m,defaultLocale:s.internationalization.defaultLocale,prefix:s.compiler?.dictionaryKeyPrefix,onExtract:f}};exports.getExtractPluginOptions=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:fs`),t=require(`node:path`),n=require(`@intlayer/config/client`),r=require(`@intlayer/config/node`),i=require(`node:fs/promises`),a=require(`@intlayer/chokidar/build`);const o=(o=process.env.INTLAYER_IS_DEV_COMMAND)=>{let s=(0,r.getConfiguration)(),{baseDir:c}=s.content,l=(0,t.join)(c,s.compiler?.outputDir??`compiler`),u=async t=>{try{if(!(0,e.existsSync)(t))return null;let n=await(0,i.readFile)(t,`utf-8`);if(!n||n.trim()===``)return null;let r=JSON.parse(n);return Array.isArray(r)?r[0]??null:r}catch(n){return(0,e.existsSync)(t)&&(await(0,i.readFile)(t,`utf-8`)).trim()!==``&&console.warn(`[intlayer] Warning: Failed to read existing dictionary at ${t}. It might be corrupt. Translations may be lost. Error:`,n),null}},d=(e,t,n)=>{let r={},i=t?.content,a=Object.keys(e).sort();for(let t of a){let a=e[t],o=i?.[t];o&&o.nodeType===`translation`&&o.translation?r[t]={...o,nodeType:`translation`,translation:{...o.translation,[n]:o.translation[n]??a}}:r[t]={nodeType:`translation`,translation:{[n]:a}}}return r},f=async e=>{let{dictionaryKey:n,content:r,locale:i}=e;try{let e=await u((0,t.join)(l,`${n}.content.json`)),o=d(r,e,i),f={...e,key:n,content:o,filePath:(0,t.join)((0,t.relative)(c,l),`${n}.content.json`)},p=await(0,a.writeContentDeclaration)(f,s,{newDictionariesPath:(0,t.relative)(c,l)});await(0,a.buildDictionary)([{...f,filePath:(0,t.relative)(c,p.path)}],s)}catch(e){if(console.error(`[intlayer] Failed to process extracted content for ${n}:`,e),e instanceof SyntaxError&&e.message.includes(`Unexpected end of JSON input`)){let t=e.message.match(/^(.*\.json):\s*Unexpected end of JSON input/);if(t){let e=t[1];try{let t=require(`fs`).readFileSync(e,`utf-8`);console.error(`[intlayer] Content of the corrupted file (${e}):\n"${t}"`)}catch(t){console.error(`[intlayer] Could not read corrupted file ${e}`,t)}}}}},p=String(o)===`true`,m=s.compiler?.enabled===`build-only`?!p:s.compiler?.enabled??!0,h=(0,n.getAppLogger)(s);return s.compiler?.enabled===`build-only`&&p&&h(`${(0,n.colorize)(`Compiler:`,n.ANSIColors.GREY_DARK)} i18n function is not inserted in the code in dev mode to optimize build time. (to test i18n in dev mode set compiler.enabled to true)`),{enabled:m,defaultLocale:s.internationalization.defaultLocale,prefix:s.compiler?.dictionaryKeyPrefix,saveComponents:s.compiler?.saveComponents,onExtract:f}};exports.getExtractPluginOptions=o;
2
2
  //# sourceMappingURL=getExtractPluginOptions.cjs.map