@intlayer/babel 8.4.2 → 8.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/extractContent.cjs +1 -1
- package/dist/cjs/extractContent/extractContent.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/extractDictionaryKey.cjs +1 -1
- package/dist/cjs/extractContent/utils/extractDictionaryKey.cjs.map +1 -1
- package/dist/cjs/getExtractPluginOptions.cjs +1 -1
- package/dist/cjs/getExtractPluginOptions.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/extractContent.mjs +1 -1
- package/dist/esm/extractContent/extractContent.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/extractDictionaryKey.mjs +1 -1
- package/dist/esm/extractContent/utils/extractDictionaryKey.mjs.map +1 -1
- package/dist/esm/getExtractPluginOptions.mjs +1 -1
- package/dist/esm/getExtractPluginOptions.mjs.map +1 -1
- package/dist/types/babel-plugin-intlayer-extract.d.ts.map +1 -1
- package/dist/types/extractContent-AFk68B7L.d.ts.map +1 -1
- package/dist/types/extractDictionaryInfo-5GLZsA_I.d.ts.map +1 -1
- package/dist/types/getExtractPluginOptions.d.ts.map +1 -1
- package/package.json +9 -9
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./extractContent/utils/detectPackageName.cjs`),n=require(`./extractContent/extractContent.cjs`);let r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/logger`),a=require(`node:path`),o=require(`@babel/parser`);const s=e=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(e,s){let c=s.opts;if(c.enabled===!1)return;let l=s.file.opts.filename;if(!l||c.filesList&&!c.filesList.includes(l))return;let u=s.file.code??``;if(!u)return;let d=(0,i.getAppLogger)(c.configuration),f=c.packageName??t.detectPackageName(l),{saveComponents:p}=c.configuration.compiler,m=n.extractContentSync(l,f,{configuration:c.configuration,code:u,onExtract:e=>{c.onExtract&&c.onExtract({dictionaryKey:e.key,filePath:l,content:e.content,locale:c.configuration.internationalization.defaultLocale})},declarationOnly:!p});if(!m)return;let{transformedCode:h}=m;if(h)try{let t=(0,o.parse)(h,{sourceType:`module`,plugins:[`jsx`,`typescript`]});e.node.body=t.program.body,e.node.directives=t.program.directives,d(`${(0,i.colorize)(`Compiler:`,r.GREY_DARK)} Extracted content from ${(0,i.colorizePath)((0,a.relative)(c.configuration.system.baseDir,l))}`,{level:`debug`})}catch(e){d([`Failed to parse transformed code for ${(0,i.colorizePath)((0,a.relative)(c.configuration.system.baseDir,l))}:`,e],{level:`error`})}}}}});exports.intlayerExtractBabelPlugin=s;
|
|
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 {
|
|
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 * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } 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":"mWA0DA,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,EAAW,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`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`./utils/extractDictionaryKey.cjs`),n=require(`./contentWriter.cjs`),r=require(`./utils/constants.cjs`),i=require(`./utils/generateKey.cjs`),a=require(`./utils/shouldExtract.cjs`),o=require(`./babelProcessor.cjs`),s=require(`./processTsxFile.cjs`);let c=require(`@intlayer/config/colors`);c=e.t(c);let l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/node`),d=require(`node:fs`),f=require(`node:path`),p=require(`@intlayer/config/utils`),m=require(`@intlayer/unmerged-dictionaries-entry`),h=require(`@intlayer/chokidar/cli`),g=require(`node:child_process`),_=null,v=null;const y=(e,t)=>{if(t)return{extractedContentMap:{[e]:t.extractedContent},transformedCode:t.code}},b=(e,n,u,p,m,h)=>{let g=u?.code??(0,d.readFileSync)(e,`utf-8`),_=h??t.extractDictionaryKey(e,g,p.configuration.compiler.dictionaryKeyPrefix),v=(0,f.extname)(e),{vueCompiler:b,svelteCompiler:x,unmergedDictionaries:S,configuration:C}=p,w={generateKey:i.generateKey,shouldExtract:a.shouldExtract,attributesToExtract:r.ATTRIBUTES_TO_EXTRACT,extractDictionaryKeyFromPath:t.extractDictionaryKeyFromPath,extractTsContent:(e,t,n,r,i)=>o.extractTsContent(e,t,n,r,i,S)};if(v===`.vue`){if(!b)throw Error(`Please install ${(0,l.colorizePath)(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`);let t=b.processVueFile(e,_,n,w,m);if(t)return y(_,t)}if(v===`.svelte`){if(!x)throw Error(`Please install ${(0,l.colorizePath)(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`);let t=x.processSvelteFile(e,_,n,w,m);if(t)return y(_,t)}if([`.tsx`,`.jsx`,`.ts`,`.js`,`.cjs`,`.mjs`].includes(v)){let t=s.processTsxFile(e,_,n,C,m,S,g);if(t)return{extractedContentMap:t.extractedContent,transformedCode:t.modifiedCode}}},x=async(e,t,r,{configuration:i,baseDir:a,appLogger:o},s)=>{if(r?.onExtract)for(let[n,i]of Object.entries(e))await r.onExtract({key:n,content:i,filePath:t});if(!r?.codeOnly&&!r?.onExtract)for(let[r,s]of Object.entries(e)){let e=(0,f.relative)(a,await n.writeContentHelper(s,r,t,i));o(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Created content file: ${(0,l.colorizePath)(e)}`)}if(s){let e=(0,h.detectFormatCommand)(i);if(e)try{(0,g.execSync)(e.replace(`{{file}}`,t),{stdio:`inherit`,cwd:a})}catch(e){console.error(e)}o(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Updated component: ${(0,l.colorizePath)((0,f.relative)(a,t))}`)}},S=(e,t)=>{let n=t?.configuration??(0,u.getConfiguration)(t?.configOptions),r=(0,l.getAppLogger)(n),{baseDir:i}=n.system;return{configuration:n,appLogger:r,baseDir:i,unmergedDictionaries:t?.unmergedDictionaries??(0,m.getUnmergedDictionaries)(n),saveComponent:!t?.declarationOnly,componentExtension:(0,f.extname)(e)}},C=async(e,n,r)=>{let{configuration:i,appLogger:a,baseDir:o,unmergedDictionaries:s,saveComponent:u,componentExtension:p}=S(e,r);if(p===`.vue`&&!_)try{_=await import(`@intlayer/vue-compiler`)}catch{a(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Install ${(0,l.colorizePath)(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`)}if(p===`.svelte`&&!v)try{v=await import(`@intlayer/svelte-compiler`)}catch{a(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Install ${(0,l.colorizePath)(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`)}let m=t.extractDictionaryKey(e,r?.code??(0,d.readFileSync)(e,`utf-8`),i.compiler.dictionaryKeyPrefix),h=b(e,n,r,{vueCompiler:_,svelteCompiler:v,unmergedDictionaries:s,configuration:i},u,m);if(!h||!h.extractedContentMap){a(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} No extractable text found in ${(0,l.colorizePath)((0,f.relative)(o,e))}`,{isVerbose:!0});return}return await x(h.extractedContentMap,e,r,{configuration:i,baseDir:o,appLogger:a},u),{transformedCode:h.transformedCode,extractedContentMap:h.extractedContentMap}},w=(e,t,n)=>{let{configuration:r,appLogger:i,baseDir:a,unmergedDictionaries:o,saveComponent:s,componentExtension:u}=S(e,n),d=(0,p.getProjectRequire)();if(u===`.vue`&&!_)try{_=d(`@intlayer/vue-compiler`)}catch{i(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Install ${(0,l.colorizePath)(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`)}if(u===`.svelte`&&!v)try{v=d(`@intlayer/svelte-compiler`)}catch{i(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} Install ${(0,l.colorizePath)(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`)}let m=b(e,t,n,{vueCompiler:_,svelteCompiler:v,unmergedDictionaries:o,configuration:r},s);if(!m?.extractedContentMap){i(`${(0,l.colorize)(`Compiler:`,c.GREY_DARK)} No extractable text found in ${(0,l.colorizePath)((0,f.relative)(a,e))}`,{isVerbose:!0});return}let{extractedContentMap:h,transformedCode:g}=m;if(n?.onExtract)for(let[t,r]of Object.entries(h))n.onExtract({key:t,content:r,filePath:e});return{transformedCode:g,extractedContentMap:h}};exports.extractContent=C,exports.extractContentSync=w;
|
|
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 {\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":"+nBAmEI,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,IACsC,CACtC,IAAM,EAAW,GAAS,OAAA,EAAA,EAAA,cAAqB,E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AU,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
|
+
{"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 * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } 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":"mrBA+DI,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,IACsC,CACtC,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,sBAC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AE,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,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../../chunk-Bmb41Sf3.cjs`),t=require(`./extractDictionaryKey.cjs`);let n=require(`@intlayer/chokidar/utils`),r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/logger`),a=require(`node:path`),o=require(`@intlayer/config/utils`),s=require(`@intlayer/unmerged-dictionaries-entry`);const c=e=>{if(typeof e.compiler?.output==`string`)return t=>(0,o.parseStringPattern)(e.compiler.output,t);if(typeof e.compiler?.output==`function`)return e.compiler.output;throw Error(`No output configuration found. Add a ${(0,i.colorize)(`compiler.output`,r.BLUE)} in your configuration.`)},l=async(e,t,r,i)=>{let{baseDir:o}=r.system,{defaultLocale:l}=r.internationalization,u=((0,s.getUnmergedDictionaries)(r)??{})[t]?.filter(e=>e.location!==`remote`).filter(e=>e.locale===void 0||e.locale===(i??l));if(u?.[0]?.filePath){let e=u[0].filePath,t=(0,a.resolve)(o,e);return{absolutePath:t,relativePath:(0,a.relative)(o,t),isPerLocale:!1}}let d=c(r),f=(0,a.extname)(e),p=(0,a.basename)(e,f),m=p.charAt(0).toLowerCase()+p.slice(1),h=(0,n.getFormatFromExtension)(f),g={key:t,componentDirPath:(0,a.relative)(o,(0,a.dirname)(e)),componentFileName:p,fileName:m,componentFormat:h,componentExtension:f,format:h,locale:l,extension:r.content.fileExtensions[0]},_=(0,n.resolveRelativePath)(await d(g),e,o),v=`###########locale###########`,y=(await d({...g,locale:v})).includes(v);return{absolutePath:_,relativePath:(0,a.relative)(o,_),isPerLocale:y}},u=async(e,n,r)=>{let i=t.extractDictionaryKey(e,n);return{dictionaryKey:i,...await l(e,i,r)}};exports.extractDictionaryInfo=u,exports.getOutput=c,exports.resolveContentFilePaths=l;
|
|
2
2
|
//# sourceMappingURL=extractDictionaryInfo.cjs.map
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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 * as ANSIColors from '@intlayer/config/colors';\nimport { 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":"sYAiBA,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,EAAW,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`}),require(`../../chunk-Bmb41Sf3.cjs`);let e=require(`@intlayer/config/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../../chunk-Bmb41Sf3.cjs`);let e=require(`@intlayer/config/defaultValues`),t=require(`@intlayer/config/utils`),n=require(`@intlayer/chokidar/cli`);const r=(t,n=e.COMPILER_DICTIONARY_KEY_PREFIX)=>{let r=t.split(/[\\/]/),i=r.pop()||``,a=i.lastIndexOf(`.`),o=a===-1?i:i.slice(0,a);return o.toLowerCase()===`index`&&(o=r.pop()||o),`${n}${o.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}`},i=(i,a,o=e.COMPILER_DICTIONARY_KEY_PREFIX)=>{let s=(0,n.detectExportedComponentName)(a);return s?`${o}${(0,t.camelCaseToKebabCase)(s)}`:r(i,o)};exports.extractDictionaryKey=i,exports.extractDictionaryKeyFromPath=r;
|
|
2
2
|
//# sourceMappingURL=extractDictionaryKey.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractDictionaryKey.cjs","names":["
|
|
1
|
+
{"version":3,"file":"extractDictionaryKey.cjs","names":["COMPILER_DICTIONARY_KEY_PREFIX"],"sources":["../../../../src/extractContent/utils/extractDictionaryKey.ts"],"sourcesContent":["import { detectExportedComponentName } from '@intlayer/chokidar/cli';\nimport { COMPILER_DICTIONARY_KEY_PREFIX } from '@intlayer/config/defaultValues';\nimport { camelCaseToKebabCase } from '@intlayer/config/utils';\n\n/**\n * Extracts a dictionary key from a file path.\n *\n * Example: \"src/components/MyComponent/index.tsx\" -> \"comp-my-component\"\n */\nexport const extractDictionaryKeyFromPath = (\n filePath: string,\n prefix = COMPILER_DICTIONARY_KEY_PREFIX\n): string => {\n const pathParts = filePath.split(/[\\\\/]/);\n const fileNameWithExt = pathParts.pop() || '';\n const lastDotIndex = fileNameWithExt.lastIndexOf('.');\n let baseName =\n lastDotIndex !== -1\n ? fileNameWithExt.slice(0, lastDotIndex)\n : fileNameWithExt;\n\n if (baseName.toLowerCase() === 'index') {\n baseName = pathParts.pop() || baseName;\n }\n\n return `${prefix}${baseName\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase()}`;\n};\n\nexport const extractDictionaryKey = (\n filePath: string,\n fileText: string,\n prefix = COMPILER_DICTIONARY_KEY_PREFIX\n): string => {\n const componentName = detectExportedComponentName(fileText);\n\n if (componentName) {\n return `${prefix}${camelCaseToKebabCase(componentName)}`;\n }\n\n return extractDictionaryKeyFromPath(filePath, prefix);\n};\n"],"mappings":"+NASA,MAAa,GACX,EACA,EAASA,EAAAA,iCACE,CACX,IAAM,EAAY,EAAS,MAAM,QAAQ,CACnC,EAAkB,EAAU,KAAK,EAAI,GACrC,EAAe,EAAgB,YAAY,IAAI,CACjD,EACF,IAAiB,GAEb,EADA,EAAgB,MAAM,EAAG,EAAa,CAO5C,OAJI,EAAS,aAAa,GAAK,UAC7B,EAAW,EAAU,KAAK,EAAI,GAGzB,GAAG,IAAS,EAChB,QAAQ,kBAAmB,QAAQ,CACnC,QAAQ,UAAW,IAAI,CACvB,aAAa,IAGL,GACX,EACA,EACA,EAASA,EAAAA,iCACE,CACX,IAAM,GAAA,EAAA,EAAA,6BAA4C,EAAS,CAM3D,OAJI,EACK,GAAG,KAAA,EAAA,EAAA,sBAA8B,EAAc,GAGjD,EAA6B,EAAU,EAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./extractContent/contentWriter.cjs`);let n=require(`@intlayer/chokidar/utils`),r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/defaultValues`),a=require(`@intlayer/config/logger`),o=require(`@intlayer/config/node`);const s=(e=(0,o.getConfiguration)(),s=process.env.INTLAYER_IS_DEV_COMMAND)=>{let c=s===`dev`||s===`serve`||s===`true`,l=c?`dev`:`build`,u=(0,a.getAppLogger)(e);e.compiler?.enabled===`build-only`&&c&&u(`${(0,a.colorize)(`Compiler:`,r.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 d=e.compiler?.enabled??i.COMPILER_ENABLED;d===`build-only`&&(d=l?l===`build`:process.env.NODE_ENV===`production`);let f=(0,n.buildComponentFilesList)(e);return{enabled:d,configuration:e,filesList:f,onExtract:async({dictionaryKey:n,content:r,filePath:i})=>{try{await t.writeContentHelper(r,n,i,e)}catch(e){u([`Failed to process extracted content for ${(0,a.colorizeKey)(n)}:`,e],{level:`error`})}}}};exports.getExtractPluginOptions=s;
|
|
2
2
|
//# sourceMappingURL=getExtractPluginOptions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExtractPluginOptions.cjs","names":["ANSIColors","
|
|
1
|
+
{"version":3,"file":"getExtractPluginOptions.cjs","names":["ANSIColors","COMPILER_ENABLED","writeContentHelper"],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import { buildComponentFilesList } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { COMPILER_ENABLED } from '@intlayer/config/defaultValues';\nimport { colorize, colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { 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 = configuration.compiler?.enabled ?? 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":"2WAqBA,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,EAAW,UAAU,CAAC,wIAChD,CAGH,IAAI,EAAU,EAAc,UAAU,SAAWC,EAAAA,iBAE7C,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
|
-
import{detectPackageName as e}from"./extractContent/utils/detectPackageName.mjs";import{extractContentSync as t}from"./extractContent/extractContent.mjs";import
|
|
1
|
+
import{detectPackageName as e}from"./extractContent/utils/detectPackageName.mjs";import{extractContentSync as t}from"./extractContent/extractContent.mjs";import*as n from"@intlayer/config/colors";import{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 {
|
|
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 * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } 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":"sWA0DA,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{extractDictionaryKey as e,extractDictionaryKeyFromPath as t}from"./utils/extractDictionaryKey.mjs";import{writeContentHelper as n}from"./contentWriter.mjs";import{ATTRIBUTES_TO_EXTRACT as r}from"./utils/constants.mjs";import{generateKey as i}from"./utils/generateKey.mjs";import{shouldExtract as a}from"./utils/shouldExtract.mjs";import{extractTsContent as o}from"./babelProcessor.mjs";import{processTsxFile as s}from"./processTsxFile.mjs";import
|
|
1
|
+
import{extractDictionaryKey as e,extractDictionaryKeyFromPath as t}from"./utils/extractDictionaryKey.mjs";import{writeContentHelper as n}from"./contentWriter.mjs";import{ATTRIBUTES_TO_EXTRACT as r}from"./utils/constants.mjs";import{generateKey as i}from"./utils/generateKey.mjs";import{shouldExtract as a}from"./utils/shouldExtract.mjs";import{extractTsContent as o}from"./babelProcessor.mjs";import{processTsxFile as s}from"./processTsxFile.mjs";import*as c from"@intlayer/config/colors";import{colorize as l,colorizePath as u,getAppLogger as d}from"@intlayer/config/logger";import{getConfiguration as f}from"@intlayer/config/node";import{readFileSync as p}from"node:fs";import{extname as m,relative as h}from"node:path";import{getProjectRequire as g}from"@intlayer/config/utils";import{getUnmergedDictionaries as _}from"@intlayer/unmerged-dictionaries-entry";import{detectFormatCommand as v}from"@intlayer/chokidar/cli";import{execSync as y}from"node:child_process";let b=null,x=null;const S=(e,t)=>{if(t)return{extractedContentMap:{[e]:t.extractedContent},transformedCode:t.code}},C=(n,l,d,f,h,g)=>{let _=d?.code??p(n,`utf-8`),v=g??e(n,_,f.configuration.compiler.dictionaryKeyPrefix),y=m(n),{vueCompiler:b,svelteCompiler:x,unmergedDictionaries:C,configuration:w}=f,T={generateKey:i,shouldExtract:a,attributesToExtract:r,extractDictionaryKeyFromPath:t,extractTsContent:(e,t,n,r,i)=>o(e,t,n,r,i,C)};if(y===`.vue`){if(!b)throw Error(`Please install ${u(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`);let e=b.processVueFile(n,v,l,T,h);if(e)return S(v,e)}if(y===`.svelte`){if(!x)throw Error(`Please install ${u(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`);let e=x.processSvelteFile(n,v,l,T,h);if(e)return S(v,e)}if([`.tsx`,`.jsx`,`.ts`,`.js`,`.cjs`,`.mjs`].includes(y)){let e=s(n,v,l,w,h,C,_);if(e)return{extractedContentMap:e.extractedContent,transformedCode:e.modifiedCode}}},w=async(e,t,r,{configuration:i,baseDir:a,appLogger:o},s)=>{if(r?.onExtract)for(let[n,i]of Object.entries(e))await r.onExtract({key:n,content:i,filePath:t});if(!r?.codeOnly&&!r?.onExtract)for(let[r,s]of Object.entries(e)){let e=h(a,await n(s,r,t,i));o(`${l(`Compiler:`,c.GREY_DARK)} Created content file: ${u(e)}`)}if(s){let e=v(i);if(e)try{y(e.replace(`{{file}}`,t),{stdio:`inherit`,cwd:a})}catch(e){console.error(e)}o(`${l(`Compiler:`,c.GREY_DARK)} Updated component: ${u(h(a,t))}`)}},T=(e,t)=>{let n=t?.configuration??f(t?.configOptions),r=d(n),{baseDir:i}=n.system;return{configuration:n,appLogger:r,baseDir:i,unmergedDictionaries:t?.unmergedDictionaries??_(n),saveComponent:!t?.declarationOnly,componentExtension:m(e)}},E=async(t,n,r)=>{let{configuration:i,appLogger:a,baseDir:o,unmergedDictionaries:s,saveComponent:d,componentExtension:f}=T(t,r);if(f===`.vue`&&!b)try{b=await import(`@intlayer/vue-compiler`)}catch{a(`${l(`Compiler:`,c.GREY_DARK)} Install ${u(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`)}if(f===`.svelte`&&!x)try{x=await import(`@intlayer/svelte-compiler`)}catch{a(`${l(`Compiler:`,c.GREY_DARK)} Install ${u(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`)}let m=e(t,r?.code??p(t,`utf-8`),i.compiler.dictionaryKeyPrefix),g=C(t,n,r,{vueCompiler:b,svelteCompiler:x,unmergedDictionaries:s,configuration:i},d,m);if(!g||!g.extractedContentMap){a(`${l(`Compiler:`,c.GREY_DARK)} No extractable text found in ${u(h(o,t))}`,{isVerbose:!0});return}return await w(g.extractedContentMap,t,r,{configuration:i,baseDir:o,appLogger:a},d),{transformedCode:g.transformedCode,extractedContentMap:g.extractedContentMap}},D=(e,t,n)=>{let{configuration:r,appLogger:i,baseDir:a,unmergedDictionaries:o,saveComponent:s,componentExtension:d}=T(e,n),f=g();if(d===`.vue`&&!b)try{b=f(`@intlayer/vue-compiler`)}catch{i(`${l(`Compiler:`,c.GREY_DARK)} Install ${u(`@intlayer/vue-compiler`,c.YELLOW)} to process Vue files.`)}if(d===`.svelte`&&!x)try{x=f(`@intlayer/svelte-compiler`)}catch{i(`${l(`Compiler:`,c.GREY_DARK)} Install ${u(`@intlayer/svelte-compiler`,c.YELLOW)} to process Svelte files.`)}let p=C(e,t,n,{vueCompiler:b,svelteCompiler:x,unmergedDictionaries:o,configuration:r},s);if(!p?.extractedContentMap){i(`${l(`Compiler:`,c.GREY_DARK)} No extractable text found in ${u(h(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}};export{E as extractContent,D as extractContentSync};
|
|
2
2
|
//# sourceMappingURL=extractContent.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractContent.mjs","names":[],"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":"86BAmEA,IAAI,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,IACsC,CACtC,IAAM,EAAW,GAAS,MAAQ,EAAa,EAAU,QAAQ,CAC3D,EACJ,GACA,EACE,EACA,EACA,EAAa,cAAc,SAAS,oBACrC,CACG,EAAM,EAAQ,EAAS,CAEvB,CAAE,cAAa,iBAAgB,uBAAsB,iBACzD,EAEI,EAAiD,CACrD,cACA,gBACA,oBAAqB,EACrB,+BACA,kBAAmB,EAAK,EAAM,EAAM,EAAQ,IAC1C,EACE,EACA,EACA,EACA,EACA,EACA,EACD,CACJ,CAED,GAAI,IAAQ,OAAQ,CAClB,GAAI,CAAC,EACH,MAAU,MACR,kBAAkB,EAAa,yBAA0B,EAAW,OAAO,CAAC,wBAC7E,CAGH,IAAM,EAAM,EAAY,eACtB,EACA,EACA,EACA,EACA,EACD,CAED,GAAI,EACF,OAAO,EAAqB,EAAc,EAAI,CAIlD,GAAI,IAAQ,UAAW,CACrB,GAAI,CAAC,EACH,MAAU,MACR,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a,EAAW,UAAU,CAAC,WAAW,EAAa,yBAA0B,EAAW,OAAO,CAAC,wBACrH,CAIL,GAAI,IAAuB,WAAa,CAAC,EACvC,GAAI,CACF,EAAiB,EAAU,4BAA4B,MACjD,CACN,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,WAAW,EAAa,4BAA6B,EAAW,OAAO,CAAC,2BACxH,CAIL,IAAM,EAAS,EACb,EACA,EACA,EACA,CAAE,cAAa,iBAAgB,uBAAsB,gBAAe,CACpE,EACD,CAED,GAAI,CAAC,GAAQ,oBAAqB,CAChC,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,gCAAgC,EAAa,EAAS,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
|
+
{"version":3,"file":"extractContent.mjs","names":[],"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 * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } 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":"w8BA+DA,IAAI,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,IACsC,CACtC,IAAM,EAAW,GAAS,MAAQ,EAAa,EAAU,QAAQ,CAC3D,EACJ,GACA,EACE,EACA,EACA,EAAa,cAAc,SAAS,oBACrC,CACG,EAAM,EAAQ,EAAS,CAEvB,CAAE,cAAa,iBAAgB,uBAAsB,iBACzD,EAEI,EAAiD,CACrD,cACA,gBACA,oBAAqB,EACrB,+BACA,kBAAmB,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,EAAO,oBACP,EACA,EACA,CAAE,gBAAe,UAAS,YAAW,CACrC,EACD,CAEM,CACL,gBAAiB,EAAO,gBACxB,oBAAqB,EAAO,oBAC7B,EAaU,GACX,EACA,EACA,IAC8B,CAC9B,GAAM,CACJ,gBACA,YACA,UACA,uBACA,gBACA,sBACE,EAAa,EAAU,EAAQ,CAE7B,EAAY,GAAmB,CAErC,GAAI,IAAuB,QAAU,CAAC,EACpC,GAAI,CACF,EAAc,EAAU,yBAAyB,MAC3C,CACN,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,WAAW,EAAa,yBAA0B,EAAW,OAAO,CAAC,wBACrH,CAIL,GAAI,IAAuB,WAAa,CAAC,EACvC,GAAI,CACF,EAAiB,EAAU,4BAA4B,MACjD,CACN,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,WAAW,EAAa,4BAA6B,EAAW,OAAO,CAAC,2BACxH,CAIL,IAAM,EAAS,EACb,EACA,EACA,EACA,CAAE,cAAa,iBAAgB,uBAAsB,gBAAe,CACpE,EACD,CAED,GAAI,CAAC,GAAQ,oBAAqB,CAChC,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,gCAAgC,EAAa,EAAS,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,2 +1,2 @@
|
|
|
1
|
-
import{extractDictionaryKey as e}from"./extractDictionaryKey.mjs";import{getFormatFromExtension as t,resolveRelativePath as n}from"@intlayer/chokidar/utils";import
|
|
1
|
+
import{extractDictionaryKey as e}from"./extractDictionaryKey.mjs";import{getFormatFromExtension as t,resolveRelativePath as n}from"@intlayer/chokidar/utils";import*as r from"@intlayer/config/colors";import{colorize as i}from"@intlayer/config/logger";import{basename as a,dirname as o,extname as s,relative as c,resolve as l}from"node:path";import{parseStringPattern as u}from"@intlayer/config/utils";import{getUnmergedDictionaries as d}from"@intlayer/unmerged-dictionaries-entry";const f=e=>{if(typeof e.compiler?.output==`string`)return t=>u(e.compiler.output,t);if(typeof e.compiler?.output==`function`)return e.compiler.output;throw Error(`No output configuration found. Add a ${i(`compiler.output`,r.BLUE)} in your configuration.`)},p=async(e,r,i,u)=>{let{baseDir:p}=i.system,{defaultLocale:m}=i.internationalization,h=(d(i)??{})[r]?.filter(e=>e.location!==`remote`).filter(e=>e.locale===void 0||e.locale===(u??m));if(h?.[0]?.filePath){let e=h[0].filePath,t=l(p,e);return{absolutePath:t,relativePath:c(p,t),isPerLocale:!1}}let g=f(i),_=s(e),v=a(e,_),y=v.charAt(0).toLowerCase()+v.slice(1),b=t(_),x={key:r,componentDirPath:c(p,o(e)),componentFileName:v,fileName:y,componentFormat:b,componentExtension:_,format:b,locale:m,extension:i.content.fileExtensions[0]},S=n(await g(x),e,p),C=`###########locale###########`,w=(await g({...x,locale:C})).includes(C);return{absolutePath:S,relativePath:c(p,S),isPerLocale:w}},m=async(t,n,r)=>{let i=e(t,n);return{dictionaryKey:i,...await p(t,i,r)}};export{m as extractDictionaryInfo,f as getOutput,p as resolveContentFilePaths};
|
|
2
2
|
//# sourceMappingURL=extractDictionaryInfo.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractDictionaryInfo.mjs","names":[],"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
|
|
1
|
+
{"version":3,"file":"extractDictionaryInfo.mjs","names":[],"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 * as ANSIColors from '@intlayer/config/colors';\nimport { 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":"geAiBA,MAAa,EACX,GAC4B,CAC5B,GAAI,OAAO,EAAc,UAAU,QAAW,SAC5C,MAAQ,IACN,EAAmB,EAAc,SAAS,OAAkB,EAAQ,CAGxE,GAAI,OAAO,EAAc,UAAU,QAAW,WAC5C,OAAO,EAAc,SAAS,OAGhC,MAAU,MAC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TIONARY_KEY_PREFIX as e}from"@intlayer/config/defaultValues";import{camelCaseToKebabCase as t}from"@intlayer/config/utils";import{detectExportedComponentName as n}from"@intlayer/chokidar/cli";const r=(t,n=e)=>{let r=t.split(/[\\/]/),i=r.pop()||``,a=i.lastIndexOf(`.`),o=a===-1?i:i.slice(0,a);return o.toLowerCase()===`index`&&(o=r.pop()||o),`${n}${o.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}`},i=(i,a,o=e)=>{let s=n(a);return s?`${o}${t(s)}`:r(i,o)};export{i as extractDictionaryKey,r as extractDictionaryKeyFromPath};
|
|
2
2
|
//# sourceMappingURL=extractDictionaryKey.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractDictionaryKey.mjs","names":[],"sources":["../../../../src/extractContent/utils/extractDictionaryKey.ts"],"sourcesContent":["import { detectExportedComponentName } from '@intlayer/chokidar/cli';\nimport {
|
|
1
|
+
{"version":3,"file":"extractDictionaryKey.mjs","names":[],"sources":["../../../../src/extractContent/utils/extractDictionaryKey.ts"],"sourcesContent":["import { detectExportedComponentName } from '@intlayer/chokidar/cli';\nimport { COMPILER_DICTIONARY_KEY_PREFIX } from '@intlayer/config/defaultValues';\nimport { camelCaseToKebabCase } from '@intlayer/config/utils';\n\n/**\n * Extracts a dictionary key from a file path.\n *\n * Example: \"src/components/MyComponent/index.tsx\" -> \"comp-my-component\"\n */\nexport const extractDictionaryKeyFromPath = (\n filePath: string,\n prefix = COMPILER_DICTIONARY_KEY_PREFIX\n): string => {\n const pathParts = filePath.split(/[\\\\/]/);\n const fileNameWithExt = pathParts.pop() || '';\n const lastDotIndex = fileNameWithExt.lastIndexOf('.');\n let baseName =\n lastDotIndex !== -1\n ? fileNameWithExt.slice(0, lastDotIndex)\n : fileNameWithExt;\n\n if (baseName.toLowerCase() === 'index') {\n baseName = pathParts.pop() || baseName;\n }\n\n return `${prefix}${baseName\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase()}`;\n};\n\nexport const extractDictionaryKey = (\n filePath: string,\n fileText: string,\n prefix = COMPILER_DICTIONARY_KEY_PREFIX\n): string => {\n const componentName = detectExportedComponentName(fileText);\n\n if (componentName) {\n return `${prefix}${camelCaseToKebabCase(componentName)}`;\n }\n\n return extractDictionaryKeyFromPath(filePath, prefix);\n};\n"],"mappings":"mNASA,MAAa,GACX,EACA,EAAS,IACE,CACX,IAAM,EAAY,EAAS,MAAM,QAAQ,CACnC,EAAkB,EAAU,KAAK,EAAI,GACrC,EAAe,EAAgB,YAAY,IAAI,CACjD,EACF,IAAiB,GAEb,EADA,EAAgB,MAAM,EAAG,EAAa,CAO5C,OAJI,EAAS,aAAa,GAAK,UAC7B,EAAW,EAAU,KAAK,EAAI,GAGzB,GAAG,IAAS,EAChB,QAAQ,kBAAmB,QAAQ,CACnC,QAAQ,UAAW,IAAI,CACvB,aAAa,IAGL,GACX,EACA,EACA,EAAS,IACE,CACX,IAAM,EAAgB,EAA4B,EAAS,CAM3D,OAJI,EACK,GAAG,IAAS,EAAqB,EAAc,GAGjD,EAA6B,EAAU,EAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{writeContentHelper as e}from"./extractContent/contentWriter.mjs";import{buildComponentFilesList as t}from"@intlayer/chokidar/utils";import{
|
|
1
|
+
import{writeContentHelper as e}from"./extractContent/contentWriter.mjs";import{buildComponentFilesList as t}from"@intlayer/chokidar/utils";import*as n from"@intlayer/config/colors";import{COMPILER_ENABLED as r}from"@intlayer/config/defaultValues";import{colorize as i,colorizeKey as a,getAppLogger as o}from"@intlayer/config/logger";import{getConfiguration as s}from"@intlayer/config/node";const c=(c=s(),l=process.env.INTLAYER_IS_DEV_COMMAND)=>{let u=l===`dev`||l===`serve`||l===`true`,d=u?`dev`:`build`,f=o(c);c.compiler?.enabled===`build-only`&&u&&f(`${i(`Compiler:`,n.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 p=c.compiler?.enabled??r;p===`build-only`&&(p=d?d===`build`:!0);let m=t(c);return{enabled:p,configuration:c,filesList:m,onExtract:async({dictionaryKey:t,content:n,filePath:r})=>{try{await e(n,t,r,c)}catch(e){f([`Failed to process extracted content for ${a(t)}:`,e],{level:`error`})}}}};export{c as getExtractPluginOptions};
|
|
2
2
|
//# sourceMappingURL=getExtractPluginOptions.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExtractPluginOptions.mjs","names":[],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import { buildComponentFilesList } from '@intlayer/chokidar/utils';\nimport {
|
|
1
|
+
{"version":3,"file":"getExtractPluginOptions.mjs","names":[],"sources":["../../src/getExtractPluginOptions.ts"],"sourcesContent":["import { buildComponentFilesList } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { COMPILER_ENABLED } from '@intlayer/config/defaultValues';\nimport { colorize, colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { 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 = configuration.compiler?.enabled ?? 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":"sYAqBA,MAAa,GACX,EAAgC,GAAkB,CAClD,EAA2C,QAAQ,IAAI,0BAC9B,CAEzB,IAAM,EAAe,IAAU,OAAS,IAAU,SAAW,IAAU,OAEjE,EAA6B,EAAe,MAAQ,QAEpD,EAAS,EAAa,EAAc,CAEtC,EAAc,UAAU,UAAY,cAAgB,GACtD,EACE,GAAG,EAAS,YAAa,EAAW,UAAU,CAAC,wIAChD,CAGH,IAAI,EAAU,EAAc,UAAU,SAAW,EAE7C,IAAY,eACd,AAIE,EAJE,EACQ,IAAiB,QAGjB,IAId,IAAM,EAAY,EAAwB,EAAc,CAExD,MAAO,CACL,UACA,gBACA,YACA,UAAW,MAAO,CAAE,gBAAe,UAAS,cAAe,CACzD,GAAI,CACF,MAAM,EACJ,EACA,EACA,EACA,EACD,OACM,EAAO,CACd,EACE,CACE,2CAA2C,EAAY,EAAc,CAAC,GACtE,EACD,CACD,CAAE,MAAO,QAAS,CACnB,GAGN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-extract.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-extract.d.ts","names":[],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"mappings":";;;;;;;;KAaY,aAAA;EACV,aAAA;EACA,QAAA;EACA,OAAA,EAAS,MAAA;EACT,MAAA,EAAQ,MAAA;AAAA;AAAA,KAGE,oBAAA;EACV,WAAA,GAAc,WAAA;EACd,SAAA;EACA,OAAA;EAEA,aAAA,IAAiB,IAAA;EACjB,aAAA,EAAe,cAAA;EATD;;AAGhB;;;EAYE,SAAA,IAAa,MAAA,EAAQ,aAAA,YAAyB,OAAA;EAN/B;;;EAUf,MAAA,GAAS,eAAA;AAAA;AAAA,KAGN,KAAA,GAAQ,UAAA;EAAe,IAAA,EAAM,oBAAA;AAAA;;;;;;;;;;;;;;;AAFhC;;;cAqBW,0BAAA,GAA8B,MAAA;EACzC,KAAA,SAAc,UAAA;AAAA,MACZ,SAAA,CAAU,KAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractContent-AFk68B7L.d.ts","names":[],"sources":["../../src/extractContent/extractContent.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"extractContent-AFk68B7L.d.ts","names":[],"sources":["../../src/extractContent/extractContent.ts"],"mappings":";;;;;KA0BY,sBAAA;EACV,aAAA,GAAgB,uBAAA;EAChB,QAAA;EACA,eAAA;EACA,oBAAA,GAAuB,MAAA;EACvB,aAAA,GAAgB,cAAA;EAChB,IAAA;EACA,SAAA,IAAa,MAAA;IACX,GAAA;IACA,OAAA,EAAS,MAAA;IACT,QAAA;EAAA,aACW,OAAA;AAAA;AAAA,KAmNV,aAAA;EACH,eAAA;EACA,mBAAA,EAAqB,MAAA,SAAe,MAAA;AAAA;AAAA,cAmCzB,cAAA,GACX,QAAA,UACA,WAAA,EAAa,WAAA,EACb,OAAA,GAAU,sBAAA,KACT,OAAA,CAAQ,aAAA;;;;;;;;;;;cA8EE,kBAAA,GACX,QAAA,UACA,WAAA,EAAa,WAAA,EACb,OAAA,GAAU,sBAAA,KACT,aAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractDictionaryInfo-5GLZsA_I.d.ts","names":[],"sources":["../../src/extractContent/utils/extractDictionaryInfo.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"extractDictionaryInfo-5GLZsA_I.d.ts","names":[],"sources":["../../src/extractContent/utils/extractDictionaryInfo.ts"],"mappings":";;;;;cAiBa,SAAA,GACX,aAAA,EAAe,cAAA,KACd,uBAAA;AAAA,KAeS,uBAAA;EACV,YAAA;EACA,YAAA;EACA,WAAA;AAAA;;;;;cAOW,uBAAA,GACX,QAAA,UACA,YAAA,UACA,aAAA,EAAe,cAAA,EACf,MAAA,GAAS,MAAA,KACR,OAAA,CAAQ,uBAAA;AAAA,KAyEC,4BAAA;EACV,aAAA,GAAgB,cAAA;AAAA;;;;cAML,qBAAA,GACX,QAAA,UACA,QAAA,UACA,aAAA,EAAe,cAAA,KACd,OAAA;EAEC,aAAA;AAAA,IACE,uBAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExtractPluginOptions.d.ts","names":[],"sources":["../../src/getExtractPluginOptions.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"getExtractPluginOptions.d.ts","names":[],"sources":["../../src/getExtractPluginOptions.ts"],"mappings":";;;;;;AAcA;;;KAAY,YAAA;;AAOZ;;;;cAAa,uBAAA,GACX,aAAA,GAAe,cAAA,EACf,KAAA,GAAO,YAAA,0BACN,oBAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/babel",
|
|
3
|
-
"version": "8.4.
|
|
3
|
+
"version": "8.4.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A Babel plugin for Intlayer that transforms declaration files and provides internationalization features during the build process according to the Intlayer configuration.",
|
|
6
6
|
"keywords": [
|
|
@@ -81,12 +81,12 @@
|
|
|
81
81
|
"@babel/plugin-syntax-jsx": "7.28.6",
|
|
82
82
|
"@babel/traverse": "7.29.0",
|
|
83
83
|
"@babel/types": "7.29.0",
|
|
84
|
-
"@intlayer/chokidar": "8.4.
|
|
85
|
-
"@intlayer/config": "8.4.
|
|
86
|
-
"@intlayer/core": "8.4.
|
|
87
|
-
"@intlayer/dictionaries-entry": "8.4.
|
|
88
|
-
"@intlayer/types": "8.4.
|
|
89
|
-
"@intlayer/unmerged-dictionaries-entry": "8.4.
|
|
84
|
+
"@intlayer/chokidar": "8.4.3",
|
|
85
|
+
"@intlayer/config": "8.4.3",
|
|
86
|
+
"@intlayer/core": "8.4.3",
|
|
87
|
+
"@intlayer/dictionaries-entry": "8.4.3",
|
|
88
|
+
"@intlayer/types": "8.4.3",
|
|
89
|
+
"@intlayer/unmerged-dictionaries-entry": "8.4.3",
|
|
90
90
|
"@types/babel__core": "7.20.5",
|
|
91
91
|
"@types/babel__generator": "7.27.0",
|
|
92
92
|
"@types/babel__traverse": "7.28.0"
|
|
@@ -104,8 +104,8 @@
|
|
|
104
104
|
"vitest": "4.1.0"
|
|
105
105
|
},
|
|
106
106
|
"peerDependencies": {
|
|
107
|
-
"@intlayer/svelte-compiler": "8.4.
|
|
108
|
-
"@intlayer/vue-compiler": "8.4.
|
|
107
|
+
"@intlayer/svelte-compiler": "8.4.3",
|
|
108
|
+
"@intlayer/vue-compiler": "8.4.3"
|
|
109
109
|
},
|
|
110
110
|
"peerDependenciesMeta": {
|
|
111
111
|
"@intlayer/svelte-compiler": {
|