@intlayer/babel 8.3.0 → 8.3.2
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/dist/cjs/babel-plugin-intlayer-extract.cjs +1 -1
- package/dist/cjs/babel-plugin-intlayer-extract.cjs.map +1 -1
- package/dist/cjs/extractContent/contentWriter.cjs +1 -1
- package/dist/cjs/extractContent/contentWriter.cjs.map +1 -1
- package/dist/cjs/extractContent/extractContent.cjs +1 -1
- package/dist/cjs/extractContent/extractContent.cjs.map +1 -1
- package/dist/cjs/extractContent/processTsxFile.cjs +2 -2
- package/dist/cjs/extractContent/processTsxFile.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs +1 -1
- package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs +1 -1
- package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/resolveDictionaryKey.cjs.map +1 -1
- package/dist/cjs/getExtractPluginOptions.cjs +1 -1
- package/dist/cjs/getExtractPluginOptions.cjs.map +1 -1
- package/dist/cjs/getOptimizePluginOptions.cjs +1 -1
- package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-extract.mjs +1 -1
- package/dist/esm/babel-plugin-intlayer-extract.mjs.map +1 -1
- package/dist/esm/extractContent/contentWriter.mjs +1 -1
- package/dist/esm/extractContent/contentWriter.mjs.map +1 -1
- package/dist/esm/extractContent/extractContent.mjs +1 -1
- package/dist/esm/extractContent/extractContent.mjs.map +1 -1
- package/dist/esm/extractContent/processTsxFile.mjs +3 -3
- package/dist/esm/extractContent/processTsxFile.mjs.map +1 -1
- package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs +1 -1
- package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs.map +1 -1
- package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs +1 -1
- package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs.map +1 -1
- package/dist/esm/extractContent/utils/resolveDictionaryKey.mjs.map +1 -1
- package/dist/esm/getExtractPluginOptions.mjs +1 -1
- package/dist/esm/getExtractPluginOptions.mjs.map +1 -1
- package/dist/esm/getOptimizePluginOptions.mjs +1 -1
- package/dist/esm/getOptimizePluginOptions.mjs.map +1 -1
- package/dist/types/extractContent/contentWriter.d.ts.map +1 -1
- package/dist/types/extractContent/extractContent.d.ts +15 -6
- package/dist/types/extractContent/extractContent.d.ts.map +1 -1
- package/dist/types/extractContent/processTsxFile.d.ts.map +1 -1
- package/dist/types/extractContent/utils/extractDictionaryInfo.d.ts.map +1 -1
- package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts +11 -5
- package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts.map +1 -1
- package/dist/types/extractContent/utils/index.d.ts +2 -2
- package/dist/types/getExtractPluginOptions.d.ts +1 -1
- package/dist/types/getExtractPluginOptions.d.ts.map +1 -1
- package/dist/types/getOptimizePluginOptions.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./extractContent/utils/detectPackageName.cjs`),t=require(`./extractContent/extractContent.cjs`);let n=require(`@intlayer/config/logger`),r=require(`node:path`),i=require(`@babel/parser`);const a=a=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(a,o){let s=o.opts;if(s.enabled===!1)return;let c=o.file.opts.filename;if(!c||s.filesList&&!s.filesList.includes(c))return;let l=o.file.code??``;if(!l)return;let u=(0,n.getAppLogger)(s.configuration),d=s.packageName??e.detectPackageName(c),{saveComponents:f}=s.configuration.compiler,p=t.extractContentSync(c,d,{configuration:s.configuration,code:l,onExtract:e=>{s.onExtract&&s.onExtract({dictionaryKey:e.key,filePath:c,content:e.content,locale:s.configuration.internationalization.defaultLocale})},declarationOnly:!f});if(!p)return;let{transformedCode:m}=p;if(m)try{let e=(0,i.parse)(m,{sourceType:`module`,plugins:[`jsx`,`typescript`]});a.node.body=e.program.body,a.node.directives=e.program.directives,u(`${(0,n.colorize)(`Compiler:`,n.ANSIColors.GREY_DARK)} Extracted content from ${(0,n.colorizePath)((0,r.relative)(s.configuration.system.baseDir,c))}`,{level:`debug`})}catch(e){
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./extractContent/utils/detectPackageName.cjs`),t=require(`./extractContent/extractContent.cjs`);let n=require(`@intlayer/config/logger`),r=require(`node:path`),i=require(`@babel/parser`);const a=a=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(a,o){let s=o.opts;if(s.enabled===!1)return;let c=o.file.opts.filename;if(!c||s.filesList&&!s.filesList.includes(c))return;let l=o.file.code??``;if(!l)return;let u=(0,n.getAppLogger)(s.configuration),d=s.packageName??e.detectPackageName(c),{saveComponents:f}=s.configuration.compiler,p=t.extractContentSync(c,d,{configuration:s.configuration,code:l,onExtract:e=>{s.onExtract&&s.onExtract({dictionaryKey:e.key,filePath:c,content:e.content,locale:s.configuration.internationalization.defaultLocale})},declarationOnly:!f});if(!p)return;let{transformedCode:m}=p;if(m)try{let e=(0,i.parse)(m,{sourceType:`module`,plugins:[`jsx`,`typescript`]});a.node.body=e.program.body,a.node.directives=e.program.directives,u(`${(0,n.colorize)(`Compiler:`,n.ANSIColors.GREY_DARK)} Extracted content from ${(0,n.colorizePath)((0,r.relative)(s.configuration.system.baseDir,c))}`,{level:`debug`})}catch(e){u([`Failed to parse transformed code for ${(0,n.colorizePath)((0,r.relative)(s.configuration.system.baseDir,c))}:`,e],{level:`error`})}}}}});exports.intlayerExtractBabelPlugin=a;
|
|
2
2
|
//# sourceMappingURL=babel-plugin-intlayer-extract.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["detectPackageName","extractContentSync","ANSIColors"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["detectPackageName","extractContentSync","ANSIColors"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n opts.onExtract({\n dictionaryKey: extractResult.key,\n filePath: filename,\n content: extractResult.content,\n locale: opts.configuration.internationalization.defaultLocale,\n });\n }\n },\n declarationOnly: !saveComponents,\n });\n\n if (!result) return;\n\n const { transformedCode: modifiedCode } = result;\n\n if (!modifiedCode) return;\n\n // Replace the Babel AST with the transformed code by re-parsing it.\n // This lets Babel serialise the injected hooks/imports through its\n // own code generator, preserving compatibility with other plugins.\n try {\n const newAst = parse(modifiedCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n programPath.node.body = newAst.program.body;\n programPath.node.directives = newAst.program.directives;\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted content from ${colorizePath(relative(opts.configuration.system.baseDir, filename))}`,\n { level: 'debug' }\n );\n } catch (error) {\n appLogger(\n [\n `Failed to parse transformed code for ${colorizePath(relative(opts.configuration.system.baseDir, filename))}:`,\n error,\n ],\n { level: 'error' }\n );\n }\n },\n },\n },\n };\n};\n"],"mappings":"2TA8DA,MAAa,EAA8B,IAGlC,CACL,KAAM,gCAEN,QAAS,CACP,QAAS,CACP,MAAM,EAAa,EAAO,CACxB,IAAM,EAAO,EAAM,KAKnB,GAFkB,EAAK,UAEL,GAAO,OAEzB,IAAM,EAAW,EAAM,KAAK,KAAK,SAIjC,GAFI,CAAC,GAED,EAAK,WAAa,CAAC,EAAK,UAAU,SAAS,EAAS,CAAE,OAE1D,IAAM,EAAmB,EAAM,KAAK,MAAQ,GAC5C,GAAI,CAAC,EAAU,OAEf,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAK,cAAc,CAC5C,EAAc,EAAK,aAAeA,EAAAA,kBAAkB,EAAS,CAE7D,CAAE,kBAAmB,EAAK,cAAc,SAExC,EAASC,EAAAA,mBAAmB,EAAU,EAAa,CACvD,cAAe,EAAK,cACpB,KAAM,EACN,UAAY,GAGN,CACA,EAAK,WACP,EAAK,UAAU,CACb,cAAe,EAAc,IAC7B,SAAU,EACV,QAAS,EAAc,QACvB,OAAQ,EAAK,cAAc,qBAAqB,cACjD,CAAC,EAGN,gBAAiB,CAAC,EACnB,CAAC,CAEF,GAAI,CAAC,EAAQ,OAEb,GAAM,CAAE,gBAAiB,GAAiB,EAErC,KAKL,GAAI,CACF,IAAM,GAAA,EAAA,EAAA,OAAe,EAAc,CACjC,WAAY,SACZ,QAAS,CAAC,MAAO,aAAa,CAC/B,CAAC,CAEF,EAAY,KAAK,KAAO,EAAO,QAAQ,KACvC,EAAY,KAAK,WAAa,EAAO,QAAQ,WAE7C,EACE,IAAA,EAAA,EAAA,UAAY,YAAaC,EAAAA,WAAW,UAAU,CAAC,2BAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAAgD,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,GAC5I,CAAE,MAAO,QAAS,CACnB,OACM,EAAO,CACd,EACE,CACE,yCAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAA8D,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,CAAC,GAC5G,EACD,CACD,CAAE,MAAO,QAAS,CACnB,GAGN,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/extractDictionaryInfo.cjs`);let t=require(`node:fs`),n=require(`node:fs/promises`),r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/core/plugins`),o;const s=(e,t,n)=>{let r=(0,a.insertContentInDictionary)(t??{key:``,content:{},filePath:``},e,n).content,i={};for(let t in e)i[t]=r[t];return i},
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/extractDictionaryInfo.cjs`);let t=require(`node:fs`),n=require(`node:fs/promises`),r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/core/plugins`),o=require(`@intlayer/types/nodeType`);const s=e=>/\{\{[^}]+\}\}/.test(e),c=e=>{let t=[],n=/\{\{([^}]+)\}\}/g,r;for(let i=n.exec(e);i!==null;i=n.exec(e)){r=i;let e=r[1].trim();t.includes(e)||t.push(e)}return t};let l;const u=(e,t,n)=>{let r=(0,a.insertContentInDictionary)(t??{key:``,content:{},filePath:``},e,n).content,i={};for(let t in e)i[t]=r[t];for(let t in e){let n=e[t];if(typeof n==`string`&&s(n)){let e=i[t];e&&e.nodeType===o.NodeType.Translation&&(i[t]={nodeType:o.NodeType.Insertion,[o.NodeType.Insertion]:e,fields:c(n)})}}return i},d=(e,t)=>{let n=(0,a.insertContentInDictionary)(t??{key:``,content:{},filePath:``},e).content,r={};for(let t in e)r[t]=n[t];for(let t in e){let n=e[t];if(typeof n==`string`&&s(n)){let e=r[t];typeof e==`string`&&(r[t]={nodeType:o.NodeType.Insertion,[o.NodeType.Insertion]:e,fields:c(n)})}}return r},f=async(a,o,s,c)=>{let{absolutePath:f,isPerLocale:p}=await e.resolveContentFilePaths(s,o,c),{defaultLocale:m}=c.internationalization,{baseDir:h}=c.system;l||=await(0,i.ensureIntlayerBundle)(c);let g=(0,r.dirname)(f);await(0,n.mkdir)(g,{recursive:!0});let _=null;if((0,t.existsSync)(f))try{_=await(0,i.loadContentDeclaration)(f,c,l)??null}catch(e){console.error(e)}let v=(0,r.relative)(h,f),y;if(p){let e=d(a,_);y={..._,key:o,content:e,locale:m,filePath:v}}else{let e=u(a,_,m);y={..._,key:o,content:e,filePath:v}}let b=(0,r.relative)(h,g),x=await(0,i.writeContentDeclaration)(y,c,{newDictionariesPath:b,localeList:[m]});return await(0,i.buildDictionary)([{...y,filePath:(0,r.relative)(h,x?.path??f)}],c),f};exports.mergeWithExistingMultilingualDictionary=u,exports.mergeWithExistingPerLocaleDictionary=d,exports.writeContentHelper=f;
|
|
2
2
|
//# sourceMappingURL=contentWriter.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contentWriter.cjs","names":["resolveContentFilePaths"],"sources":["../../../src/extractContent/contentWriter.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n buildDictionary,\n ensureIntlayerBundle,\n loadContentDeclaration,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { insertContentInDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport { resolveContentFilePaths } from './utils/extractDictionaryInfo';\n\n/**\n * Translation node structure used in dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\n/**\n * Dictionary content structure - map of keys to translation nodes\n */\ntype DictionaryContentMap = Record<string, TranslationNode>;\n\n/**\n * Cached bundle file path to optimize performance\n */\nlet cachedBundleFilePath: string | undefined;\n\n/**\n * Merge extracted content with existing dictionary for multilingual format.\n * - Keys in extracted but not in existing: added with default locale only\n * - Keys in both: preserve existing translations, update default locale value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingMultilingualDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null,\n defaultLocale: string\n): DictionaryContentMap => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent,\n defaultLocale as Locale\n );\n\n const mergedContent = mergedDictionary.content as DictionaryContentMap;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: DictionaryContentMap = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n return finalContent;\n};\n\n/**\n * Merge extracted content with existing dictionary for per-locale format.\n * - Keys in extracted but not in existing: added\n * - Keys in both: update value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingPerLocaleDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null\n): Record<string, string> => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent\n );\n\n const mergedContent = mergedDictionary.content as Record<string, string>;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: Record<string, string> = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n return finalContent;\n};\n\n/**\n * Helper to write extracted content to dictionary file(s).\n */\nexport const writeContentHelper = async (\n extractedContent: Record<string, string>,\n dictionaryKey: DictionaryKey,\n filePath: string,\n configuration: IntlayerConfig\n): Promise<string> => {\n const { absolutePath, isPerLocale } = await resolveContentFilePaths(\n filePath,\n dictionaryKey,\n configuration\n );\n\n const { defaultLocale } = configuration.internationalization;\n const { baseDir } = configuration.system;\n\n if (!cachedBundleFilePath) {\n cachedBundleFilePath = await ensureIntlayerBundle(configuration);\n }\n\n const outputDir = dirname(absolutePath);\n\n // Ensure output directory exists\n await mkdir(outputDir, { recursive: true });\n\n // Read existing dictionary to preserve translations and metadata\n let existingDictionary: Dictionary | null = null;\n\n if (existsSync(absolutePath)) {\n try {\n const dictionary = await loadContentDeclaration(\n absolutePath,\n configuration,\n cachedBundleFilePath\n );\n\n existingDictionary = dictionary ?? null;\n } catch (error) {\n console.error(error);\n }\n }\n\n const relativeContentFilePath = relative(baseDir, absolutePath);\n\n let mergedDictionary: Dictionary;\n\n if (isPerLocale) {\n // Per-locale format: simple string content for a single locale\n const mergedContent = mergeWithExistingPerLocaleDictionary(\n extractedContent,\n existingDictionary\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes for multiple locales\n const mergedContent = mergeWithExistingMultilingualDictionary(\n extractedContent,\n existingDictionary,\n defaultLocale\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, outputDir);\n\n const writeResult = await writeContentDeclaration(\n mergedDictionary,\n configuration,\n {\n newDictionariesPath: relativeDir,\n localeList: [defaultLocale],\n }\n );\n\n // Build the dictionary immediately\n const dictionaryToBuild: Dictionary = {\n ...mergedDictionary,\n filePath: relative(baseDir, writeResult?.path ?? absolutePath),\n };\n\n await buildDictionary([dictionaryToBuild], configuration);\n\n return absolutePath;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"contentWriter.cjs","names":["NodeType","resolveContentFilePaths"],"sources":["../../../src/extractContent/contentWriter.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n buildDictionary,\n ensureIntlayerBundle,\n loadContentDeclaration,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { insertContentInDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport { NodeType } from '@intlayer/types/nodeType';\nimport { resolveContentFilePaths } from './utils/extractDictionaryInfo';\n\nconst hasInsertionVars = (str: string): boolean => /\\{\\{[^}]+\\}\\}/.test(str);\n\nconst getInsertionFields = (template: string): string[] => {\n const fields: string[] = [];\n const regex = /\\{\\{([^}]+)\\}\\}/g;\n let match: RegExpExecArray | null;\n for (\n let result = regex.exec(template);\n result !== null;\n result = regex.exec(template)\n ) {\n match = result;\n const field = match[1].trim();\n if (!fields.includes(field)) fields.push(field);\n }\n return fields;\n};\n\n/**\n * Translation node structure used in dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\n/**\n * Dictionary content structure - map of keys to translation nodes\n */\ntype DictionaryContentMap = Record<string, TranslationNode>;\n\n/**\n * Cached bundle file path to optimize performance\n */\nlet cachedBundleFilePath: string | undefined;\n\n/**\n * Merge extracted content with existing dictionary for multilingual format.\n * - Keys in extracted but not in existing: added with default locale only\n * - Keys in both: preserve existing translations, update default locale value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingMultilingualDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null,\n defaultLocale: string\n): DictionaryContentMap => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent,\n defaultLocale as Locale\n );\n\n const mergedContent = mergedDictionary.content as DictionaryContentMap;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: DictionaryContentMap = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n // Promote any key whose source text contains {{vars}} to an insertion node\n for (const key in extractedContent) {\n const rawValue = extractedContent[key];\n if (typeof rawValue === 'string' && hasInsertionVars(rawValue)) {\n const node = finalContent[key] as any;\n if (node && node.nodeType === NodeType.Translation) {\n (finalContent as any)[key] = {\n nodeType: NodeType.Insertion,\n [NodeType.Insertion]: node,\n fields: getInsertionFields(rawValue),\n };\n }\n }\n }\n\n return finalContent;\n};\n\n/**\n * Merge extracted content with existing dictionary for per-locale format.\n * - Keys in extracted but not in existing: added\n * - Keys in both: update value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingPerLocaleDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null\n): Record<string, string> => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent\n );\n\n const mergedContent = mergedDictionary.content as Record<string, string>;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: Record<string, string> = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n // Promote any key whose source text contains {{vars}} to an insertion node\n for (const key in extractedContent) {\n const rawValue = extractedContent[key];\n if (typeof rawValue === 'string' && hasInsertionVars(rawValue)) {\n const currentVal = finalContent[key];\n if (typeof currentVal === 'string') {\n (finalContent as any)[key] = {\n nodeType: NodeType.Insertion,\n [NodeType.Insertion]: currentVal,\n fields: getInsertionFields(rawValue),\n };\n }\n }\n }\n\n return finalContent;\n};\n\n/**\n * Helper to write extracted content to dictionary file(s).\n */\nexport const writeContentHelper = async (\n extractedContent: Record<string, string>,\n dictionaryKey: DictionaryKey,\n filePath: string,\n configuration: IntlayerConfig\n): Promise<string> => {\n const { absolutePath, isPerLocale } = await resolveContentFilePaths(\n filePath,\n dictionaryKey,\n configuration\n );\n\n const { defaultLocale } = configuration.internationalization;\n const { baseDir } = configuration.system;\n\n if (!cachedBundleFilePath) {\n cachedBundleFilePath = await ensureIntlayerBundle(configuration);\n }\n\n const outputDir = dirname(absolutePath);\n\n // Ensure output directory exists\n await mkdir(outputDir, { recursive: true });\n\n // Read existing dictionary to preserve translations and metadata\n let existingDictionary: Dictionary | null = null;\n\n if (existsSync(absolutePath)) {\n try {\n const dictionary = await loadContentDeclaration(\n absolutePath,\n configuration,\n cachedBundleFilePath\n );\n\n existingDictionary = dictionary ?? null;\n } catch (error) {\n console.error(error);\n }\n }\n\n const relativeContentFilePath = relative(baseDir, absolutePath);\n\n let mergedDictionary: Dictionary;\n\n if (isPerLocale) {\n // Per-locale format: simple string content for a single locale\n const mergedContent = mergeWithExistingPerLocaleDictionary(\n extractedContent,\n existingDictionary\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes for multiple locales\n const mergedContent = mergeWithExistingMultilingualDictionary(\n extractedContent,\n existingDictionary,\n defaultLocale\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, outputDir);\n\n const writeResult = await writeContentDeclaration(\n mergedDictionary,\n configuration,\n {\n newDictionariesPath: relativeDir,\n localeList: [defaultLocale],\n }\n );\n\n // Build the dictionary immediately\n const dictionaryToBuild: Dictionary = {\n ...mergedDictionary,\n filePath: relative(baseDir, writeResult?.path ?? absolutePath),\n };\n\n await buildDictionary([dictionaryToBuild], configuration);\n\n return absolutePath;\n};\n"],"mappings":"mWAgBA,MAAM,EAAoB,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B,OAAQ,EAAmB,EAAS,CACrC,GAKP,OAAO,GAMI,EAAqB,MAChC,EACA,EACA,EACA,IACoB,CACpB,GAAM,CAAE,eAAc,eAAgB,MAAMC,EAAAA,wBAC1C,EACA,EACA,EACD,CAEK,CAAE,iBAAkB,EAAc,qBAClC,CAAE,WAAY,EAAc,OAElC,AACE,IAAuB,MAAA,EAAA,EAAA,sBAA2B,EAAc,CAGlE,IAAM,GAAA,EAAA,EAAA,SAAoB,EAAa,CAGvC,MAAA,EAAA,EAAA,OAAY,EAAW,CAAE,UAAW,GAAM,CAAC,CAG3C,IAAI,EAAwC,KAE5C,IAAA,EAAA,EAAA,YAAe,EAAa,CAC1B,GAAI,CAOF,EANmB,MAAA,EAAA,EAAA,wBACjB,EACA,EACA,EACD,EAEkC,WAC5B,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,IAAM,GAAA,EAAA,EAAA,UAAmC,EAAS,EAAa,CAE3D,EAEJ,GAAI,EAAa,CAEf,IAAM,EAAgB,EACpB,EACA,EACD,CAED,EAAmB,CAEjB,GAAG,EACH,IAAK,EACL,QAAS,EACT,OAAQ,EACR,SAAU,EACX,KACI,CAEL,IAAM,EAAgB,EACpB,EACA,EACA,EACD,CAED,EAAmB,CAEjB,GAAG,EACH,IAAK,EACL,QAAS,EACT,SAAU,EACX,CAGH,IAAM,GAAA,EAAA,EAAA,UAAuB,EAAS,EAAU,CAE1C,EAAc,MAAA,EAAA,EAAA,yBAClB,EACA,EACA,CACE,oBAAqB,EACrB,WAAY,CAAC,EAAc,CAC5B,CACF,CAUD,OAFA,MAAA,EAAA,EAAA,iBAAsB,CALgB,CACpC,GAAG,EACH,UAAA,EAAA,EAAA,UAAmB,EAAS,GAAa,MAAQ,EAAa,CAC/D,CAEwC,CAAE,EAAc,CAElD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/extractDictionaryKey.cjs`),t=require(`./contentWriter.cjs`),n=require(`./utils/constants.cjs`),r=require(`./utils/generateKey.cjs`),i=require(`./utils/shouldExtract.cjs`),a=require(`./babelProcessor.cjs`),o=require(`./processTsxFile.cjs`);let s=require(`@intlayer/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/extractDictionaryKey.cjs`),t=require(`./contentWriter.cjs`),n=require(`./utils/constants.cjs`),r=require(`./utils/generateKey.cjs`),i=require(`./utils/shouldExtract.cjs`),a=require(`./babelProcessor.cjs`),o=require(`./processTsxFile.cjs`);let s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`node:fs`),u=require(`node:path`),d=require(`@intlayer/config/utils`),f=require(`@intlayer/unmerged-dictionaries-entry`),p=require(`@intlayer/chokidar/cli`),m=require(`node:child_process`),h=null,g=null;const _=(e,t)=>{if(t)return{extractedContentMap:{[e]:t.extractedContent},transformedCode:t.code}},v=(t,c,d,f,p,m)=>{let h=d?.code??(0,l.readFileSync)(t,`utf-8`),g=m??e.extractDictionaryKey(t,h,f.configuration.compiler.dictionaryKeyPrefix),v=(0,u.extname)(t),{vueCompiler:y,svelteCompiler:b,unmergedDictionaries:x,configuration:S}=f,C={generateKey:r.generateKey,shouldExtract:i.shouldExtract,attributesToExtract:n.ATTRIBUTES_TO_EXTRACT,extractDictionaryKeyFromPath:e.extractDictionaryKeyFromPath,extractTsContent:(e,t,n,r,i)=>a.extractTsContent(e,t,n,r,i,x)};if(v===`.vue`){if(!y)throw Error(`Please install ${(0,s.colorizePath)(`@intlayer/vue-compiler`,s.ANSIColors.YELLOW)} to process Vue files.`);let e=y.processVueFile(t,g,c,C,p);if(e)return _(g,e)}if(v===`.svelte`){if(!b)throw Error(`Please install ${(0,s.colorizePath)(`@intlayer/svelte-compiler`,s.ANSIColors.YELLOW)} to process Svelte files.`);let e=b.processSvelteFile(t,g,c,C,p);if(e)return _(g,e)}if([`.tsx`,`.jsx`,`.ts`,`.js`,`.cjs`,`.mjs`].includes(v)){let e=o.processTsxFile(t,g,c,S,p,x,h);if(e)return{extractedContentMap:e.extractedContent,transformedCode:e.modifiedCode}}},y=async(e,n,r,{configuration:i,baseDir:a,appLogger:o},c)=>{if(r?.onExtract)for(let[t,i]of Object.entries(e))await r.onExtract({key:t,content:i,filePath:n});if(!r?.codeOnly&&!r?.onExtract)for(let[r,c]of Object.entries(e)){let e=(0,u.relative)(a,await t.writeContentHelper(c,r,n,i));o(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Created content file: ${(0,s.colorizePath)(e)}`)}if(c){let e=(0,p.detectFormatCommand)(i);if(e)try{(0,m.execSync)(e.replace(`{{file}}`,n),{stdio:`inherit`,cwd:a})}catch(e){console.error(e)}o(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Updated component: ${(0,s.colorizePath)((0,u.relative)(a,n))}`)}},b=(e,t)=>{let n=t?.configuration??(0,c.getConfiguration)(t?.configOptions),r=(0,s.getAppLogger)(n),{baseDir:i}=n.system;return{configuration:n,appLogger:r,baseDir:i,unmergedDictionaries:t?.unmergedDictionaries??(0,f.getUnmergedDictionaries)(n),saveComponent:!t?.declarationOnly,componentExtension:(0,u.extname)(e)}},x=async(t,n,r)=>{let{configuration:i,appLogger:a,baseDir:o,unmergedDictionaries:c,saveComponent:d,componentExtension:f}=b(t,r);if(f===`.vue`&&!h)try{h=await import(`@intlayer/vue-compiler`)}catch{a(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Install ${(0,s.colorizePath)(`@intlayer/vue-compiler`,s.ANSIColors.YELLOW)} to process Vue files.`)}if(f===`.svelte`&&!g)try{g=await import(`@intlayer/svelte-compiler`)}catch{a(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Install ${(0,s.colorizePath)(`@intlayer/svelte-compiler`,s.ANSIColors.YELLOW)} to process Svelte files.`)}let p=e.extractDictionaryKey(t,r?.code??(0,l.readFileSync)(t,`utf-8`),i.compiler.dictionaryKeyPrefix),m=v(t,n,r,{vueCompiler:h,svelteCompiler:g,unmergedDictionaries:c,configuration:i},d,p);if(!m||!m.extractedContentMap){a(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} No extractable text found in ${(0,s.colorizePath)((0,u.relative)(o,t))}`,{isVerbose:!0});return}return await y(m.extractedContentMap,t,r,{configuration:i,baseDir:o,appLogger:a},d),{transformedCode:m.transformedCode,extractedContentMap:m.extractedContentMap}},S=(e,t,n)=>{let{configuration:r,appLogger:i,baseDir:a,unmergedDictionaries:o,saveComponent:c,componentExtension:l}=b(e,n),f=(0,d.getProjectRequire)();if(l===`.vue`&&!h)try{h=f(`@intlayer/vue-compiler`)}catch{i(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Install ${(0,s.colorizePath)(`@intlayer/vue-compiler`,s.ANSIColors.YELLOW)} to process Vue files.`)}if(l===`.svelte`&&!g)try{g=f(`@intlayer/svelte-compiler`)}catch{i(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} Install ${(0,s.colorizePath)(`@intlayer/svelte-compiler`,s.ANSIColors.YELLOW)} to process Svelte files.`)}let p=v(e,t,n,{vueCompiler:h,svelteCompiler:g,unmergedDictionaries:o,configuration:r},c);if(!p?.extractedContentMap){i(`${(0,s.colorize)(`Compiler:`,s.ANSIColors.GREY_DARK)} No extractable text found in ${(0,s.colorizePath)((0,u.relative)(a,e))}`,{isVerbose:!0});return}let{extractedContentMap:m,transformedCode:_}=p;if(n?.onExtract)for(let[t,r]of Object.entries(m))n.onExtract({key:t,content:r,filePath:e});return{transformedCode:_,extractedContentMap:m}};exports.extractContent=x,exports.extractContentSync=S;
|
|
2
2
|
//# sourceMappingURL=extractContent.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractContent.cjs","names":["extractDictionaryKey","ATTRIBUTES_TO_EXTRACT","extractTsContent","ANSIColors","processTsxFile","writeContentHelper"],"sources":["../../../src/extractContent/extractContent.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { extname, relative } from 'node:path';\nimport type * as t from '@babel/types';\nimport { detectFormatCommand } from '@intlayer/chokidar/cli';\nimport { formatPath } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { extractTsContent } from './babelProcessor';\nimport { writeContentHelper } from './contentWriter';\nimport { processTsxFile } from './processTsxFile';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n extractDictionaryKeyFromPath,\n type PackageName,\n shouldExtract,\n} from './utils';\nimport { resolveContentFilePaths } from './utils/extractDictionaryInfo';\nimport { extractDictionaryKey } from './utils/extractDictionaryKey';\nimport { generateKey } from './utils/generateKey';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n unmergedDictionaries?: Record<string, unknown>;\n configuration?: IntlayerConfig;\n code?: string;\n onExtract?: (result: {\n key: string;\n content: Record<string, string>;\n filePath: string;\n }) => void | Promise<void>;\n};\n\ntype ExternalCompilerResult = {\n extractedContent: Record<string, string>;\n code: string;\n};\n\ntype ExternalCompilerOptions = {\n generateKey: typeof generateKey;\n shouldExtract: typeof shouldExtract;\n attributesToExtract: typeof ATTRIBUTES_TO_EXTRACT;\n extractDictionaryKeyFromPath: typeof extractDictionaryKeyFromPath;\n extractTsContent: (\n ast: unknown,\n code: string,\n keys: Set<string>,\n config: IntlayerConfig,\n path: string\n ) => ReturnType<typeof extractTsContent>;\n};\n\ntype VueCompiler = typeof import('@intlayer/vue-compiler');\ntype SvelteCompiler = typeof import('@intlayer/svelte-compiler');\n\n// Module caches\nlet vueCompiler: VueCompiler | null = null;\nlet svelteCompiler: SvelteCompiler | null = null;\n\ntype InternalExtractResult = {\n extractedContentMap: Record<string, Record<string, string>> | null;\n transformedCode: string | null;\n};\n\nconst formatCompilerResult = (\n componentKey: string,\n res?: ExternalCompilerResult\n): InternalExtractResult | undefined => {\n if (!res) return undefined;\n\n return {\n extractedContentMap: { [componentKey]: res.extractedContent },\n transformedCode: res.code,\n };\n};\n\ntype Dependencies = {\n vueCompiler: VueCompiler | null;\n svelteCompiler: SvelteCompiler | null;\n unmergedDictionaries: Record<string, unknown>;\n configuration: IntlayerConfig;\n};\n\nconst processFileInternal = (\n filePath: string,\n packageName: PackageName,\n options: ExtractIntlayerOptions | undefined,\n dependencies: Dependencies,\n saveComponent: boolean,\n providedComponentKey?: string\n):\n | InternalExtractResult\n | Promise<InternalExtractResult | undefined>\n | undefined => {\n const fileText = options?.code ?? readFileSync(filePath, 'utf-8');\n const componentKey =\n providedComponentKey ??\n extractDictionaryKey(\n filePath,\n fileText,\n dependencies.configuration.compiler.dictionaryKeyPrefix\n );\n const ext = extname(filePath);\n\n const { vueCompiler, svelteCompiler, unmergedDictionaries, configuration } =\n dependencies;\n\n const compilerCommonOptions: ExternalCompilerOptions = {\n generateKey,\n shouldExtract,\n attributesToExtract: ATTRIBUTES_TO_EXTRACT,\n extractDictionaryKeyFromPath,\n extractTsContent: (ast, code, keys, config, path) =>\n extractTsContent(\n ast as t.File,\n code,\n keys,\n config,\n path,\n unmergedDictionaries\n ),\n };\n\n if (ext === '.vue') {\n if (!vueCompiler) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-compiler', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n\n const res = vueCompiler.processVueFile(\n filePath,\n componentKey,\n packageName,\n compilerCommonOptions,\n saveComponent\n );\n\n if (res) {\n return formatCompilerResult(componentKey, res);\n }\n }\n\n if (ext === '.svelte') {\n if (!svelteCompiler) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-compiler', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n\n const res = svelteCompiler.processSvelteFile(\n filePath,\n componentKey,\n packageName,\n compilerCommonOptions,\n saveComponent\n );\n\n if (res) {\n return formatCompilerResult(componentKey, res);\n }\n }\n\n if (['.tsx', '.jsx', '.ts', '.js', '.cjs', '.mjs'].includes(ext)) {\n const result = processTsxFile(\n filePath,\n componentKey,\n packageName,\n configuration,\n saveComponent,\n unmergedDictionaries,\n fileText\n );\n\n if (result) {\n return {\n extractedContentMap: result.extractedContent,\n transformedCode: result.modifiedCode,\n };\n }\n }\n\n return undefined;\n};\n\nconst handleExtractionSideEffects = async (\n extractedContentMap: Record<string, Record<string, string>>,\n filePath: string,\n options: ExtractIntlayerOptions | undefined,\n {\n configuration,\n baseDir,\n appLogger,\n }: {\n configuration: IntlayerConfig;\n baseDir: string;\n appLogger: ReturnType<typeof getAppLogger>;\n },\n saveComponent: boolean\n) => {\n if (options?.onExtract) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n await options.onExtract({ key, content, filePath });\n }\n }\n\n const writeContent = !options?.codeOnly && !options?.onExtract;\n\n if (writeContent) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n const contentFilePath = await writeContentHelper(\n content,\n key,\n filePath,\n configuration\n );\n\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Created content file: ${colorizePath(relativeContentFilePath)}`\n );\n }\n }\n\n if (saveComponent) {\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const extractContent = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n): Promise<{ transformedCode: string | null } | undefined> => {\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { baseDir } = configuration.system;\n const unmergedDictionaries =\n options?.unmergedDictionaries ?? getUnmergedDictionaries(configuration);\n const saveComponent = !options?.declarationOnly;\n const componentExtension = extname(filePath);\n\n if (componentExtension === '.vue' && !vueCompiler) {\n vueCompiler = (await import(\n '@intlayer/vue-compiler'\n )) as unknown as VueCompiler;\n }\n\n if (componentExtension === '.svelte' && !svelteCompiler) {\n svelteCompiler = (await import(\n '@intlayer/svelte-compiler'\n )) as unknown as SvelteCompiler;\n }\n\n const fileText = options?.code ?? readFileSync(filePath, 'utf-8');\n const dictionaryKey = extractDictionaryKey(\n filePath,\n fileText,\n configuration.compiler.dictionaryKeyPrefix\n );\n\n const result = await processFileInternal(\n filePath,\n packageName,\n options,\n { vueCompiler, svelteCompiler, unmergedDictionaries, configuration },\n saveComponent,\n dictionaryKey\n );\n\n if (!result || !result.extractedContentMap) {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} No extractable text found in ${colorizePath(relative(baseDir, filePath))}`,\n { isVerbose: true }\n );\n return undefined;\n }\n\n await handleExtractionSideEffects(\n result.extractedContentMap,\n filePath,\n options,\n { configuration, baseDir, appLogger },\n saveComponent\n );\n\n return { transformedCode: result.transformedCode };\n};\n\nexport const extractContentSync = (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n):\n | {\n transformedCode: string | null;\n extractedContent: Record<string, Record<string, string>>;\n }\n | undefined => {\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.system;\n const unmergedDictionaries =\n options?.unmergedDictionaries ?? getUnmergedDictionaries(configuration);\n const saveComponent = !options?.declarationOnly;\n const componentExtension = extname(filePath);\n\n const requireFn = getProjectRequire();\n\n if (componentExtension === '.vue' && !vueCompiler) {\n try {\n vueCompiler = requireFn('@intlayer/vue-compiler') as VueCompiler;\n } catch {\n // Ignored\n }\n }\n if (componentExtension === '.svelte' && !svelteCompiler) {\n try {\n svelteCompiler = requireFn('@intlayer/svelte-compiler') as SvelteCompiler;\n } catch {\n // Ignored\n }\n }\n\n const result = processFileInternal(\n filePath,\n packageName,\n options,\n { vueCompiler, svelteCompiler, unmergedDictionaries, configuration },\n saveComponent\n );\n\n if (result instanceof Promise) {\n throw new Error(\n `Synchronous extraction failed: External compiler returned a Promise for ${formatPath(relative(baseDir, filePath))}`\n );\n }\n\n if (result?.extractedContentMap) {\n const { extractedContentMap, transformedCode } = result;\n\n if (options?.onExtract) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n void options.onExtract({ key, content, filePath });\n }\n }\n\n return { transformedCode, extractedContent: extractedContentMap };\n }\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} No extractable text found in ${colorizePath(relative(baseDir, filePath))}`,\n { isVerbose: true }\n );\n\n return undefined;\n};\n"],"mappings":"irBAqEI,EAAkC,KAClC,EAAwC,KAO5C,MAAM,GACJ,EACA,IACsC,CACjC,KAEL,MAAO,CACL,oBAAqB,EAAG,GAAe,EAAI,iBAAkB,CAC7D,gBAAiB,EAAI,KACtB,EAUG,GACJ,EACA,EACA,EACA,EACA,EACA,IAIe,CACf,IAAM,EAAW,GAAS,OAAA,EAAA,EAAA,cAAqB,EAAU,QAAQ,CAC3D,EACJ,GACAA,EAAAA,qBACE,EACA,EACA,EAAa,cAAc,SAAS,oBACrC,CACG,GAAA,EAAA,EAAA,SAAc,EAAS,CAEvB,CAAE,cAAa,iBAAgB,uBAAsB,iBACzD,EAEI,EAAiD,CACrD,YAAA,EAAA,YACA,cAAA,EAAA,cACA,oBAAqBC,EAAAA,sBACrB,6BAAA,EAAA,6BACA,kBAAmB,EAAK,EAAM,EAAM,EAAQ,IAC1CC,EAAAA,iBACE,EACA,EACA,EACA,EAC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ACA,IAMe,CACf,IAAM,EACJ,GAAS,gBAAA,EAAA,EAAA,kBAAkC,GAAS,cAAc,CAC9D,GAAA,EAAA,EAAA,cAAyB,EAAc,CACvC,CAAE,WAAY,EAAc,OAC5B,EACJ,GAAS,uBAAA,EAAA,EAAA,yBAAgD,EAAc,CACnE,EAAgB,CAAC,GAAS,gBAC1B,GAAA,EAAA,EAAA,SAA6B,EAAS,CAEtC,GAAA,EAAA,EAAA,oBAA+B,CAErC,GAAI,IAAuB,QAAU,CAAC,EACpC,GAAI,CACF,EAAc,EAAU,yBAAyB,MAC3C,EAIV,GAAI,IAAuB,WAAa,CAAC,EACvC,GAAI,CACF,EAAiB,EAAU,4BAA4B,MACjD,EAKV,IAAM,EAAS,EACb,EACA,EACA,EACA,CAAE,cAAa,iBAAgB,uBAAsB,gBAAe,CACpE,EACD,CAED,GAAI,aAAkB,QACpB,MAAU,MACR,4EAAA,EAAA,EAAA,aAAA,EAAA,EAAA,UAA+F,EAAS,EAAS,CAAC,GACnH,CAGH,GAAI,GAAQ,oBAAqB,CAC/B,GAAM,CAAE,sBAAqB,mBAAoB,EAEjD,GAAI,GAAS,UACX,IAAK,GAAM,CAAC,EAAK,KAAY,OAAO,QAAQ,EAAoB,CACzD,EAAQ,UAAU,CAAE,MAAK,UAAS,WAAU,CAAC,CAItD,MAAO,CAAE,kBAAiB,iBAAkB,EAAqB,CAGnE,EACE,IAAA,EAAA,EAAA,UAAY,YAAaA,EAAAA,WAAW,UAAU,CAAC,iCAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAAsD,EAAS,EAAS,CAAC,GACxH,CAAE,UAAW,GAAM,CACpB"}
|
|
1
|
+
{"version":3,"file":"extractContent.cjs","names":["extractDictionaryKey","ATTRIBUTES_TO_EXTRACT","extractTsContent","ANSIColors","processTsxFile","writeContentHelper"],"sources":["../../../src/extractContent/extractContent.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { extname, relative } from 'node:path';\nimport type * as t from '@babel/types';\nimport { detectFormatCommand } from '@intlayer/chokidar/cli';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { extractTsContent } from './babelProcessor';\nimport { writeContentHelper } from './contentWriter';\nimport { processTsxFile } from './processTsxFile';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n extractDictionaryKeyFromPath,\n type PackageName,\n shouldExtract,\n} from './utils';\nimport { extractDictionaryKey } from './utils/extractDictionaryKey';\nimport { generateKey } from './utils/generateKey';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n unmergedDictionaries?: Record<string, unknown>;\n configuration?: IntlayerConfig;\n code?: string;\n onExtract?: (result: {\n key: string;\n content: Record<string, string>;\n filePath: string;\n }) => void | Promise<void>;\n};\n\ntype ExternalCompilerResult = {\n extractedContent: Record<string, string>;\n code: string;\n};\n\ntype ExternalCompilerOptions = {\n generateKey: typeof generateKey;\n shouldExtract: typeof shouldExtract;\n attributesToExtract: typeof ATTRIBUTES_TO_EXTRACT;\n extractDictionaryKeyFromPath: typeof extractDictionaryKeyFromPath;\n extractTsContent: (\n ast: unknown,\n code: string,\n keys: Set<string>,\n config: IntlayerConfig,\n path: string\n ) => ReturnType<typeof extractTsContent>;\n};\n\ntype VueCompiler = typeof import('@intlayer/vue-compiler');\ntype SvelteCompiler = typeof import('@intlayer/svelte-compiler');\n\n// Module caches\nlet vueCompiler: VueCompiler | null = null;\nlet svelteCompiler: SvelteCompiler | null = null;\n\ntype InternalExtractResult = {\n extractedContentMap: Record<string, Record<string, string>> | null;\n transformedCode: string | null;\n};\n\nconst formatCompilerResult = (\n componentKey: string,\n res?: ExternalCompilerResult\n): InternalExtractResult | undefined => {\n if (!res) return undefined;\n\n return {\n extractedContentMap: { [componentKey]: res.extractedContent },\n transformedCode: res.code,\n };\n};\n\ntype Dependencies = {\n vueCompiler: VueCompiler | null;\n svelteCompiler: SvelteCompiler | null;\n unmergedDictionaries: Record<string, unknown>;\n configuration: IntlayerConfig;\n};\n\nconst processFileInternal = (\n filePath: string,\n packageName: PackageName,\n options: ExtractIntlayerOptions | undefined,\n dependencies: Dependencies,\n saveComponent: boolean,\n providedComponentKey?: string\n): InternalExtractResult | undefined => {\n const fileText = options?.code ?? readFileSync(filePath, 'utf-8');\n const componentKey =\n providedComponentKey ??\n extractDictionaryKey(\n filePath,\n fileText,\n dependencies.configuration.compiler.dictionaryKeyPrefix\n );\n const ext = extname(filePath);\n\n const { vueCompiler, svelteCompiler, unmergedDictionaries, configuration } =\n dependencies;\n\n const compilerCommonOptions: ExternalCompilerOptions = {\n generateKey,\n shouldExtract,\n attributesToExtract: ATTRIBUTES_TO_EXTRACT,\n extractDictionaryKeyFromPath,\n extractTsContent: (ast, code, keys, config, path) =>\n extractTsContent(\n ast as t.File,\n code,\n keys,\n config,\n path,\n unmergedDictionaries\n ),\n };\n\n if (ext === '.vue') {\n if (!vueCompiler) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-compiler', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n\n const res = vueCompiler.processVueFile(\n filePath,\n componentKey,\n packageName,\n compilerCommonOptions,\n saveComponent\n );\n\n if (res) {\n return formatCompilerResult(componentKey, res);\n }\n }\n\n if (ext === '.svelte') {\n if (!svelteCompiler) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-compiler', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n\n const res = svelteCompiler.processSvelteFile(\n filePath,\n componentKey,\n packageName,\n compilerCommonOptions,\n saveComponent\n );\n\n if (res) {\n return formatCompilerResult(componentKey, res);\n }\n }\n\n if (['.tsx', '.jsx', '.ts', '.js', '.cjs', '.mjs'].includes(ext)) {\n const result = processTsxFile(\n filePath,\n componentKey,\n packageName,\n configuration,\n saveComponent,\n unmergedDictionaries,\n fileText\n );\n\n if (result) {\n return {\n extractedContentMap: result.extractedContent,\n transformedCode: result.modifiedCode,\n };\n }\n }\n\n return undefined;\n};\n\nconst handleExtractionSideEffects = async (\n extractedContentMap: Record<string, Record<string, string>>,\n filePath: string,\n options: ExtractIntlayerOptions | undefined,\n {\n configuration,\n baseDir,\n appLogger,\n }: {\n configuration: IntlayerConfig;\n baseDir: string;\n appLogger: ReturnType<typeof getAppLogger>;\n },\n saveComponent: boolean\n) => {\n if (options?.onExtract) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n await options.onExtract({ key, content, filePath });\n }\n }\n\n const writeContent = !options?.codeOnly && !options?.onExtract;\n\n if (writeContent) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n const contentFilePath = await writeContentHelper(\n content,\n key,\n filePath,\n configuration\n );\n\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Created content file: ${colorizePath(relativeContentFilePath)}`\n );\n }\n }\n\n if (saveComponent) {\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\ntype ExtractResult = {\n transformedCode: string | null;\n extractedContentMap: Record<string, Record<string, string>>;\n};\n\ntype ExtractContext = {\n configuration: IntlayerConfig;\n appLogger: ReturnType<typeof getAppLogger>;\n baseDir: string;\n unmergedDictionaries: Record<string, unknown>;\n saveComponent: boolean;\n componentExtension: string;\n};\n\nconst buildContext = (\n filePath: string,\n options: ExtractIntlayerOptions | undefined\n): ExtractContext => {\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.system;\n const unmergedDictionaries =\n options?.unmergedDictionaries ?? getUnmergedDictionaries(configuration);\n const saveComponent = !options?.declarationOnly;\n const componentExtension = extname(filePath);\n\n return {\n configuration,\n appLogger,\n baseDir,\n unmergedDictionaries,\n saveComponent,\n componentExtension,\n };\n};\n\nexport const extractContent = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n): Promise<ExtractResult | undefined> => {\n const {\n configuration,\n appLogger,\n baseDir,\n unmergedDictionaries,\n saveComponent,\n componentExtension,\n } = buildContext(filePath, options);\n\n if (componentExtension === '.vue' && !vueCompiler) {\n try {\n vueCompiler = await import('@intlayer/vue-compiler');\n } catch {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Install ${colorizePath('@intlayer/vue-compiler', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n }\n\n if (componentExtension === '.svelte' && !svelteCompiler) {\n try {\n svelteCompiler = await import('@intlayer/svelte-compiler');\n } catch {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Install ${colorizePath('@intlayer/svelte-compiler', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n }\n\n const fileText = options?.code ?? readFileSync(filePath, 'utf-8');\n const dictionaryKey = extractDictionaryKey(\n filePath,\n fileText,\n configuration.compiler.dictionaryKeyPrefix\n );\n\n const result = processFileInternal(\n filePath,\n packageName,\n options,\n { vueCompiler, svelteCompiler, unmergedDictionaries, configuration },\n saveComponent,\n dictionaryKey\n );\n\n if (!result || !result.extractedContentMap) {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} No extractable text found in ${colorizePath(relative(baseDir, filePath))}`,\n { isVerbose: true }\n );\n return undefined;\n }\n\n await handleExtractionSideEffects(\n result.extractedContentMap,\n filePath,\n options,\n { configuration, baseDir, appLogger },\n saveComponent\n );\n\n return {\n transformedCode: result.transformedCode,\n extractedContentMap: result.extractedContentMap,\n };\n};\n\n/**\n * Synchronous variant of `extractContent` — used by the Babel plugin which\n * runs in a sync transform context (e.g. Next.js / Webpack).\n *\n * Differences from `extractContent`:\n * - Loads external compilers (Vue, Svelte) via `require()` instead of `import()`\n * - Fires `onExtract` callbacks as fire-and-forget (cannot await in sync context)\n * - Does NOT write dictionary files or run the code formatter; callers that\n * need persistence should supply an `onExtract` callback\n */\nexport const extractContentSync = (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n): ExtractResult | undefined => {\n const {\n configuration,\n appLogger,\n baseDir,\n unmergedDictionaries,\n saveComponent,\n componentExtension,\n } = buildContext(filePath, options);\n\n const requireFn = getProjectRequire();\n\n if (componentExtension === '.vue' && !vueCompiler) {\n try {\n vueCompiler = requireFn('@intlayer/vue-compiler') as VueCompiler;\n } catch {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Install ${colorizePath('@intlayer/vue-compiler', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n }\n\n if (componentExtension === '.svelte' && !svelteCompiler) {\n try {\n svelteCompiler = requireFn('@intlayer/svelte-compiler') as SvelteCompiler;\n } catch {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Install ${colorizePath('@intlayer/svelte-compiler', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n }\n\n const result = processFileInternal(\n filePath,\n packageName,\n options,\n { vueCompiler, svelteCompiler, unmergedDictionaries, configuration },\n saveComponent\n );\n\n if (!result?.extractedContentMap) {\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} No extractable text found in ${colorizePath(relative(baseDir, filePath))}`,\n { isVerbose: true }\n );\n return undefined;\n }\n\n const { extractedContentMap, transformedCode } = result;\n\n if (options?.onExtract) {\n for (const [key, content] of Object.entries(extractedContentMap)) {\n void options.onExtract({ key, content, filePath });\n }\n }\n\n return { transformedCode, extractedContentMap };\n};\n"],"mappings":"2oBAmEI,EAA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EAAAA,WAAW,UAAU,CAAC,YAAA,EAAA,EAAA,cAAwB,yBAA0BA,EAAAA,WAAW,OAAO,CAAC,wBACrH,CAIL,GAAI,IAAuB,WAAa,CAAC,EACvC,GAAI,CACF,EAAiB,EAAU,4BAA4B,MACjD,CACN,EACE,IAAA,EAAA,EAAA,UAAY,YAAaA,EAAAA,WAAW,UAAU,CAAC,YAAA,EAAA,EAAA,cAAwB,4BAA6BA,EAAAA,WAAW,OAAO,CAAC,2BACxH,CAIL,IAAM,EAAS,EACb,EACA,EACA,EACA,CAAE,cAAa,iBAAgB,uBAAsB,gBAAe,CACpE,EACD,CAED,GAAI,CAAC,GAAQ,oBAAqB,CAChC,EACE,IAAA,EAAA,EAAA,UAAY,YAAaA,EAAAA,WAAW,UAAU,CAAC,iCAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAAsD,EAAS,EAAS,CAAC,GACxH,CAAE,UAAW,GAAM,CACpB,CACD,OAGF,GAAM,CAAE,sBAAqB,mBAAoB,EAEjD,GAAI,GAAS,UACX,IAAK,GAAM,CAAC,EAAK,KAAY,OAAO,QAAQ,EAAoB,CACzD,EAAQ,UAAU,CAAE,MAAK,UAAS,WAAU,CAAC,CAItD,MAAO,CAAE,kBAAiB,sBAAqB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./utils/constants.cjs`),n=require(`./utils/getExistingIntlayerInfo.cjs`),r=require(`./babelProcessor.cjs`);let i=require(`node:fs`),a=require(`@intlayer/chokidar/cli`),o=require(`@babel/parser`),s=require(`node:child_process`),c=require(`@babel/traverse`);c=e.__toESM(c);let l=require(`@babel/types`);l=e.__toESM(l);const u=typeof c.default==`function`?c.default:c.default.default,d=(e,c,d,f,p=!0,m={},h)=>{let g=h??(0,i.readFileSync)(e,`utf-8`),_=(0,o.parse)(g,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),v=_.program.directives.some(e=>e.value.value===`use client`),y=t.SERVER_CAPABLE_PACKAGES.has(d)&&!v?`${d}/server`:d,b=d===`solid-intlayer`,{extractedContent:x,replacements:S,componentsNeedingHooks:C,componentKeyMap:w,componentPaths:T,hookMap:E}=r.extractBabelContentForComponents(_,g,new Set,c,f,e,m);if(Object.keys(x).length===0)return null;let D=[],O=e=>{let t=e;for(;t;){
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./utils/constants.cjs`),n=require(`./utils/getExistingIntlayerInfo.cjs`),r=require(`./babelProcessor.cjs`);let i=require(`node:fs`),a=require(`@intlayer/chokidar/cli`),o=require(`@babel/parser`),s=require(`node:child_process`),c=require(`@babel/traverse`);c=e.__toESM(c);let l=require(`@babel/types`);l=e.__toESM(l);const u=typeof c.default==`function`?c.default:c.default.default,d=(e,c,d,f,p=!0,m={},h)=>{let g=h??(0,i.readFileSync)(e,`utf-8`),_=(0,o.parse)(g,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),v=_.program.directives.some(e=>e.value.value===`use client`),y=t.SERVER_CAPABLE_PACKAGES.has(d)&&!v?`${d}/server`:d,b=d===`solid-intlayer`,{extractedContent:x,replacements:S,componentsNeedingHooks:C,componentKeyMap:w,componentPaths:T,hookMap:E}=r.extractBabelContentForComponents(_,g,new Set,c,f,e,m);if(Object.keys(x).length===0)return null;let D=[],O=new Map;for(let e of T)O.set(e.node,e);let k=new Map;for(let e of T)k.set(e.node,n.getExistingIntlayerInfo(e));let A=e=>{let t=e;for(;t;){if(O.has(t.node))return k.get(t.node);t=t.parentPath}},j=e=>{let t=e;for(;t;){let e=O.get(t.node);if(e){let t=k.get(e.node);if(t)return t.hook;if(C.has(e))return E.get(e.node)||`useIntlayer`}t=t.parentPath}return`useIntlayer`};for(let{path:e,key:t,type:n,variables:r,childrenToReplace:i}of S){let a=A(e),o=a?.variableName??`content`,s=a?.isDestructured?t:b?`${o}().${t}`:`${o}.${t}`,c=j(e)===`getIntlayer`?``:`.value`;if(n===`jsx-text`&&e.isJSXText())D.push({start:e.node.start,end:e.node.end,replacement:`{${s}}`});else if(n===`jsx-attribute`&&e.isJSXAttribute()){let t=e.node.value;t&&D.push({start:t.start,end:t.end,replacement:`{${s}${c}}`})}else if(n===`string-literal`&&e.isStringLiteral())D.push({start:e.node.start,end:e.node.end,replacement:`${s}${c}`});else if(n===`jsx-text-combined`&&i&&i.length>0){let e=`{${s}}`,t=i[0].start,n=i[i.length-1].end;D.push({start:t,end:n,replacement:e})}else if(n===`jsx-insertion`&&r&&i&&i.length>0){let e=`{${s}({ ${r.map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return`${t}: ${n}`}).join(`, `)} })}`,t=i[0].start,n=i[i.length-1].end;D.push({start:t,end:n,replacement:e})}}let M=!1,N=!1;for(let e of C){let t=w.get(e.node),n=k.get(e.node);if(n){if(n.hook===`useIntlayer`&&(M=!0),n.hook===`getIntlayer`&&(N=!0),n.isDestructured&&n.objectPatternNode){let t=new Set;for(let{path:n,key:r}of S){let i=n;for(;i;){if(i.node===e.node){t.add(r);break}i=i.parentPath}}let r=[...t].filter(e=>!n.existingDestructuredKeys.includes(e));if(r.length>0){let{objectPatternNode:e}=n,t=e.properties[e.properties.length-1];D.push({start:t.end,end:t.end,replacement:`, ${r.join(`, `)}`})}}}else{let n=E.get(e.node)||`useIntlayer`;n===`useIntlayer`&&(M=!0),n===`getIntlayer`&&(N=!0);let r=e.get(`body`),i=`\n const content = ${n}('${t}');\n`;if(r.isBlockStatement())D.push({start:r.node.start+1,end:r.node.start+1,replacement:i});else if(r.isExpression()){let e=r.node.start,i=r.node.end,a=-1,o=-1;for(let t=e-1;t>=0;t--){let e=g[t];if(e===`(`){a=t;break}if(e!==` `&&e!==`
|
|
2
2
|
`&&e!==`\r`&&e!==` `)break}if(a!==-1)for(let e=i;e<g.length;e++){let t=g[e];if(t===`)`){o=e;break}if(t!==` `&&t!==`
|
|
3
3
|
`&&t!==`\r`&&t!==` `)break}a!==-1&&o!==-1?(D.push({start:o,end:o+1,replacement:`)
|
|
4
4
|
}`}),D.push({start:a,end:a+1,replacement:`{\n const content = ${n}('${t}');\n return (`})):(D.push({start:i,end:i,replacement:`
|
|
5
|
-
}`}),D.push({start:e,end:e,replacement:`{\n const content = ${n}('${t}');\n return `}))}}}let
|
|
5
|
+
}`}),D.push({start:e,end:e,replacement:`{\n const content = ${n}('${t}');\n return `}))}}}let P=(e,t)=>{let n;if(u(_,{ImportDeclaration(e){e.node.source.value===t&&(n=e,e.stop())}}),!n){let n=`import { ${e} } from '${t}';\n`,r=0;if(_.program.body.length>0)r=_.program.body[0].start;else if(_.program.directives&&_.program.directives.length>0){r=_.program.directives[_.program.directives.length-1].end,g[r]===`;`&&r++,D.push({start:r,end:r,replacement:`\n${n}`});return}(r===0||_.program.body.length>0&&r===_.program.body[0].start)&&D.push({start:r,end:r,replacement:n})}else if(!n.node.specifiers.some(t=>l.isImportSpecifier(t)&&l.isIdentifier(t.imported)&&t.imported.name===e)){let t=g.slice(n.node.start,n.node.end),r=t.lastIndexOf(`}`);if(r!==-1){let i=!t.slice(0,r).trim().endsWith(`,`),a=n.node.start+r,o=i?`, `:` `;D.push({start:a,end:a,replacement:`${o}${e} `})}}};M&&P(`useIntlayer`,y),N&&P(`getIntlayer`,`intlayer`),D.sort((e,t)=>t.start===e.start?t.end-e.end:t.start-e.start);let F=g;for(let e of D)F=F.slice(0,e.start)+e.replacement+F.slice(e.end);if(p){(0,i.writeFileSync)(e,F);let t=(0,a.detectFormatCommand)(f);if(t)try{(0,s.execSync)(t.replace(`{{file}}`,e),{stdio:`inherit`,cwd:f.system.baseDir})}catch(e){console.error(e)}}return{extractedContent:x,modifiedCode:F}};exports.processTsxFile=d;
|
|
6
6
|
//# sourceMappingURL=processTsxFile.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processTsxFile.cjs","names":["_traverse","SERVER_CAPABLE_PACKAGES","extractBabelContentForComponents","getExistingIntlayerInfo","t"],"sources":["../../../src/extractContent/processTsxFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { parse } from '@babel/parser';\nimport _traverse, { type NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport { detectFormatCommand } from '@intlayer/chokidar/cli';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { extractBabelContentForComponents } from './babelProcessor';\nimport {\n getExistingIntlayerInfo,\n type PackageName,\n SERVER_CAPABLE_PACKAGES,\n} from './utils';\n\nexport type TextEdit = {\n start: number;\n end: number;\n replacement: string;\n};\n\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as any).default\n) as typeof _traverse;\n\n/**\n * Processes a TSX/JSX/TS/JS file to extract content and inject Intlayer hooks/calls.\n */\nexport const processTsxFile = (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n configuration: IntlayerConfig,\n save: boolean = true,\n unmergedDictionaries: Record<string, unknown> = {},\n providedFileCode?: string\n): {\n extractedContent: Record<string, Record<string, string>>;\n modifiedCode: string;\n} | null => {\n const fileCode = providedFileCode ?? readFileSync(filePath, 'utf-8');\n\n const ast = parse(fileCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n const hasUseClient = ast.program.directives.some(\n (directive) => directive.value.value === 'use client'\n );\n\n const effectivePackageName =\n SERVER_CAPABLE_PACKAGES.has(packageName) && !hasUseClient\n ? `${packageName}/server`\n : packageName;\n\n const isSolid = packageName === 'solid-intlayer';\n const existingKeys = new Set<string>();\n\n const {\n extractedContent,\n replacements,\n componentsNeedingHooks,\n componentKeyMap,\n componentPaths,\n hookMap,\n } = extractBabelContentForComponents(\n ast,\n fileCode,\n existingKeys,\n componentKey,\n configuration,\n filePath,\n unmergedDictionaries\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n const textEdits: TextEdit[] = [];\n\n const getProvidingHookType = (\n path: NodePath\n ): 'useIntlayer' | 'getIntlayer' => {\n let current: NodePath | null = path;\n while (current) {\n const functionPath = componentPaths.find(\n (path) => path.node === current?.node\n );\n\n if (functionPath) {\n const existingInfo = getExistingIntlayerInfo(functionPath);\n\n if (existingInfo) {\n return existingInfo.hook;\n }\n\n if (componentsNeedingHooks.has(functionPath)) {\n return hookMap.get(functionPath.node) || 'useIntlayer';\n }\n }\n current = current.parentPath;\n }\n return 'useIntlayer';\n };\n\n for (const {\n path,\n key,\n type,\n variables,\n childrenToReplace,\n } of replacements) {\n const contentAccessCode = isSolid ? `content().${key}` : `content.${key}`;\n const hookType = getProvidingHookType(path);\n const valueSuffix = hookType === 'getIntlayer' ? '' : '.value';\n\n if (type === 'jsx-text' && path.isJSXText()) {\n textEdits.push({\n start: path.node.start!,\n end: path.node.end!,\n replacement: `{${contentAccessCode}}`,\n });\n } else if (type === 'jsx-attribute' && path.isJSXAttribute()) {\n const valNode = path.node.value;\n\n if (valNode) {\n textEdits.push({\n start: valNode.start!,\n end: valNode.end!,\n replacement: `{${contentAccessCode}${valueSuffix}}`,\n });\n }\n } else if (type === 'string-literal' && path.isStringLiteral()) {\n textEdits.push({\n start: path.node.start!,\n end: path.node.end!,\n replacement: `${contentAccessCode}${valueSuffix}`,\n });\n } else if (\n type === 'jsx-text-combined' &&\n childrenToReplace &&\n childrenToReplace.length > 0\n ) {\n const accessStr = `{${contentAccessCode}}`;\n const start = childrenToReplace[0].start!;\n const end = childrenToReplace[childrenToReplace.length - 1].end!;\n textEdits.push({ start, end, replacement: accessStr });\n } else if (\n type === 'jsx-insertion' &&\n variables &&\n childrenToReplace &&\n childrenToReplace.length > 0\n ) {\n const objProps = variables\n .map((variableString) => {\n const [key, variableValue] = variableString\n .split(':')\n .map((part) => part.trim());\n return `${key}: ${variableValue}`;\n })\n .join(', ');\n\n const accessStr = `{${contentAccessCode}({ ${objProps} })}`;\n const start = childrenToReplace[0].start!;\n const end = childrenToReplace[childrenToReplace.length - 1].end!;\n textEdits.push({ start, end, replacement: accessStr });\n }\n }\n\n let needsUseIntlayer = false;\n let needsGetIntlayer = false;\n\n for (const componentPath of componentsNeedingHooks) {\n const finalKey = componentKeyMap.get(componentPath.node)!;\n const existingInfo = getExistingIntlayerInfo(componentPath);\n\n if (existingInfo) {\n if (existingInfo.hook === 'useIntlayer') needsUseIntlayer = true;\n\n if (existingInfo.hook === 'getIntlayer') needsGetIntlayer = true;\n } else {\n const hook = hookMap.get(componentPath.node) || 'useIntlayer';\n\n if (hook === 'useIntlayer') needsUseIntlayer = true;\n\n if (hook === 'getIntlayer') needsGetIntlayer = true;\n\n const bodyPath = componentPath.get('body') as NodePath;\n const hookStatementStr = `\\n const content = ${hook}('${finalKey}');\\n`;\n\n if (bodyPath.isBlockStatement()) {\n textEdits.push({\n start: bodyPath.node.start! + 1,\n end: bodyPath.node.start! + 1,\n replacement: hookStatementStr,\n });\n } else if (bodyPath.isExpression()) {\n const start = bodyPath.node.start!;\n const end = bodyPath.node.end!;\n\n // Detect wrapping parentheses: `() => (expr)` — scan backward from\n // the expression start and forward from its end for matching `(` / `)`.\n let parenStart = -1;\n let parenEnd = -1;\n\n for (let i = start - 1; i >= 0; i--) {\n const char = fileCode[i];\n if (char === '(') {\n parenStart = i;\n break;\n }\n if (char !== ' ' && char !== '\\n' && char !== '\\r' && char !== '\\t')\n break;\n }\n\n if (parenStart !== -1) {\n for (let i = end; i < fileCode.length; i++) {\n const char = fileCode[i];\n if (char === ')') {\n parenEnd = i;\n break;\n }\n if (char !== ' ' && char !== '\\n' && char !== '\\r' && char !== '\\t')\n break;\n }\n }\n\n if (parenStart !== -1 && parenEnd !== -1) {\n // Replace the surrounding `(` … `)` with a block statement. We keep\n // the parentheses as `return (…)` to prevent automatic semicolon\n // insertion when the returned expression starts on a new line.\n textEdits.push({\n start: parenEnd,\n end: parenEnd + 1,\n replacement: `)\\n}`,\n });\n textEdits.push({\n start: parenStart,\n end: parenStart + 1,\n replacement: `{\\n const content = ${hook}('${finalKey}');\\n return (`,\n });\n } else {\n textEdits.push({\n start: end,\n end: end,\n replacement: `\\n}`,\n });\n textEdits.push({\n start: start,\n end: start,\n replacement: `{\\n const content = ${hook}('${finalKey}');\\n return `,\n });\n }\n }\n }\n }\n\n const injectImport = (hookName: string, targetPackage: string) => {\n let existingImportPath: NodePath<t.ImportDeclaration> | undefined;\n\n traverse(ast, {\n ImportDeclaration(path) {\n if (path.node.source.value === targetPackage) {\n existingImportPath = path;\n path.stop();\n }\n },\n });\n\n if (!existingImportPath) {\n const newImportStr = `import { ${hookName} } from '${targetPackage}';\\n`;\n let insertPos = 0;\n\n if (ast.program.body.length > 0) {\n insertPos = ast.program.body[0].start!;\n } else if (ast.program.directives && ast.program.directives.length > 0) {\n insertPos =\n ast.program.directives[ast.program.directives.length - 1].end!;\n\n if (fileCode[insertPos] === ';') insertPos++;\n\n textEdits.push({\n start: insertPos,\n end: insertPos,\n replacement: `\\n${newImportStr}`,\n });\n return;\n }\n\n if (\n insertPos === 0 ||\n (ast.program.body.length > 0 &&\n insertPos === ast.program.body[0].start!)\n ) {\n textEdits.push({\n start: insertPos,\n end: insertPos,\n replacement: newImportStr,\n });\n }\n } else {\n const existingSpecifiers = existingImportPath.node.specifiers;\n const missingImport = !existingSpecifiers.some(\n (specifier) =>\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported) &&\n specifier.imported.name === hookName\n );\n\n if (missingImport) {\n const importCode = fileCode.slice(\n existingImportPath.node.start!,\n existingImportPath.node.end!\n );\n const closingBraceIndex = importCode.lastIndexOf('}');\n\n if (closingBraceIndex !== -1) {\n const isCommaNeeded = !importCode\n .slice(0, closingBraceIndex)\n .trim()\n .endsWith(',');\n const absolutePos =\n existingImportPath.node.start! + closingBraceIndex;\n const prefix = isCommaNeeded ? ', ' : ' ';\n textEdits.push({\n start: absolutePos,\n end: absolutePos,\n replacement: `${prefix}${hookName} `,\n });\n }\n }\n }\n };\n\n if (needsUseIntlayer) injectImport('useIntlayer', effectivePackageName);\n\n if (needsGetIntlayer) injectImport('getIntlayer', 'intlayer');\n\n textEdits.sort((editA, editB) => {\n if (editB.start !== editA.start) return editB.start - editA.start;\n\n return editB.end - editA.end;\n });\n\n let formattedCode = fileCode;\n\n for (const edit of textEdits) {\n formattedCode =\n formattedCode.slice(0, edit.start) +\n edit.replacement +\n formattedCode.slice(edit.end);\n }\n\n if (save) {\n writeFileSync(filePath, formattedCode);\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n }\n\n return { extractedContent, modifiedCode: formattedCode };\n};\n"],"mappings":"+bAoBA,MAAM,EACJ,OAAOA,EAAAA,SAAc,WAAaA,EAAAA,QAAaA,EAAAA,QAAkB,QAMtD,GACX,EACA,EACA,EACA,EACA,EAAgB,GAChB,EAAgD,EAAE,CAClD,IAIU,CACV,IAAM,EAAW,IAAA,EAAA,EAAA,cAAiC,EAAU,QAAQ,CAE9D,GAAA,EAAA,EAAA,OAAY,EAAU,CAC1B,WAAY,SACZ,QAAS,CAAC,MAAO,aAAa,CAC/B,CAAC,CAEI,EAAe,EAAI,QAAQ,WAAW,KACzC,GAAc,EAAU,MAAM,QAAU,aAC1C,CAEK,EACJC,EAAAA,wBAAwB,IAAI,EAAY,EAAI,CAAC,EACzC,GAAG,EAAY,SACf,EAEA,EAAU,IAAgB,iBAG1B,CACJ,mBACA,eACA,yBACA,kBACA,iBACA,WACEC,EAAAA,iCACF,EACA,EAXmB,IAAI,IAavB,EACA,EACA,EACA,EACD,CAED,GAAI,OAAO,KAAK,EAAiB,CAAC,SAAW,EAAG,OAAO,KAEvD,IAAM,EAAwB,EAAE,CAE1B,EACJ,GACkC,CAClC,IAAI,EAA2B,EAC/B,KAAO,GAAS,CACd,IAAM,EAAe,EAAe,KACjC,GAAS,EAAK,OAAS,GAAS,KAClC,CAED,GAAI,EAAc,CACh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N,SAAS,IAAI,CACV,EACJ,EAAmB,KAAK,MAAS,EAC7B,EAAS,EAAgB,KAAO,IACtC,EAAU,KAAK,CACb,MAAO,EACP,IAAK,EACL,YAAa,GAAG,IAAS,EAAS,GACnC,CAAC,IAMN,GAAkB,EAAa,cAAe,EAAqB,CAEnE,GAAkB,EAAa,cAAe,WAAW,CAE7D,EAAU,MAAM,EAAO,IACjB,EAAM,QAAU,EAAM,MAEnB,EAAM,IAAM,EAAM,IAFe,EAAM,MAAQ,EAAM,MAG5D,CAEF,IAAI,EAAgB,EAEpB,IAAK,IAAM,KAAQ,EACjB,EACE,EAAc,MAAM,EAAG,EAAK,MAAM,CAClC,EAAK,YACL,EAAc,MAAM,EAAK,IAAI,CAGjC,GAAI,EAAM,EACR,EAAA,EAAA,eAAc,EAAU,EAAc,CAEtC,IAAM,GAAA,EAAA,EAAA,qBAAoC,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAS,CAAE,CACpD,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,EAK1B,MAAO,CAAE,mBAAkB,aAAc,EAAe"}
|
|
1
|
+
{"version":3,"file":"processTsxFile.cjs","names":["_traverse","SERVER_CAPABLE_PACKAGES","extractBabelContentForComponents","getExistingIntlayerInfo","t"],"sources":["../../../src/extractContent/processTsxFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { parse } from '@babel/parser';\nimport _traverse, { type NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport { detectFormatCommand } from '@intlayer/chokidar/cli';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { extractBabelContentForComponents } from './babelProcessor';\nimport {\n type ExistingIntlayerInfo,\n getExistingIntlayerInfo,\n type PackageName,\n SERVER_CAPABLE_PACKAGES,\n} from './utils';\n\nexport type TextEdit = {\n start: number;\n end: number;\n replacement: string;\n};\n\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as any).default\n) as typeof _traverse;\n\n/**\n * Processes a TSX/JSX/TS/JS file to extract content and inject Intlayer hooks/calls.\n */\nexport const processTsxFile = (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n configuration: IntlayerConfig,\n save: boolean = true,\n unmergedDictionaries: Record<string, unknown> = {},\n providedFileCode?: string\n): {\n extractedContent: Record<string, Record<string, string>>;\n modifiedCode: string;\n} | null => {\n const fileCode = providedFileCode ?? readFileSync(filePath, 'utf-8');\n\n const ast = parse(fileCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n const hasUseClient = ast.program.directives.some(\n (directive) => directive.value.value === 'use client'\n );\n\n const effectivePackageName =\n SERVER_CAPABLE_PACKAGES.has(packageName) && !hasUseClient\n ? `${packageName}/server`\n : packageName;\n\n const isSolid = packageName === 'solid-intlayer';\n const existingKeys = new Set<string>();\n\n const {\n extractedContent,\n replacements,\n componentsNeedingHooks,\n componentKeyMap,\n componentPaths,\n hookMap,\n } = extractBabelContentForComponents(\n ast,\n fileCode,\n existingKeys,\n componentKey,\n configuration,\n filePath,\n unmergedDictionaries\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n const textEdits: TextEdit[] = [];\n\n // Build a lookup map: component AST node → NodePath (O(1) access)\n const componentNodeToPath = new Map<t.Node, NodePath>();\n for (const componentPath of componentPaths) {\n componentNodeToPath.set(componentPath.node, componentPath);\n }\n\n // Cache getExistingIntlayerInfo results for all component paths (avoids repeated traversals)\n const existingInfoCache = new Map<t.Node, ExistingIntlayerInfo | undefined>();\n for (const componentPath of componentPaths) {\n existingInfoCache.set(\n componentPath.node,\n getExistingIntlayerInfo(componentPath)\n );\n }\n\n /**\n * Walks up the ancestor chain to find the nearest enclosing component's\n * existing Intlayer info (if any).\n */\n const getExistingInfoForPath = (\n path: NodePath\n ): ExistingIntlayerInfo | undefined => {\n let current: NodePath | null = path;\n while (current) {\n if (componentNodeToPath.has(current.node)) {\n return existingInfoCache.get(current.node);\n }\n current = current.parentPath;\n }\n return undefined;\n };\n\n const getProvidingHookType = (\n path: NodePath\n ): 'useIntlayer' | 'getIntlayer' => {\n let current: NodePath | null = path;\n while (current) {\n const componentPath = componentNodeToPath.get(current.node);\n\n if (componentPath) {\n const existingInfo = existingInfoCache.get(componentPath.node);\n\n if (existingInfo) {\n return existingInfo.hook;\n }\n\n if (componentsNeedingHooks.has(componentPath)) {\n return hookMap.get(componentPath.node) || 'useIntlayer';\n }\n }\n current = current.parentPath;\n }\n return 'useIntlayer';\n };\n\n for (const {\n path,\n key,\n type,\n variables,\n childrenToReplace,\n } of replacements) {\n const existingInfo = getExistingInfoForPath(path);\n // When the existing call is destructured (e.g. `const { a } = getIntlayer(...)`),\n // new keys are added directly to that destructuring, so access them by name alone.\n const varName = existingInfo?.variableName ?? 'content';\n const contentAccessCode = existingInfo?.isDestructured\n ? key\n : isSolid\n ? `${varName}().${key}`\n : `${varName}.${key}`;\n const hookType = getProvidingHookType(path);\n const valueSuffix = hookType === 'getIntlayer' ? '' : '.value';\n\n if (type === 'jsx-text' && path.isJSXText()) {\n textEdits.push({\n start: path.node.start!,\n end: path.node.end!,\n replacement: `{${contentAccessCode}}`,\n });\n } else if (type === 'jsx-attribute' && path.isJSXAttribute()) {\n const valNode = path.node.value;\n\n if (valNode) {\n textEdits.push({\n start: valNode.start!,\n end: valNode.end!,\n replacement: `{${contentAccessCode}${valueSuffix}}`,\n });\n }\n } else if (type === 'string-literal' && path.isStringLiteral()) {\n textEdits.push({\n start: path.node.start!,\n end: path.node.end!,\n replacement: `${contentAccessCode}${valueSuffix}`,\n });\n } else if (\n type === 'jsx-text-combined' &&\n childrenToReplace &&\n childrenToReplace.length > 0\n ) {\n const accessStr = `{${contentAccessCode}}`;\n const start = childrenToReplace[0].start!;\n const end = childrenToReplace[childrenToReplace.length - 1].end!;\n textEdits.push({ start, end, replacement: accessStr });\n } else if (\n type === 'jsx-insertion' &&\n variables &&\n childrenToReplace &&\n childrenToReplace.length > 0\n ) {\n const objProps = variables\n .map((variableString) => {\n const [key, variableValue] = variableString\n .split(':')\n .map((part) => part.trim());\n return `${key}: ${variableValue}`;\n })\n .join(', ');\n\n const accessStr = `{${contentAccessCode}({ ${objProps} })}`;\n const start = childrenToReplace[0].start!;\n const end = childrenToReplace[childrenToReplace.length - 1].end!;\n textEdits.push({ start, end, replacement: accessStr });\n }\n }\n\n let needsUseIntlayer = false;\n let needsGetIntlayer = false;\n\n for (const componentPath of componentsNeedingHooks) {\n const finalKey = componentKeyMap.get(componentPath.node)!;\n const existingInfo = existingInfoCache.get(componentPath.node);\n\n if (existingInfo) {\n if (existingInfo.hook === 'useIntlayer') needsUseIntlayer = true;\n\n if (existingInfo.hook === 'getIntlayer') needsGetIntlayer = true;\n\n // When the existing call is destructured, inject any missing keys into\n // the destructuring pattern so they can be accessed by name directly.\n if (existingInfo.isDestructured && existingInfo.objectPatternNode) {\n const neededKeys = new Set<string>();\n\n for (const { path: rPath, key: rKey } of replacements) {\n let current: NodePath | null = rPath;\n\n while (current) {\n if (current.node === componentPath.node) {\n neededKeys.add(rKey);\n break;\n }\n current = current.parentPath;\n }\n }\n\n const missingKeys = [...neededKeys].filter(\n (key) => !existingInfo.existingDestructuredKeys.includes(key)\n );\n\n if (missingKeys.length > 0) {\n const { objectPatternNode } = existingInfo;\n // Insert right after the last property so the space/newline before\n // `}` is naturally preserved: `{ a }` → `{ a, b }`.\n const lastProp =\n objectPatternNode.properties[\n objectPatternNode.properties.length - 1\n ];\n textEdits.push({\n start: lastProp.end!,\n end: lastProp.end!,\n replacement: `, ${missingKeys.join(', ')}`,\n });\n }\n }\n } else {\n const hook = hookMap.get(componentPath.node) || 'useIntlayer';\n\n if (hook === 'useIntlayer') needsUseIntlayer = true;\n\n if (hook === 'getIntlayer') needsGetIntlayer = true;\n\n const bodyPath = componentPath.get('body') as NodePath;\n const hookStatementStr = `\\n const content = ${hook}('${finalKey}');\\n`;\n\n if (bodyPath.isBlockStatement()) {\n textEdits.push({\n start: bodyPath.node.start! + 1,\n end: bodyPath.node.start! + 1,\n replacement: hookStatementStr,\n });\n } else if (bodyPath.isExpression()) {\n const start = bodyPath.node.start!;\n const end = bodyPath.node.end!;\n\n // Detect wrapping parentheses: `() => (expr)` — scan backward from\n // the expression start and forward from its end for matching `(` / `)`.\n let parenStart = -1;\n let parenEnd = -1;\n\n for (let i = start - 1; i >= 0; i--) {\n const char = fileCode[i];\n if (char === '(') {\n parenStart = i;\n break;\n }\n if (char !== ' ' && char !== '\\n' && char !== '\\r' && char !== '\\t')\n break;\n }\n\n if (parenStart !== -1) {\n for (let i = end; i < fileCode.length; i++) {\n const char = fileCode[i];\n if (char === ')') {\n parenEnd = i;\n break;\n }\n if (char !== ' ' && char !== '\\n' && char !== '\\r' && char !== '\\t')\n break;\n }\n }\n\n if (parenStart !== -1 && parenEnd !== -1) {\n // Replace the surrounding `(` … `)` with a block statement. We keep\n // the parentheses as `return (…)` to prevent automatic semicolon\n // insertion when the returned expression starts on a new line.\n textEdits.push({\n start: parenEnd,\n end: parenEnd + 1,\n replacement: `)\\n}`,\n });\n textEdits.push({\n start: parenStart,\n end: parenStart + 1,\n replacement: `{\\n const content = ${hook}('${finalKey}');\\n return (`,\n });\n } else {\n textEdits.push({\n start: end,\n end: end,\n replacement: `\\n}`,\n });\n textEdits.push({\n start: start,\n end: start,\n replacement: `{\\n const content = ${hook}('${finalKey}');\\n return `,\n });\n }\n }\n }\n }\n\n const injectImport = (hookName: string, targetPackage: string) => {\n let existingImportPath: NodePath<t.ImportDeclaration> | undefined;\n\n traverse(ast, {\n ImportDeclaration(path) {\n if (path.node.source.value === targetPackage) {\n existingImportPath = path;\n path.stop();\n }\n },\n });\n\n if (!existingImportPath) {\n const newImportStr = `import { ${hookName} } from '${targetPackage}';\\n`;\n let insertPos = 0;\n\n if (ast.program.body.length > 0) {\n insertPos = ast.program.body[0].start!;\n } else if (ast.program.directives && ast.program.directives.length > 0) {\n insertPos =\n ast.program.directives[ast.program.directives.length - 1].end!;\n\n if (fileCode[insertPos] === ';') insertPos++;\n\n textEdits.push({\n start: insertPos,\n end: insertPos,\n replacement: `\\n${newImportStr}`,\n });\n return;\n }\n\n if (\n insertPos === 0 ||\n (ast.program.body.length > 0 &&\n insertPos === ast.program.body[0].start!)\n ) {\n textEdits.push({\n start: insertPos,\n end: insertPos,\n replacement: newImportStr,\n });\n }\n } else {\n const existingSpecifiers = existingImportPath.node.specifiers;\n const missingImport = !existingSpecifiers.some(\n (specifier) =>\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported) &&\n specifier.imported.name === hookName\n );\n\n if (missingImport) {\n const importCode = fileCode.slice(\n existingImportPath.node.start!,\n existingImportPath.node.end!\n );\n const closingBraceIndex = importCode.lastIndexOf('}');\n\n if (closingBraceIndex !== -1) {\n const isCommaNeeded = !importCode\n .slice(0, closingBraceIndex)\n .trim()\n .endsWith(',');\n const absolutePos =\n existingImportPath.node.start! + closingBraceIndex;\n const prefix = isCommaNeeded ? ', ' : ' ';\n textEdits.push({\n start: absolutePos,\n end: absolutePos,\n replacement: `${prefix}${hookName} `,\n });\n }\n }\n }\n };\n\n if (needsUseIntlayer) injectImport('useIntlayer', effectivePackageName);\n\n if (needsGetIntlayer) injectImport('getIntlayer', 'intlayer');\n\n textEdits.sort((editA, editB) => {\n if (editB.start !== editA.start) return editB.start - editA.start;\n\n return editB.end - editA.end;\n });\n\n let formattedCode = fileCode;\n\n for (const edit of textEdits) {\n formattedCode =\n formattedCode.slice(0, edit.start) +\n edit.replacement +\n formattedCode.slice(edit.end);\n }\n\n if (save) {\n writeFileSync(filePath, formattedCode);\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n }\n\n return { extractedContent, modifiedCode: formattedCode };\n};\n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ACd,QAAQ,MAAM,EAAM,EAK1B,MAAO,CAAE,mBAAkB,aAAc,EAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./extractDictionaryKey.cjs`);let t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./extractDictionaryKey.cjs`);let t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/logger`),r=require(`node:path`),i=require(`@intlayer/config/utils`),a=require(`@intlayer/unmerged-dictionaries-entry`);const o=e=>{if(typeof e.compiler?.output==`string`)return t=>(0,i.parseStringPattern)(e.compiler.output,t);if(typeof e.compiler?.output==`function`)return e.compiler.output;throw Error(`No output configuration found. Add a ${(0,n.colorize)(`compiler.output`,n.ANSIColors.BLUE)} in your configuration.`)},s=async(e,n,i,s)=>{let{baseDir:c}=i.system,{defaultLocale:l}=i.internationalization,u=((0,a.getUnmergedDictionaries)(i)??{})[n]?.filter(e=>e.location!==`remote`).filter(e=>e.locale===void 0||e.locale===(s??l));if(u?.[0]?.filePath){let e=u[0].filePath,t=(0,r.resolve)(c,e);return{absolutePath:t,relativePath:(0,r.relative)(c,t),isPerLocale:!1}}let d=o(i),f=(0,r.extname)(e),p=(0,r.basename)(e,f),m=p.charAt(0).toLowerCase()+p.slice(1),h=(0,t.getFormatFromExtension)(f),g={key:n,componentDirPath:(0,r.relative)(c,(0,r.dirname)(e)),componentFileName:p,fileName:m,componentFormat:h,componentExtension:f,format:h,locale:l,extension:i.content.fileExtensions[0]},_=(0,t.resolveRelativePath)(await d(g),e,c),v=`###########locale###########`,y=(await d({...g,locale:v})).includes(v);return{absolutePath:_,relativePath:(0,r.relative)(c,_),isPerLocale:y}},c=async(t,n,r)=>{let i=e.extractDictionaryKey(t,n);return{dictionaryKey:i,...await s(t,i,r)}};exports.extractDictionaryInfo=c,exports.getOutput=o,exports.resolveContentFilePaths=s;
|
|
2
2
|
//# sourceMappingURL=extractDictionaryInfo.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractDictionaryInfo.cjs","names":["
|
|
1
|
+
{"version":3,"file":"extractDictionaryInfo.cjs","names":["ANSIColors","extractDictionaryKey"],"sources":["../../../../src/extractContent/utils/extractDictionaryInfo.ts"],"sourcesContent":["import { basename, dirname, extname, relative, resolve } from 'node:path';\nimport {\n getFormatFromExtension,\n resolveRelativePath,\n} from '@intlayer/chokidar/utils';\nimport { ANSIColors, colorize } from '@intlayer/config/logger';\nimport { parseStringPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type {\n FilePathPatternContext,\n FilePathPatternFunction,\n} from '@intlayer/types/filePathPattern';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\nexport const getOutput = (\n configuration: IntlayerConfig\n): FilePathPatternFunction => {\n if (typeof configuration.compiler?.output === 'string') {\n return (context: FilePathPatternContext) =>\n parseStringPattern(configuration.compiler.output as string, context);\n }\n\n if (typeof configuration.compiler?.output === 'function') {\n return configuration.compiler.output;\n }\n\n throw new Error(\n `No output configuration found. Add a ${colorize('compiler.output', ANSIColors.BLUE)} in your configuration.`\n );\n};\n\nexport type ResolveContentFilePaths = {\n absolutePath: string;\n relativePath: string;\n isPerLocale: boolean;\n};\n\n/**\n * Resolves the paths for the content files associated with a component.\n * Checks for existing dictionaries first.\n */\nexport const resolveContentFilePaths = async (\n filePath: string,\n componentKey: string,\n configuration: IntlayerConfig,\n locale?: Locale\n): Promise<ResolveContentFilePaths> => {\n const { baseDir } = configuration.system;\n const { defaultLocale } = configuration.internationalization;\n\n const unmergedDictionaries = getUnmergedDictionaries(configuration) ?? {};\n const existingDicts = unmergedDictionaries[componentKey]\n ?.filter(\n (dictionary) =>\n // Remove remote dictionaries (Fix: Check for !== instead of ===)\n dictionary.location !== 'remote'\n )\n .filter(\n (dictionary) =>\n // Check for first locale dictionary sorted by priority that include the targeted locale\n dictionary.locale === undefined ||\n dictionary.locale === (locale ?? defaultLocale)\n );\n\n if (existingDicts?.[0]?.filePath) {\n const existingPath = existingDicts[0].filePath;\n const resolvedAbsolutePath = resolve(baseDir, existingPath);\n\n return {\n absolutePath: resolvedAbsolutePath,\n relativePath: relative(baseDir, resolvedAbsolutePath),\n isPerLocale: false,\n };\n }\n\n const pattern = getOutput(configuration);\n\n const extension = extname(\n filePath\n ) as FilePathPatternContext['componentExtension'];\n const componentName = basename(filePath, extension);\n const uncapitalizedName =\n componentName.charAt(0).toLowerCase() + componentName.slice(1);\n const componentFormat = getFormatFromExtension(\n extension!\n ) as FilePathPatternContext['componentFormat'];\n\n const context: FilePathPatternContext = {\n key: componentKey,\n componentDirPath: relative(baseDir, dirname(filePath)),\n componentFileName: componentName,\n fileName: uncapitalizedName,\n componentFormat,\n componentExtension: extension,\n format: componentFormat!,\n locale: defaultLocale,\n extension: configuration.content.fileExtensions[0],\n };\n\n const rawAbsolutePath = await pattern(context);\n\n // Apply the resolution rules\n const absolutePath = resolveRelativePath(rawAbsolutePath, filePath, baseDir);\n\n const localeIdentifier = '###########locale###########' as Locale;\n\n const rawPerLocalePath = await pattern({\n ...context,\n locale: localeIdentifier,\n });\n const isPerLocale = rawPerLocalePath.includes(localeIdentifier);\n\n return {\n absolutePath,\n relativePath: relative(baseDir, absolutePath),\n isPerLocale,\n };\n};\n\nexport type ExtractDictionaryInfoOptions = {\n configuration?: IntlayerConfig;\n};\n\n/**\n * Extracts the dictionary key and dictionary file path for a given component file.\n */\nexport const extractDictionaryInfo = async (\n filePath: string,\n fileText: string,\n configuration: IntlayerConfig\n): Promise<\n {\n dictionaryKey: string;\n } & ResolveContentFilePaths\n> => {\n const dictionaryKey = extractDictionaryKey(filePath, fileText);\n\n const resolvedPaths = await resolveContentFilePaths(\n filePath,\n dictionaryKey,\n configuration\n );\n\n return {\n dictionaryKey,\n ...resolvedPaths,\n };\n};\n"],"mappings":"8VAgBA,MAAa,EACX,GAC4B,CAC5B,GAAI,OAAO,EAAc,UAAU,QAAW,SAC5C,MAAQ,KAAA,EAAA,EAAA,oBACa,EAAc,SAAS,OAAkB,EAAQ,CAGxE,GAAI,OAAO,EAAc,UAAU,QAAW,WAC5C,OAAO,EAAc,SAAS,OAGhC,MAAU,MACR,yCAAA,EAAA,EAAA,UAAiD,kBAAmBA,EAAAA,WAAW,KAAK,CAAC,yBACtF,EAaU,EAA0B,MACrC,EACA,EACA,EACA,IACqC,CACrC,GAAM,CAAE,WAAY,EAAc,OAC5B,CAAE,iBAAkB,EAAc,qBAGlC,IAAA,EAAA,EAAA,yBAD+C,EAAc,EAAI,EAAE,EAC9B,IACvC,OACC,GAEC,EAAW,WAAa,SAC3B,CACA,OACE,GAEC,EAAW,SAAW,IAAA,IACtB,EAAW,UAAY,GAAU,GACpC,CAEH,GAAI,IAAgB,IAAI,SAAU,CAChC,IAAM,EAAe,EAAc,GAAG,SAChC,GAAA,EAAA,EAAA,SAA+B,EAAS,EAAa,CAE3D,MAAO,CACL,aAAc,EACd,cAAA,EAAA,EAAA,UAAuB,EAAS,EAAqB,CACrD,YAAa,GACd,CAGH,IAAM,EAAU,EAAU,EAAc,CAElC,GAAA,EAAA,EAAA,SACJ,EACD,CACK,GAAA,EAAA,EAAA,UAAyB,EAAU,EAAU,CAC7C,EACJ,EAAc,OAAO,EAAE,CAAC,aAAa,CAAG,EAAc,MAAM,EAAE,CAC1D,GAAA,EAAA,EAAA,wBACJ,EACD,CAEK,EAAkC,CACtC,IAAK,EACL,kBAAA,EAAA,EAAA,UAA2B,GAAA,EAAA,EAAA,SAAiB,EAAS,CAAC,CACtD,kBAAmB,EACnB,SAAU,EACV,kBACA,mBAAoB,EACpB,OAAQ,EACR,OAAQ,EACR,UAAW,EAAc,QAAQ,eAAe,GACjD,CAKK,GAAA,EAAA,EAAA,qBAHkB,MAAM,EAAQ,EAAQ,CAGY,EAAU,EAAQ,CAEtE,EAAmB,+BAMnB,GAJmB,MAAM,EAAQ,CACrC,GAAG,EACH,OAAQ,EACT,CAAC,EACmC,SAAS,EAAiB,CAE/D,MAAO,CACL,eACA,cAAA,EAAA,EAAA,UAAuB,EAAS,EAAa,CAC7C,cACD,EAUU,EAAwB,MACnC,EACA,EACA,IAKG,CACH,IAAM,EAAgBC,EAAAA,qBAAqB,EAAU,EAAS,CAQ9D,MAAO,CACL,gBACA,GARoB,MAAM,EAC1B,EACA,EACA,EACD,CAKA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../../_virtual/_rolldown/runtime.cjs`);let t=require(`@babel/types`);t=e.__toESM(t);const n=e=>{let n;return e.traverse({CallExpression(e){let r=e.node.callee;if(t.isIdentifier(r)&&(r.name===`useIntlayer`||r.name===`getIntlayer`)){let i=e.node.arguments[0];t.isStringLiteral(i)&&(n={key:i.value,hook:r.name},e.stop()
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../../_virtual/_rolldown/runtime.cjs`);let t=require(`@babel/types`);t=e.__toESM(t);const n=e=>{let n;return e.traverse({CallExpression(e){let r=e.node.callee;if(t.isIdentifier(r)&&(r.name===`useIntlayer`||r.name===`getIntlayer`)){let i=e.node.arguments[0];if(t.isStringLiteral(i)){let a=e.parent,o=!1,s=[],c,l=`content`;t.isVariableDeclarator(a)&&(t.isObjectPattern(a.id)?(o=!0,c=a.id,s=a.id.properties.filter(e=>t.isObjectProperty(e)&&t.isIdentifier(e.key)).map(e=>e.key.name)):t.isIdentifier(a.id)&&(l=a.id.name)),n={key:i.value,hook:r.name,variableName:l,isDestructured:o,existingDestructuredKeys:s,objectPatternNode:c},e.stop()}}},Function(e){e.skip()}}),n};exports.getExistingIntlayerInfo=n;
|
|
2
2
|
//# sourceMappingURL=getExistingIntlayerInfo.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExistingIntlayerInfo.cjs","names":["t"],"sources":["../../../../src/extractContent/utils/getExistingIntlayerInfo.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\n\n/**\n * Searches for an existing useIntlayer or getIntlayer call in the function body.\n */\nexport const getExistingIntlayerInfo = (\n path: NodePath\n):
|
|
1
|
+
{"version":3,"file":"getExistingIntlayerInfo.cjs","names":["t"],"sources":["../../../../src/extractContent/utils/getExistingIntlayerInfo.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\n\nexport type ExistingIntlayerInfo = {\n key: string;\n hook: 'useIntlayer' | 'getIntlayer';\n /** The variable name used to store the call result (e.g. `t` in `const t = useIntlayer(...)`) */\n variableName: string;\n /** True when the call result is destructured: `const { a, b } = getIntlayer(...)` */\n isDestructured: boolean;\n /** Keys already present in the destructuring pattern (empty when not destructured) */\n existingDestructuredKeys: string[];\n /** The ObjectPattern AST node, present only when `isDestructured` is true */\n objectPatternNode?: t.ObjectPattern;\n};\n\n/**\n * Searches for an existing useIntlayer or getIntlayer call in the function body.\n */\nexport const getExistingIntlayerInfo = (\n path: NodePath\n): ExistingIntlayerInfo | undefined => {\n let result: ExistingIntlayerInfo | undefined;\n\n // We only check the direct body of the function, not nested functions\n path.traverse({\n CallExpression(childPath) {\n const callee = childPath.node.callee;\n\n if (\n t.isIdentifier(callee) &&\n (callee.name === 'useIntlayer' || callee.name === 'getIntlayer')\n ) {\n const arg = childPath.node.arguments[0];\n\n if (t.isStringLiteral(arg)) {\n const parentNode = childPath.parent;\n let isDestructured = false;\n let existingDestructuredKeys: string[] = [];\n let objectPatternNode: t.ObjectPattern | undefined;\n let variableName = 'content';\n\n if (t.isVariableDeclarator(parentNode)) {\n if (t.isObjectPattern(parentNode.id)) {\n isDestructured = true;\n objectPatternNode = parentNode.id;\n existingDestructuredKeys = parentNode.id.properties\n .filter(\n (p): p is t.ObjectProperty =>\n t.isObjectProperty(p) && t.isIdentifier(p.key)\n )\n .map((p) => (p.key as t.Identifier).name);\n } else if (t.isIdentifier(parentNode.id)) {\n variableName = parentNode.id.name;\n }\n }\n\n result = {\n key: arg.value,\n hook: callee.name as 'useIntlayer' | 'getIntlayer',\n variableName,\n isDestructured,\n existingDestructuredKeys,\n objectPatternNode,\n };\n childPath.stop();\n }\n }\n },\n Function(childPath) {\n childPath.skip(); // Don't look inside nested functions\n },\n });\n\n return result;\n};\n"],"mappings":"wKAmBA,MAAa,EACX,GACqC,CACrC,IAAI,EAoDJ,OAjDA,EAAK,SAAS,CACZ,eAAe,EAAW,CACxB,IAAM,EAAS,EAAU,KAAK,OAE9B,GACEA,EAAE,aAAa,EAAO,GACrB,EAAO,OAAS,eAAiB,EAAO,OAAS,eAClD,CACA,IAAM,EAAM,EAAU,KAAK,UAAU,GAErC,GAAIA,EAAE,gBAAgB,EAAI,CAAE,CAC1B,IAAM,EAAa,EAAU,OACzB,EAAiB,GACjB,EAAqC,EAAE,CACvC,EACA,EAAe,UAEfA,EAAE,qBAAqB,EAAW,GAChCA,EAAE,gBAAgB,EAAW,GAAG,EAClC,EAAiB,GACjB,EAAoB,EAAW,GAC/B,EAA2B,EAAW,GAAG,WACtC,OACE,GACCA,EAAE,iBAAiB,EAAE,EAAIA,EAAE,aAAa,EAAE,IAAI,CACjD,CACA,IAAK,GAAO,EAAE,IAAqB,KAAK,EAClCA,EAAE,aAAa,EAAW,GAAG,GACtC,EAAe,EAAW,GAAG,OAIjC,EAAS,CACP,IAAK,EAAI,MACT,KAAM,EAAO,KACb,eACA,iBACA,2BACA,oBACD,CACD,EAAU,MAAM,IAItB,SAAS,EAAW,CAClB,EAAU,MAAM,EAEnB,CAAC,CAEK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveDictionaryKey.cjs","names":[],"sources":["../../../../src/extractContent/utils/resolveDictionaryKey.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type {
|
|
1
|
+
{"version":3,"file":"resolveDictionaryKey.cjs","names":[],"sources":["../../../../src/extractContent/utils/resolveDictionaryKey.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\n/**\n * Resolves a unique dictionary key, checking for existing dictionaries and files.\n * Note: this chokidar-specific variant fetches unmergedDictionaries internally\n * from the configuration (unlike the `@intlayer/babel` version which takes it as a parameter).\n */\nexport const resolveDictionaryKey = (\n initialKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n unmergedDictionaries?: Record<string, unknown>,\n usedKeys: Set<string> = new Set()\n): string => {\n const dicts =\n unmergedDictionaries ?? getUnmergedDictionaries(configuration) ?? {};\n\n const { fileExtensions } = configuration.content;\n\n const dirName = dirname(filePath);\n const firstExtension = fileExtensions[0];\n const extension = firstExtension.startsWith('.')\n ? firstExtension\n : `.${firstExtension}`;\n\n let index = 0;\n\n while (index < 100) {\n const keyToTest = index === 0 ? initialKey : `${initialKey}${index}`;\n const dictionaries = dicts[keyToTest] as Dictionary[] | undefined;\n const contentFilePath = join(dirName, `${keyToTest}${extension}`);\n const isKeyUsed = usedKeys.has(keyToTest);\n const hasDictionaries = dictionaries && dictionaries.length > 0;\n const fileExists = existsSync(contentFilePath);\n\n if (!isKeyUsed && !hasDictionaries && !fileExists) {\n return keyToTest;\n }\n index++;\n }\n\n return initialKey;\n};\n"],"mappings":"sNAWA,MAAa,GACX,EACA,EACA,EACA,EACA,EAAwB,IAAI,MACjB,CACX,IAAM,EACJ,IAAA,EAAA,EAAA,yBAAgD,EAAc,EAAI,EAAE,CAEhE,CAAE,kBAAmB,EAAc,QAEnC,GAAA,EAAA,EAAA,SAAkB,EAAS,CAC3B,EAAiB,EAAe,GAChC,EAAY,EAAe,WAAW,IAAI,CAC5C,EACA,IAAI,IAEJ,EAAQ,EAEZ,KAAO,EAAQ,KAAK,CAClB,IAAM,EAAY,IAAU,EAAI,EAAa,GAAG,IAAa,IACvD,EAAe,EAAM,GACrB,GAAA,EAAA,EAAA,MAAuB,EAAS,GAAG,IAAY,IAAY,CAC3D,EAAY,EAAS,IAAI,EAAU,CACnC,EAAkB,GAAgB,EAAa,OAAS,EACxD,GAAA,EAAA,EAAA,YAAwB,EAAgB,CAE9C,GAAI,CAAC,GAAa,CAAC,GAAmB,CAAC,EACrC,OAAO,EAET,IAGF,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./extractContent/contentWriter.cjs`);let t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`);const i=(i=(0,r.getConfiguration)(),a=process.env.INTLAYER_IS_DEV_COMMAND)=>{let o=
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./extractContent/contentWriter.cjs`);let t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`);const i=(i=(0,r.getConfiguration)(),a=process.env.INTLAYER_IS_DEV_COMMAND)=>{let o=a===`dev`||a===`serve`||a===`true`,s=o?`dev`:`build`,c=(0,n.getAppLogger)(i);i.compiler?.enabled===`build-only`&&o&&c(`${(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)`);let l=i.compiler?.enabled??r.DefaultValues.Compiler.COMPILER_ENABLED;l===`build-only`&&(l=s?s===`build`:process.env.NODE_ENV===`production`);let u=(0,t.buildComponentFilesList)(i);return{enabled:l,configuration:i,filesList:u,onExtract:async({dictionaryKey:t,content:r,filePath:a})=>{try{await e.writeContentHelper(r,t,a,i)}catch(e){c([`Failed to process extracted content for ${(0,n.colorizeKey)(t)}:`,e],{level:`error`})}}}};exports.getExtractPluginOptions=i;
|
|
2
2
|
//# sourceMappingURL=getExtractPluginOptions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExtractPluginOptions.cjs","names":["ANSIColors","DefaultValues","writeContentHelper"],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"getExtractPluginOptions.cjs","names":["ANSIColors","DefaultValues","writeContentHelper"],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import { buildComponentFilesList } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { DefaultValues, getConfiguration } from '@intlayer/config/node';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { ExtractPluginOptions } from './babel-plugin-intlayer-extract';\nimport { writeContentHelper } from './extractContent/contentWriter';\n\n/**\n * Mode of the compiler\n * - 'dev': Development mode with HMR support\n * - 'build': Production build mode\n */\nexport type CompilerMode = 'dev' | 'build';\n\n/**\n * Get the options for the Intlayer Babel extraction plugin\n * This function loads the Intlayer configuration and sets up the onExtract callback\n * to write dictionaries to the filesystem.\n */\nexport const getExtractPluginOptions = (\n configuration: IntlayerConfig = getConfiguration(),\n isDev: CompilerMode | string | undefined = process.env.INTLAYER_IS_DEV_COMMAND\n): ExtractPluginOptions => {\n // Accept 'dev'/'serve' (Vite), boolean true, or the string 'true' (env var)\n const isDevBoolean = isDev === 'dev' || isDev === 'serve' || isDev === 'true';\n\n const compilerMode: CompilerMode = isDevBoolean ? 'dev' : 'build';\n\n const logger = getAppLogger(configuration);\n\n if (configuration.compiler?.enabled === 'build-only' && isDevBoolean) {\n logger(\n `${colorize('Compiler:', 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)`\n );\n }\n\n let enabled =\n configuration.compiler?.enabled ?? DefaultValues.Compiler.COMPILER_ENABLED;\n\n if (enabled === 'build-only') {\n if (compilerMode) {\n enabled = compilerMode === 'build';\n } else {\n // Fallback if mode isn't explicitly provided (e.g. pure babel plugin context)\n enabled = process.env.NODE_ENV === 'production';\n }\n }\n\n const filesList = buildComponentFilesList(configuration);\n\n return {\n enabled,\n configuration,\n filesList,\n onExtract: async ({ dictionaryKey, content, filePath }) => {\n try {\n await writeContentHelper(\n content,\n dictionaryKey,\n filePath,\n configuration\n );\n } catch (error) {\n logger(\n [\n `Failed to process extracted content for ${colorizeKey(dictionaryKey)}:`,\n error,\n ],\n { level: 'error' }\n );\n }\n },\n };\n};\n"],"mappings":"uRAwBA,MAAa,GACX,GAAA,EAAA,EAAA,mBAAkD,CAClD,EAA2C,QAAQ,IAAI,0BAC9B,CAEzB,IAAM,EAAe,IAAU,OAAS,IAAU,SAAW,IAAU,OAEjE,EAA6B,EAAe,MAAQ,QAEpD,GAAA,EAAA,EAAA,cAAsB,EAAc,CAEtC,EAAc,UAAU,UAAY,cAAgB,GACtD,EACE,IAAA,EAAA,EAAA,UAAY,YAAaA,EAAAA,WAAW,UAAU,CAAC,wIAChD,CAGH,IAAI,EACF,EAAc,UAAU,SAAWC,EAAAA,cAAc,SAAS,iBAExD,IAAY,eACd,AAIE,EAJE,EACQ,IAAiB,QAGjB,QAAQ,IAAI,WAAa,cAIvC,IAAM,GAAA,EAAA,EAAA,yBAAoC,EAAc,CAExD,MAAO,CACL,UACA,gBACA,YACA,UAAW,MAAO,CAAE,gBAAe,UAAS,cAAe,CACzD,GAAI,CACF,MAAMC,EAAAA,mBACJ,EACA,EACA,EACA,EACD,OACM,EAAO,CACd,EACE,CACE,4CAAA,EAAA,EAAA,aAAuD,EAAc,CAAC,GACtE,EACD,CACD,CAAE,MAAO,QAAS,CACnB,GAGN"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/chokidar/utils`),t=require(`@intlayer/config/node`),n=require(`node:path`);const r=e=>{try{let{getDictionaries:t}=require(`@intlayer/dictionaries-entry`),n=t(e);return Object.values(n)}catch{return[]}},i=i=>{let{configOptions:a,dictionaries:o,overrides:s}=i??{},c=(0,t.getConfiguration)(a),{mainDir:l,dictionariesDir:u,unmergedDictionariesDir:d,dynamicDictionariesDir:f,fetchDictionariesDir:p}=c.system,{importMode:m,optimize:h}=c.build,g=(0,
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/chokidar/utils`),t=require(`@intlayer/config/node`),n=require(`node:path`);const r=e=>{try{let{getDictionaries:t}=require(`@intlayer/dictionaries-entry`),n=t(e);return Object.values(n)}catch{return[]}},i=i=>{let{configOptions:a,dictionaries:o,overrides:s}=i??{},c=(0,t.getConfiguration)(a),{mainDir:l,dictionariesDir:u,unmergedDictionariesDir:d,dynamicDictionariesDir:f,fetchDictionariesDir:p}=c.system,{importMode:m,optimize:h}=c.build,g=(0,n.join)(l,`dictionaries.mjs`),_=(0,n.join)(l,`unmerged_dictionaries.mjs`),v=(0,n.join)(l,`dynamic_dictionaries.mjs`),y=(0,n.join)(l,`fetch_dictionaries.mjs`),b=[...(0,e.buildComponentFilesList)(c),g,_],x=o??r(c),S={};return x.forEach(e=>{S[e.key]=e.importMode??m}),{optimize:h,dictionariesDir:u,dictionariesEntryPath:g,unmergedDictionariesDir:d,unmergedDictionariesEntryPath:_,dynamicDictionariesDir:f,dynamicDictionariesEntryPath:v,fetchDictionariesDir:p,fetchDictionariesEntryPath:y,replaceDictionaryEntry:!0,importMode:m,dictionaryModeMap:S,filesList:b,...s}};exports.getOptimizePluginOptions=i;
|
|
2
2
|
//# sourceMappingURL=getOptimizePluginOptions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOptimizePluginOptions.cjs","names":[],"sources":["../../src/getOptimizePluginOptions.ts"],"sourcesContent":["import { join } from 'node:path';\nimport {
|
|
1
|
+
{"version":3,"file":"getOptimizePluginOptions.cjs","names":[],"sources":["../../src/getOptimizePluginOptions.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { buildComponentFilesList } from '@intlayer/chokidar/utils';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { OptimizePluginOptions } from './babel-plugin-intlayer-optimize';\n\ntype GetOptimizePluginOptionsParams = {\n /**\n * Configuration options for loading intlayer config\n */\n configOptions?: GetConfigurationOptions;\n /**\n * Pre-loaded dictionaries (optional - will be loaded if not provided)\n */\n dictionaries?: Dictionary[];\n /**\n * Override specific options\n */\n overrides?: Partial<OptimizePluginOptions>;\n};\n\n/**\n * Load dictionaries from the dictionaries-entry package\n */\nconst loadDictionaries = (config: IntlayerConfig): Dictionary[] => {\n try {\n // Dynamic require to avoid build-time dependency issues\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { getDictionaries } = require('@intlayer/dictionaries-entry');\n const dictionariesRecord = getDictionaries(config);\n\n return Object.values(dictionariesRecord);\n } catch {\n // If dictionaries-entry is not available, return empty array\n return [];\n }\n};\n\n/**\n * Get the options for the Intlayer Babel optimization plugin\n * This function loads the Intlayer configuration and returns the paths\n * needed for dictionary optimization and import rewriting.\n */\nexport const getOptimizePluginOptions = (\n params?: GetOptimizePluginOptionsParams\n): OptimizePluginOptions => {\n const {\n configOptions,\n dictionaries: providedDictionaries,\n overrides,\n } = params ?? {};\n\n const config = getConfiguration(configOptions);\n const {\n mainDir,\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n } = config.system;\n const { importMode, optimize } = config.build;\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(config);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by an empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by an empty object if import made dynamic\n ];\n\n // Load dictionaries if not provided\n const dictionaries = providedDictionaries ?? loadDictionaries(config);\n\n const dictionaryModeMap: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n > = {};\n\n dictionaries.forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] = dictionary.importMode ?? importMode;\n });\n\n return {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesDir,\n unmergedDictionariesEntryPath,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n replaceDictionaryEntry: true,\n importMode,\n dictionaryModeMap,\n filesList,\n ...overrides,\n };\n};\n"],"mappings":"mNA4BA,MAAM,EAAoB,GAAyC,CACjE,GAAI,CAGF,GAAM,CAAE,mBAAoB,QAAQ,+BAA+B,CAC7D,EAAqB,EAAgB,EAAO,CAElD,OAAO,OAAO,OAAO,EAAmB,MAClC,CAEN,MAAO,EAAE,GASA,EACX,GAC0B,CAC1B,GAAM,CACJ,gBACA,aAAc,EACd,aACE,GAAU,EAAE,CAEV,GAAA,EAAA,EAAA,kBAA0B,EAAc,CACxC,CACJ,UACA,kBACA,0BACA,yBACA,wBACE,EAAO,OACL,CAAE,aAAY,YAAa,EAAO,MAElC,GAAA,EAAA,EAAA,MAA6B,EAAS,mBAAmB,CACzD,GAAA,EAAA,EAAA,MACJ,EACA,4BACD,CACK,GAAA,EAAA,EAAA,MACJ,EACA,2BACD,CACK,GAAA,EAAA,EAAA,MAAkC,EAAS,yBAAyB,CAIpE,EAAY,CAChB,IAAA,EAAA,EAAA,yBAH+C,EAAO,CAItD,EACA,EACD,CAGK,EAAe,GAAwB,EAAiB,EAAO,CAE/D,EAGF,EAAE,CAMN,OAJA,EAAa,QAAS,GAAe,CACnC,EAAkB,EAAW,KAAO,EAAW,YAAc,GAC7D,CAEK,CACL,WACA,kBACA,wBACA,0BACA,gCACA,yBACA,+BACA,uBACA,6BACA,uBAAwB,GACxB,aACA,oBACA,YACA,GAAG,EACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{detectPackageName as e}from"./extractContent/utils/detectPackageName.mjs";import{extractContentSync as t}from"./extractContent/extractContent.mjs";import{ANSIColors as n,colorize as r,colorizePath as i,getAppLogger as a}from"@intlayer/config/logger";import{relative as o}from"node:path";import{parse as s}from"@babel/parser";const c=c=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(c,l){let u=l.opts;if(u.enabled===!1)return;let d=l.file.opts.filename;if(!d||u.filesList&&!u.filesList.includes(d))return;let f=l.file.code??``;if(!f)return;let p=a(u.configuration),m=u.packageName??e(d),{saveComponents:h}=u.configuration.compiler,g=t(d,m,{configuration:u.configuration,code:f,onExtract:e=>{u.onExtract&&u.onExtract({dictionaryKey:e.key,filePath:d,content:e.content,locale:u.configuration.internationalization.defaultLocale})},declarationOnly:!h});if(!g)return;let{transformedCode:_}=g;if(_)try{let e=s(_,{sourceType:`module`,plugins:[`jsx`,`typescript`]});c.node.body=e.program.body,c.node.directives=e.program.directives,p(`${r(`Compiler:`,n.GREY_DARK)} Extracted content from ${i(o(u.configuration.system.baseDir,d))}`,{level:`debug`})}catch(e){
|
|
1
|
+
import{detectPackageName as e}from"./extractContent/utils/detectPackageName.mjs";import{extractContentSync as t}from"./extractContent/extractContent.mjs";import{ANSIColors as n,colorize as r,colorizePath as i,getAppLogger as a}from"@intlayer/config/logger";import{relative as o}from"node:path";import{parse as s}from"@babel/parser";const c=c=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(c,l){let u=l.opts;if(u.enabled===!1)return;let d=l.file.opts.filename;if(!d||u.filesList&&!u.filesList.includes(d))return;let f=l.file.code??``;if(!f)return;let p=a(u.configuration),m=u.packageName??e(d),{saveComponents:h}=u.configuration.compiler,g=t(d,m,{configuration:u.configuration,code:f,onExtract:e=>{u.onExtract&&u.onExtract({dictionaryKey:e.key,filePath:d,content:e.content,locale:u.configuration.internationalization.defaultLocale})},declarationOnly:!h});if(!g)return;let{transformedCode:_}=g;if(_)try{let e=s(_,{sourceType:`module`,plugins:[`jsx`,`typescript`]});c.node.body=e.program.body,c.node.directives=e.program.directives,p(`${r(`Compiler:`,n.GREY_DARK)} Extracted content from ${i(o(u.configuration.system.baseDir,d))}`,{level:`debug`})}catch(e){p([`Failed to parse transformed code for ${i(o(u.configuration.system.baseDir,d))}:`,e],{level:`error`})}}}}});export{c as intlayerExtractBabelPlugin};
|
|
2
2
|
//# sourceMappingURL=babel-plugin-intlayer-extract.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-extract.mjs","names":[],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-extract.mjs","names":[],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport {\n ANSIColors,\n colorize,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n opts.onExtract({\n dictionaryKey: extractResult.key,\n filePath: filename,\n content: extractResult.content,\n locale: opts.configuration.internationalization.defaultLocale,\n });\n }\n },\n declarationOnly: !saveComponents,\n });\n\n if (!result) return;\n\n const { transformedCode: modifiedCode } = result;\n\n if (!modifiedCode) return;\n\n // Replace the Babel AST with the transformed code by re-parsing it.\n // This lets Babel serialise the injected hooks/imports through its\n // own code generator, preserving compatibility with other plugins.\n try {\n const newAst = parse(modifiedCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n programPath.node.body = newAst.program.body;\n programPath.node.directives = newAst.program.directives;\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted content from ${colorizePath(relative(opts.configuration.system.baseDir, filename))}`,\n { level: 'debug' }\n );\n } catch (error) {\n appLogger(\n [\n `Failed to parse transformed code for ${colorizePath(relative(opts.configuration.system.baseDir, filename))}:`,\n error,\n ],\n { level: 'error' }\n );\n }\n },\n },\n },\n };\n};\n"],"mappings":"4UA8DA,MAAa,EAA8B,IAGlC,CACL,KAAM,gCAEN,QAAS,CACP,QAAS,CACP,MAAM,EAAa,EAAO,CACxB,IAAM,EAAO,EAAM,KAKnB,GAFkB,EAAK,UAEL,GAAO,OAEzB,IAAM,EAAW,EAAM,KAAK,KAAK,SAIjC,GAFI,CAAC,GAED,EAAK,WAAa,CAAC,EAAK,UAAU,SAAS,EAAS,CAAE,OAE1D,IAAM,EAAmB,EAAM,KAAK,MAAQ,GAC5C,GAAI,CAAC,EAAU,OAEf,IAAM,EAAY,EAAa,EAAK,cAAc,CAC5C,EAAc,EAAK,aAAe,EAAkB,EAAS,CAE7D,CAAE,kBAAmB,EAAK,cAAc,SAExC,EAAS,EAAmB,EAAU,EAAa,CACvD,cAAe,EAAK,cACpB,KAAM,EACN,UAAY,GAGN,CACA,EAAK,WACP,EAAK,UAAU,CACb,cAAe,EAAc,IAC7B,SAAU,EACV,QAAS,EAAc,QACvB,OAAQ,EAAK,cAAc,qBAAqB,cACjD,CAAC,EAGN,gBAAiB,CAAC,EACnB,CAAC,CAEF,GAAI,CAAC,EAAQ,OAEb,GAAM,CAAE,gBAAiB,GAAiB,EAErC,KAKL,GAAI,CACF,IAAM,EAAS,EAAM,EAAc,CACjC,WAAY,SACZ,QAAS,CAAC,MAAO,aAAa,CAC/B,CAAC,CAEF,EAAY,KAAK,KAAO,EAAO,QAAQ,KACvC,EAAY,KAAK,WAAa,EAAO,QAAQ,WAE7C,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,0BAA0B,EAAa,EAAS,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,GAC5I,CAAE,MAAO,QAAS,CACnB,OACM,EAAO,CACd,EACE,CACE,wCAAwC,EAAa,EAAS,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,CAAC,GAC5G,EACD,CACD,CAAE,MAAO,QAAS,CACnB,GAGN,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{resolveContentFilePaths as e}from"./utils/extractDictionaryInfo.mjs";import{existsSync as t}from"node:fs";import{mkdir as n}from"node:fs/promises";import{dirname as r,relative as i}from"node:path";import{buildDictionary as a,ensureIntlayerBundle as o,loadContentDeclaration as s,writeContentDeclaration as c}from"@intlayer/chokidar/build";import{insertContentInDictionary as l}from"@intlayer/core/plugins";
|
|
1
|
+
import{resolveContentFilePaths as e}from"./utils/extractDictionaryInfo.mjs";import{existsSync as t}from"node:fs";import{mkdir as n}from"node:fs/promises";import{dirname as r,relative as i}from"node:path";import{buildDictionary as a,ensureIntlayerBundle as o,loadContentDeclaration as s,writeContentDeclaration as c}from"@intlayer/chokidar/build";import{insertContentInDictionary as l}from"@intlayer/core/plugins";import{NodeType as u}from"@intlayer/types/nodeType";const d=e=>/\{\{[^}]+\}\}/.test(e),f=e=>{let t=[],n=/\{\{([^}]+)\}\}/g,r;for(let i=n.exec(e);i!==null;i=n.exec(e)){r=i;let e=r[1].trim();t.includes(e)||t.push(e)}return t};let p;const m=(e,t,n)=>{let r=l(t??{key:``,content:{},filePath:``},e,n).content,i={};for(let t in e)i[t]=r[t];for(let t in e){let n=e[t];if(typeof n==`string`&&d(n)){let e=i[t];e&&e.nodeType===u.Translation&&(i[t]={nodeType:u.Insertion,[u.Insertion]:e,fields:f(n)})}}return i},h=(e,t)=>{let n=l(t??{key:``,content:{},filePath:``},e).content,r={};for(let t in e)r[t]=n[t];for(let t in e){let n=e[t];if(typeof n==`string`&&d(n)){let e=r[t];typeof e==`string`&&(r[t]={nodeType:u.Insertion,[u.Insertion]:e,fields:f(n)})}}return r},g=async(l,u,d,f)=>{let{absolutePath:g,isPerLocale:_}=await e(d,u,f),{defaultLocale:v}=f.internationalization,{baseDir:y}=f.system;p||=await o(f);let b=r(g);await n(b,{recursive:!0});let x=null;if(t(g))try{x=await s(g,f,p)??null}catch(e){console.error(e)}let S=i(y,g),C;if(_){let e=h(l,x);C={...x,key:u,content:e,locale:v,filePath:S}}else{let e=m(l,x,v);C={...x,key:u,content:e,filePath:S}}let w=i(y,b),T=await c(C,f,{newDictionariesPath:w,localeList:[v]});return await a([{...C,filePath:i(y,T?.path??g)}],f),g};export{m as mergeWithExistingMultilingualDictionary,h as mergeWithExistingPerLocaleDictionary,g as writeContentHelper};
|
|
2
2
|
//# sourceMappingURL=contentWriter.mjs.map
|