vite-intlayer 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.
@@ -1,2 +1,2 @@
1
- import{readFile as e}from"node:fs/promises";import{dirname as t,relative as n}from"node:path";import{detectPackageName as r,extractContent as i,getExtractPluginOptions as a,writeContentHelper as o}from"@intlayer/babel";import{ANSIColors as s,colorize as c,colorizeKey as l,colorizeNumber as u,colorizePath as d,getAppLogger as f,x as p}from"@intlayer/config/logger";import{getConfiguration as m}from"@intlayer/config/node";const h=h=>{let g,_,v,y=``,b=[],x=null,S=new Map,C=new Map,w=e=>{let t=S.get(e);return t?Date.now()-t<500:!1},T=e=>{S.set(e,Date.now());let t=Date.now();for(let[e,n]of S.entries())t-n>500*2&&S.delete(e)},E=e=>JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]])),D=(e,t)=>{let n=E(t);return C.get(e)===n?!1:(C.set(e,n),!0)},O=async()=>{b=_.filesList},k=async e=>{g=m(h?.configOptions),_=a(g,e),v=f(g),await O()},A=async e=>{let t=e.env?.DEV?`dev`:`build`;y=e.root,await k(t)},j=async()=>{try{v(`Intlayer compiler initialized`,{level:`info`})}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to prepare Intlayer: ${e}`,{level:`error`})}},M=async()=>{x&&await x},N=async({file:t,server:r,modules:i})=>{if(b.some(e=>e===t)){if(w(t)){v(`${c(`Compiler:`,s.GREY_DARK)} Skipping re-transform of ${d(n(y,t))} (recently processed)`,{level:`info`,isVerbose:!0});return}T(t);for(let e of i)r.moduleGraph.invalidateModule(e);try{await I(await e(t,`utf-8`),t)}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to re-transform ${t}: ${e}`,{level:`error`})}r.ws.send({type:`full-reload`})}},P=async e=>{let{dictionaryKey:t,content:n,filePath:r}=e;if(!D(t,n)){v(`${c(`Compiler:`,s.GREY_DARK)} Skipping dictionary ${l(t)} (content unchanged)`,{level:`info`,isVerbose:!0});return}try{await o(n,t,r,g)}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to write/build dictionary for ${l(t)}: ${e}`,{level:`error`})}},F=async e=>{let t=Object.keys(e.content);return v(`${c(`Compiler:`,s.GREY_DARK)} Extracted ${u(t.length)} content keys from ${d(n(y,e.filePath))}`,{level:`info`}),x=(x??Promise.resolve()).then(()=>P(e)).catch(e=>{v(`${c(`Compiler:`,s.GREY_DARK)} Error in dictionary write chain: ${e}`,{level:`error`})}),x},I=async(e,a)=>{if(!_.enabled||a.includes(`?`))return;let o=a;if(b.includes(o)){v(`${c(`Compiler:`,s.GREY_DARK)} Transforming ${d(n(y,o))}`,{level:`info`,isVerbose:!0});try{let n=await i(o,r(t(o)),{configuration:g,code:e,onExtract:async({key:e,content:t})=>{await F({dictionaryKey:e,content:t,filePath:o,locale:g.internationalization.defaultLocale})}});if(x&&await x,n?.transformedCode)return{code:n.transformedCode}}catch(e){v([`Failed to transform ${d(n(y,o))}:`,e],{level:`error`})}}};return{name:`vite-intlayer-compiler`,enforce:`pre`,configResolved:A,buildStart:j,buildEnd:M,handleHotUpdate:N,transform:I,apply:(e,t)=>(g||=m(h?.configOptions),v||=f(g),g.compiler.output?(_||=a(g,t.command),_.enabled):(v(`${p} No output configuration found. Add a ${c(`compiler.output`,s.BLUE)} in your configuration.`,{level:`error`}),!1))}};export{h as intlayerCompiler};
1
+ import{readFile as e}from"node:fs/promises";import{dirname as t,relative as n}from"node:path";import{detectPackageName as r,extractContent as i,getExtractPluginOptions as a,writeContentHelper as o}from"@intlayer/babel";import*as s from"@intlayer/config/colors";import{colorize as c,colorizeKey as l,colorizeNumber as u,colorizePath as d,getAppLogger as f,x as p}from"@intlayer/config/logger";import{getConfiguration as m}from"@intlayer/config/node";const h=h=>{let g,_,v,y=``,b=[],x=null,S=new Map,C=new Map,w=e=>{let t=S.get(e);return t?Date.now()-t<500:!1},T=e=>{S.set(e,Date.now());let t=Date.now();for(let[e,n]of S.entries())t-n>500*2&&S.delete(e)},E=e=>JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]])),D=(e,t)=>{let n=E(t);return C.get(e)===n?!1:(C.set(e,n),!0)},O=async()=>{b=_.filesList},k=async e=>{g=m(h?.configOptions),_=a(g,e),v=f(g),await O()},A=async e=>{let t=e.env?.DEV?`dev`:`build`;y=e.root,await k(t)},j=async()=>{try{v(`Intlayer compiler initialized`,{level:`info`})}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to prepare Intlayer: ${e}`,{level:`error`})}},M=async()=>{x&&await x},N=async({file:t,server:r,modules:i})=>{if(b.some(e=>e===t)){if(w(t)){v(`${c(`Compiler:`,s.GREY_DARK)} Skipping re-transform of ${d(n(y,t))} (recently processed)`,{level:`info`,isVerbose:!0});return}T(t);for(let e of i)r.moduleGraph.invalidateModule(e);try{await I(await e(t,`utf-8`),t)}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to re-transform ${t}: ${e}`,{level:`error`})}r.ws.send({type:`full-reload`})}},P=async e=>{let{dictionaryKey:t,content:n,filePath:r}=e;if(!D(t,n)){v(`${c(`Compiler:`,s.GREY_DARK)} Skipping dictionary ${l(t)} (content unchanged)`,{level:`info`,isVerbose:!0});return}try{await o(n,t,r,g)}catch(e){v(`${c(`Compiler:`,s.GREY_DARK)} Failed to write/build dictionary for ${l(t)}: ${e}`,{level:`error`})}},F=async e=>{let t=Object.keys(e.content);return v(`${c(`Compiler:`,s.GREY_DARK)} Extracted ${u(t.length)} content keys from ${d(n(y,e.filePath))}`,{level:`info`}),x=(x??Promise.resolve()).then(()=>P(e)).catch(e=>{v(`${c(`Compiler:`,s.GREY_DARK)} Error in dictionary write chain: ${e}`,{level:`error`})}),x},I=async(e,a)=>{if(!_.enabled||a.includes(`?`))return;let o=a;if(b.includes(o)){v(`${c(`Compiler:`,s.GREY_DARK)} Transforming ${d(n(y,o))}`,{level:`info`,isVerbose:!0});try{let n=await i(o,r(t(o)),{configuration:g,code:e,onExtract:async({key:e,content:t})=>{await F({dictionaryKey:e,content:t,filePath:o,locale:g.internationalization.defaultLocale})}});if(x&&await x,n?.transformedCode)return{code:n.transformedCode}}catch(e){v([`Failed to transform ${d(n(y,o))}:`,e],{level:`error`})}}};return{name:`vite-intlayer-compiler`,enforce:`pre`,configResolved:A,buildStart:j,buildEnd:M,handleHotUpdate:N,transform:I,apply:(e,t)=>(g||=m(h?.configOptions),v||=f(g),g.compiler.output?(_||=a(g,t.command),_.enabled):(v(`${p} No output configuration found. Add a ${c(`compiler.output`,s.BLUE)} in your configuration.`,{level:`error`}),!1))}};export{h as intlayerCompiler};
2
2
  //# sourceMappingURL=IntlayerCompilerPlugin.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"IntlayerCompilerPlugin.mjs","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n type CompilerMode,\n detectPackageName,\n type ExtractPluginOptions,\n type ExtractResult,\n extractContent,\n getExtractPluginOptions,\n writeContentHelper,\n} from '@intlayer/babel';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { CompilerConfig, IntlayerConfig } from '@intlayer/types/config';\nimport type { HmrContext, PluginOption } from 'vite';\n\n/**\n * Options for initializing the compiler\n */\nexport type IntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Create an IntlayerCompiler - A Vite-compatible compiler plugin for Intlayer\n *\n * This autonomous compiler handles:\n * - Configuration loading and management\n * - Hot Module Replacement (HMR) for content changes\n * - File transformation with content extraction\n * - Dictionary persistence and building\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { intlayerCompiler } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerCompiler()],\n * });\n * ```\n */\nexport const intlayerCompiler = (\n options?: IntlayerCompilerOptions\n): PluginOption => {\n let config: IntlayerConfig;\n let compilerConfig: ExtractPluginOptions;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let filesList: string[] = [];\n\n // Promise to track dictionary writing (for synchronization)\n let pendingDictionaryWrite: Promise<void> | null = null;\n\n // Track recently processed files to prevent infinite loops\n // Key: file path, Value: timestamp of last processing\n const recentlyProcessedFiles = new Map<string, number>();\n // Track recently written dictionaries to prevent duplicate writes\n // Key: dictionary key, Value: hash of content that was written\n const recentDictionaryContent = new Map<string, string>();\n // Debounce window in milliseconds - skip re-processing files within this window\n const DEBOUNCE_MS = 500;\n\n /**\n * Check if a file was recently processed (within debounce window)\n * and should be skipped to prevent infinite loops\n */\n const wasRecentlyProcessed = (filePath: string): boolean => {\n const lastProcessed = recentlyProcessedFiles.get(filePath);\n if (!lastProcessed) return false;\n\n const now = Date.now();\n return now - lastProcessed < DEBOUNCE_MS;\n };\n\n /**\n * Mark a file as recently processed\n */\n const markAsProcessed = (filePath: string): void => {\n recentlyProcessedFiles.set(filePath, Date.now());\n\n // Clean up old entries to prevent memory leaks\n const now = Date.now();\n for (const [path, timestamp] of recentlyProcessedFiles.entries()) {\n if (now - timestamp > DEBOUNCE_MS * 2) {\n recentlyProcessedFiles.delete(path);\n }\n }\n };\n\n /**\n * Create a simple hash of content for comparison\n * Used to detect if dictionary content has actually changed\n */\n const hashContent = (content: Record<string, string>): string =>\n JSON.stringify(\n Object.keys(content)\n .sort()\n .map((key) => [key, content[key]])\n );\n\n /**\n * Check if dictionary content has changed since last write\n */\n const hasDictionaryContentChanged = (\n dictionaryKey: string,\n content: Record<string, string>\n ): boolean => {\n const newHash = hashContent(content);\n const previousHash = recentDictionaryContent.get(dictionaryKey);\n\n if (previousHash === newHash) {\n return false;\n }\n\n // Update the stored hash\n recentDictionaryContent.set(dictionaryKey, newHash);\n return true;\n };\n\n /**\n * Build the list of files to transform based on configuration patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n filesList = compilerConfig.filesList;\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n config = getConfiguration(options?.configOptions);\n\n compilerConfig = getExtractPluginOptions(config, compilerMode);\n\n logger = getAppLogger(config);\n\n // Build files list for transformation\n await buildFilesListFn();\n };\n\n /**\n * Vite hook: configResolved\n * Called when Vite config is resolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n }): Promise<void> => {\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n\n await init(compilerMode);\n };\n\n /**\n * Build start hook - no longer needs to prepare dictionaries\n * The compiler is now autonomous and extracts content inline\n */\n const buildStart = async (): Promise<void> => {\n // Bootstrap dictionaries and types before build starts\n // This ensures existing dictionaries are available for resolution\n try {\n logger('Intlayer compiler initialized', {\n level: 'info',\n });\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to prepare Intlayer: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Build end hook - wait for any pending dictionary writes\n */\n const buildEnd = async (): Promise<void> => {\n // Wait for any pending dictionary writes to complete\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n };\n\n /**\n * Vite hook: handleHotUpdate\n * Handles HMR for content files - invalidates cache and triggers re-transform\n */\n const handleHotUpdate = async ({\n file,\n server,\n modules,\n }: HmrContext): Promise<void> => {\n // Check if this is a file we should transform\n const isTransformableFile = filesList.some((fileEl) => fileEl === file);\n\n if (isTransformableFile) {\n // Check if this file was recently processed to prevent infinite loops\n // When a component is transformed, it writes a dictionary, which triggers HMR,\n // which would re-transform the component - this debounce prevents that loop\n if (wasRecentlyProcessed(file)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping re-transform of ${colorizePath(relative(projectRoot, file))} (recently processed)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return undefined;\n }\n\n // Mark file as being processed before transformation\n markAsProcessed(file);\n\n // Invalidate all affected modules to ensure re-transform\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Force re-transform by reading and processing the file\n // This ensures content extraction happens on every file change\n try {\n const code = await readFile(file, 'utf-8');\n\n // Trigger the transform manually to extract content\n await transformHandler(code, file);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to re-transform ${file}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n // Trigger full reload for content changes\n server.ws.send({ type: 'full-reload' });\n }\n };\n\n /**\n * Write and build one or more dictionaries based on extracted content.\n * Leverages shared logic from @intlayer/babel.\n */\n const writeAndBuildDictionary = async (\n result: ExtractResult\n ): Promise<void> => {\n const { dictionaryKey, content, filePath: sourceFilePath } = result;\n\n // Skip if content hasn't changed - prevents infinite loops during HMR\n if (!hasDictionaryContentChanged(dictionaryKey, content)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping dictionary ${colorizeKey(dictionaryKey)} (content unchanged)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return;\n }\n\n try {\n await writeContentHelper(content, dictionaryKey, sourceFilePath!, config);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to write/build dictionary for ${colorizeKey(dictionaryKey)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Callback for when content is extracted from a file\n * Immediately writes and builds the dictionary\n */\n const handleExtractedContent = async (\n result: ExtractResult\n ): Promise<void> => {\n const contentKeys = Object.keys(result.content);\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted ${colorizeNumber(contentKeys.length)} content keys from ${colorizePath(relative(projectRoot, result.filePath))}`,\n {\n level: 'info',\n }\n );\n\n // Chain the write operation to ensure sequential writes\n pendingDictionaryWrite = (pendingDictionaryWrite ?? Promise.resolve())\n .then(() => writeAndBuildDictionary(result))\n .catch((error) => {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Error in dictionary write chain: ${error}`,\n {\n level: 'error',\n }\n );\n });\n\n return pendingDictionaryWrite;\n };\n\n /**\n * Transform a file using the appropriate extraction plugin based on file type.\n * Delegates to `extractContent` from `@intlayer/babel` which handles\n * JS/TS/JSX/TSX/Vue/Svelte extraction and transformation.\n */\n const transformHandler = async (code: string, id: string) => {\n // Only transform if compiler is enabled\n if (!compilerConfig.enabled) {\n return undefined;\n }\n\n // Skip virtual modules (query strings indicate compiled/virtual modules)\n // e.g., App.svelte?svelte&type=style, Component.vue?vue&type=script\n if (id.includes('?')) {\n return undefined;\n }\n\n const filename = id;\n\n if (!filesList.includes(filename)) {\n return undefined;\n }\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Transforming ${colorizePath(relative(projectRoot, filename))}`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n\n try {\n const packageName = detectPackageName(dirname(filename));\n\n const result = await extractContent(filename, packageName, {\n configuration: config,\n code,\n // Dictionary writing is handled by handleExtractedContent below.\n onExtract: async ({ key, content }) => {\n await handleExtractedContent({\n dictionaryKey: key,\n content,\n filePath: filename,\n locale: config.internationalization.defaultLocale,\n });\n },\n });\n\n // Wait for the dictionary to be written before returning\n // This ensures the dictionary exists before any subsequent processing\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n\n if (result?.transformedCode) {\n return {\n code: result.transformedCode,\n };\n }\n } catch (error) {\n logger(\n [\n `Failed to transform ${colorizePath(relative(projectRoot, filename))}:`,\n error,\n ],\n {\n level: 'error',\n }\n );\n }\n\n return undefined;\n };\n\n return {\n name: 'vite-intlayer-compiler',\n enforce: 'pre',\n configResolved,\n buildStart,\n buildEnd,\n handleHotUpdate,\n transform: transformHandler,\n apply: (_viteConfig, env) => {\n // Initialize config if not already done\n if (!config) {\n config = getConfiguration(options?.configOptions);\n }\n if (!logger) {\n logger = getAppLogger(config);\n }\n\n if (!config.compiler.output) {\n logger(\n `${x} No output configuration found. Add a ${colorize('compiler.output', ANSIColors.BLUE)} in your configuration.`,\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n if (!compilerConfig) {\n compilerConfig = getExtractPluginOptions(config, env.command);\n }\n\n return compilerConfig.enabled;\n },\n };\n};\n"],"mappings":"uaA8DA,MAAa,EACX,GACiB,CACjB,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAsB,EAAE,CAGxB,EAA+C,KAI7C,EAAyB,IAAI,IAG7B,EAA0B,IAAI,IAQ9B,EAAwB,GAA8B,CAC1D,IAAM,EAAgB,EAAuB,IAAI,EAAS,CAI1D,OAHK,EAEO,KAAK,KAAK,CACT,EAAgB,IAHF,IASvB,EAAmB,GAA2B,CAClD,EAAuB,IAAI,EAAU,KAAK,KAAK,CAAC,CAGhD,IAAM,EAAM,KAAK,KAAK,CACtB,IAAK,GAAM,CAAC,EAAM,KAAc,EAAuB,SAAS,CAC1D,EAAM,EAAY,IAAc,GAClC,EAAuB,OAAO,EAAK,EASnC,EAAe,GACnB,KAAK,UACH,OAAO,KAAK,EAAQ,CACjB,MAAM,CACN,IAAK,GAAQ,CAAC,EAAK,EAAQ,GAAK,CAAC,CACrC,CAKG,GACJ,EACA,IACY,CACZ,IAAM,EAAU,EAAY,EAAQ,CASpC,OARqB,EAAwB,IAAI,EAAc,GAE1C,EACZ,IAIT,EAAwB,IAAI,EAAe,EAAQ,CAC5C,KAMH,EAAmB,SAA2B,CAClD,EAAY,EAAe,WAMvB,EAAO,KAAO,IAA8C,CAChE,EAAS,EAAiB,GAAS,cAAc,CAEjD,EAAiB,EAAwB,EAAQ,EAAa,CAE9D,EAAS,EAAa,EAAO,CAG7B,MAAM,GAAkB,EAOpB,EAAiB,KAAO,IAGT,CACnB,IAAM,EAA6B,EAAW,KAAK,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1B,EAAO,SAAS,QAWrB,AACE,IAAiB,EAAwB,EAAQ,EAAI,QAAQ,CAGxD,EAAe,UAdpB,EACE,GAAG,EAAE,wCAAwC,EAAS,kBAAmB,EAAW,KAAK,CAAC,yBAC1F,CACE,MAAO,QACR,CACF,CAEM,KASZ"}
1
+ {"version":3,"file":"IntlayerCompilerPlugin.mjs","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n type CompilerMode,\n detectPackageName,\n type ExtractPluginOptions,\n type ExtractResult,\n extractContent,\n getExtractPluginOptions,\n writeContentHelper,\n} from '@intlayer/babel';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { CompilerConfig, IntlayerConfig } from '@intlayer/types/config';\nimport type { HmrContext, PluginOption } from 'vite';\n\n/**\n * Options for initializing the compiler\n */\nexport type IntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Create an IntlayerCompiler - A Vite-compatible compiler plugin for Intlayer\n *\n * This autonomous compiler handles:\n * - Configuration loading and management\n * - Hot Module Replacement (HMR) for content changes\n * - File transformation with content extraction\n * - Dictionary persistence and building\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { intlayerCompiler } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerCompiler()],\n * });\n * ```\n */\nexport const intlayerCompiler = (\n options?: IntlayerCompilerOptions\n): PluginOption => {\n let config: IntlayerConfig;\n let compilerConfig: ExtractPluginOptions;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let filesList: string[] = [];\n\n // Promise to track dictionary writing (for synchronization)\n let pendingDictionaryWrite: Promise<void> | null = null;\n\n // Track recently processed files to prevent infinite loops\n // Key: file path, Value: timestamp of last processing\n const recentlyProcessedFiles = new Map<string, number>();\n // Track recently written dictionaries to prevent duplicate writes\n // Key: dictionary key, Value: hash of content that was written\n const recentDictionaryContent = new Map<string, string>();\n // Debounce window in milliseconds - skip re-processing files within this window\n const DEBOUNCE_MS = 500;\n\n /**\n * Check if a file was recently processed (within debounce window)\n * and should be skipped to prevent infinite loops\n */\n const wasRecentlyProcessed = (filePath: string): boolean => {\n const lastProcessed = recentlyProcessedFiles.get(filePath);\n if (!lastProcessed) return false;\n\n const now = Date.now();\n return now - lastProcessed < DEBOUNCE_MS;\n };\n\n /**\n * Mark a file as recently processed\n */\n const markAsProcessed = (filePath: string): void => {\n recentlyProcessedFiles.set(filePath, Date.now());\n\n // Clean up old entries to prevent memory leaks\n const now = Date.now();\n for (const [path, timestamp] of recentlyProcessedFiles.entries()) {\n if (now - timestamp > DEBOUNCE_MS * 2) {\n recentlyProcessedFiles.delete(path);\n }\n }\n };\n\n /**\n * Create a simple hash of content for comparison\n * Used to detect if dictionary content has actually changed\n */\n const hashContent = (content: Record<string, string>): string =>\n JSON.stringify(\n Object.keys(content)\n .sort()\n .map((key) => [key, content[key]])\n );\n\n /**\n * Check if dictionary content has changed since last write\n */\n const hasDictionaryContentChanged = (\n dictionaryKey: string,\n content: Record<string, string>\n ): boolean => {\n const newHash = hashContent(content);\n const previousHash = recentDictionaryContent.get(dictionaryKey);\n\n if (previousHash === newHash) {\n return false;\n }\n\n // Update the stored hash\n recentDictionaryContent.set(dictionaryKey, newHash);\n return true;\n };\n\n /**\n * Build the list of files to transform based on configuration patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n filesList = compilerConfig.filesList;\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n config = getConfiguration(options?.configOptions);\n\n compilerConfig = getExtractPluginOptions(config, compilerMode);\n\n logger = getAppLogger(config);\n\n // Build files list for transformation\n await buildFilesListFn();\n };\n\n /**\n * Vite hook: configResolved\n * Called when Vite config is resolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n }): Promise<void> => {\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n\n await init(compilerMode);\n };\n\n /**\n * Build start hook - no longer needs to prepare dictionaries\n * The compiler is now autonomous and extracts content inline\n */\n const buildStart = async (): Promise<void> => {\n // Bootstrap dictionaries and types before build starts\n // This ensures existing dictionaries are available for resolution\n try {\n logger('Intlayer compiler initialized', {\n level: 'info',\n });\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to prepare Intlayer: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Build end hook - wait for any pending dictionary writes\n */\n const buildEnd = async (): Promise<void> => {\n // Wait for any pending dictionary writes to complete\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n };\n\n /**\n * Vite hook: handleHotUpdate\n * Handles HMR for content files - invalidates cache and triggers re-transform\n */\n const handleHotUpdate = async ({\n file,\n server,\n modules,\n }: HmrContext): Promise<void> => {\n // Check if this is a file we should transform\n const isTransformableFile = filesList.some((fileEl) => fileEl === file);\n\n if (isTransformableFile) {\n // Check if this file was recently processed to prevent infinite loops\n // When a component is transformed, it writes a dictionary, which triggers HMR,\n // which would re-transform the component - this debounce prevents that loop\n if (wasRecentlyProcessed(file)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping re-transform of ${colorizePath(relative(projectRoot, file))} (recently processed)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return undefined;\n }\n\n // Mark file as being processed before transformation\n markAsProcessed(file);\n\n // Invalidate all affected modules to ensure re-transform\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Force re-transform by reading and processing the file\n // This ensures content extraction happens on every file change\n try {\n const code = await readFile(file, 'utf-8');\n\n // Trigger the transform manually to extract content\n await transformHandler(code, file);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to re-transform ${file}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n // Trigger full reload for content changes\n server.ws.send({ type: 'full-reload' });\n }\n };\n\n /**\n * Write and build one or more dictionaries based on extracted content.\n * Leverages shared logic from @intlayer/babel.\n */\n const writeAndBuildDictionary = async (\n result: ExtractResult\n ): Promise<void> => {\n const { dictionaryKey, content, filePath: sourceFilePath } = result;\n\n // Skip if content hasn't changed - prevents infinite loops during HMR\n if (!hasDictionaryContentChanged(dictionaryKey, content)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping dictionary ${colorizeKey(dictionaryKey)} (content unchanged)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return;\n }\n\n try {\n await writeContentHelper(content, dictionaryKey, sourceFilePath!, config);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to write/build dictionary for ${colorizeKey(dictionaryKey)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Callback for when content is extracted from a file\n * Immediately writes and builds the dictionary\n */\n const handleExtractedContent = async (\n result: ExtractResult\n ): Promise<void> => {\n const contentKeys = Object.keys(result.content);\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted ${colorizeNumber(contentKeys.length)} content keys from ${colorizePath(relative(projectRoot, result.filePath))}`,\n {\n level: 'info',\n }\n );\n\n // Chain the write operation to ensure sequential writes\n pendingDictionaryWrite = (pendingDictionaryWrite ?? Promise.resolve())\n .then(() => writeAndBuildDictionary(result))\n .catch((error) => {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Error in dictionary write chain: ${error}`,\n {\n level: 'error',\n }\n );\n });\n\n return pendingDictionaryWrite;\n };\n\n /**\n * Transform a file using the appropriate extraction plugin based on file type.\n * Delegates to `extractContent` from `@intlayer/babel` which handles\n * JS/TS/JSX/TSX/Vue/Svelte extraction and transformation.\n */\n const transformHandler = async (code: string, id: string) => {\n // Only transform if compiler is enabled\n if (!compilerConfig.enabled) {\n return undefined;\n }\n\n // Skip virtual modules (query strings indicate compiled/virtual modules)\n // e.g., App.svelte?svelte&type=style, Component.vue?vue&type=script\n if (id.includes('?')) {\n return undefined;\n }\n\n const filename = id;\n\n if (!filesList.includes(filename)) {\n return undefined;\n }\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Transforming ${colorizePath(relative(projectRoot, filename))}`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n\n try {\n const packageName = detectPackageName(dirname(filename));\n\n const result = await extractContent(filename, packageName, {\n configuration: config,\n code,\n // Dictionary writing is handled by handleExtractedContent below.\n onExtract: async ({ key, content }) => {\n await handleExtractedContent({\n dictionaryKey: key,\n content,\n filePath: filename,\n locale: config.internationalization.defaultLocale,\n });\n },\n });\n\n // Wait for the dictionary to be written before returning\n // This ensures the dictionary exists before any subsequent processing\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n\n if (result?.transformedCode) {\n return {\n code: result.transformedCode,\n };\n }\n } catch (error) {\n logger(\n [\n `Failed to transform ${colorizePath(relative(projectRoot, filename))}:`,\n error,\n ],\n {\n level: 'error',\n }\n );\n }\n\n return undefined;\n };\n\n return {\n name: 'vite-intlayer-compiler',\n enforce: 'pre',\n configResolved,\n buildStart,\n buildEnd,\n handleHotUpdate,\n transform: transformHandler,\n apply: (_viteConfig, env) => {\n // Initialize config if not already done\n if (!config) {\n config = getConfiguration(options?.configOptions);\n }\n if (!logger) {\n logger = getAppLogger(config);\n }\n\n if (!config.compiler.output) {\n logger(\n `${x} No output configuration found. Add a ${colorize('compiler.output', ANSIColors.BLUE)} in your configuration.`,\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n if (!compilerConfig) {\n compilerConfig =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syncPlugin.mjs";import{join as t}from"node:path";import{intlayerOptimizeBabelPlugin as n}from"@intlayer/babel";import{getAppLogger as r}from"@intlayer/config/logger";import{transformSync as i}from"@babel/core";import{buildComponentFilesList as a,runOnce as o}from"@intlayer/chokidar/utils";import{DefaultValues as s}from"@intlayer/config/client";import{getDictionaries as c}from"@intlayer/dictionaries-entry";const l=/\b(use|get)Intlayer\b/,u=async u=>{try{let d=r(u),{optimize:f}=u.build,p=u.build.importMode??u.dictionary?.importMode,{dictionariesDir:m,dynamicDictionariesDir:h,unmergedDictionariesDir:g,fetchDictionariesDir:_,mainDir:v}=u.system,{baseDir:y}=u.system,b=t(v,`dictionaries.mjs`),x=t(v,`unmerged_dictionaries.mjs`),S=t(v,`dynamic_dictionaries.mjs`),C=[...a(u),b,x],w=c(u),T={};return Object.values(w).forEach(e=>{T[e.key]=e.importMode??p??s.Dictionary.IMPORT_MODE}),[e(u,C),{name:`vite-intlayer-babel-transform`,enforce:`post`,apply:(e,n)=>{let r=n.command===`build`,i=f===void 0&&r||f===!0;return i&&o(t(y,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>d(`Build optimization enabled`),{cacheTimeoutMs:1e3*10}),i},transform(e,t){let r=t.split(`?`,1)[0];if(!C.includes(r))return null;let a=[b,x].includes(r);if(!(l.test(e)||a))return null;let o=i(e,{filename:r,plugins:[[n,{optimize:f,dictionariesDir:m,dictionariesEntryPath:b,unmergedDictionariesEntryPath:x,unmergedDictionariesDir:g,dynamicDictionariesDir:h,dynamicDictionariesEntryPath:S,fetchDictionariesDir:_,importMode:p,filesList:C,replaceDictionaryEntry:!0,dictionaryModeMap:T}]],parserOpts:{sourceType:`module`,allowImportExportEverywhere:!0,plugins:[`typescript`,`jsx`,`decorators-legacy`,`classProperties`,`objectRestSpread`,`asyncGenerators`,`functionBind`,`exportDefaultFrom`,`exportNamespaceFrom`,`dynamicImport`,`nullishCoalescingOperator`,`optionalChaining`]}});if(o?.code)return{code:o.code,map:o.map}}}]}catch(e){return console.warn(`Failed to transform with Babel plugin:`,e),[]}};export{u as intlayerOptimize};
1
+ import{intlayerVueAsyncPlugin as e}from"./intlayerVueAsyncPlugin.mjs";import{join as t}from"node:path";import{intlayerOptimizeBabelPlugin as n}from"@intlayer/babel";import{getAppLogger as r}from"@intlayer/config/logger";import{transformSync as i}from"@babel/core";import{buildComponentFilesList as a,runOnce as o}from"@intlayer/chokidar/utils";import{IMPORT_MODE as s}from"@intlayer/config/defaultValues";import{getDictionaries as c}from"@intlayer/dictionaries-entry";const l=/\b(use|get)Intlayer\b/,u=async u=>{try{let d=r(u),{optimize:f}=u.build,p=u.build.importMode??u.dictionary?.importMode,{dictionariesDir:m,dynamicDictionariesDir:h,unmergedDictionariesDir:g,fetchDictionariesDir:_,mainDir:v}=u.system,{baseDir:y}=u.system,b=t(v,`dictionaries.mjs`),x=t(v,`unmerged_dictionaries.mjs`),S=t(v,`dynamic_dictionaries.mjs`),C=[...a(u),b,x],w=c(u),T={};return Object.values(w).forEach(e=>{T[e.key]=e.importMode??p??s}),[e(u,C),{name:`vite-intlayer-babel-transform`,enforce:`post`,apply:(e,n)=>{let r=n.command===`build`,i=f===void 0&&r||f===!0;return i&&o(t(y,`.intlayer`,`cache`,`intlayer-prune-plugin-enabled.lock`),()=>d(`Build optimization enabled`),{cacheTimeoutMs:1e3*10}),i},transform(e,t){let r=t.split(`?`,1)[0];if(!C.includes(r))return null;let a=[b,x].includes(r);if(!(l.test(e)||a))return null;let o=i(e,{filename:r,plugins:[[n,{optimize:f,dictionariesDir:m,dictionariesEntryPath:b,unmergedDictionariesEntryPath:x,unmergedDictionariesDir:g,dynamicDictionariesDir:h,dynamicDictionariesEntryPath:S,fetchDictionariesDir:_,importMode:p,filesList:C,replaceDictionaryEntry:!0,dictionaryModeMap:T}]],parserOpts:{sourceType:`module`,allowImportExportEverywhere:!0,plugins:[`typescript`,`jsx`,`decorators-legacy`,`classProperties`,`objectRestSpread`,`asyncGenerators`,`functionBind`,`exportDefaultFrom`,`exportNamespaceFrom`,`dynamicImport`,`nullishCoalescingOperator`,`optionalChaining`]}});if(o?.code)return{code:o.code,map:o.map}}}]}catch(e){return console.warn(`Failed to transform with Babel plugin:`,e),[]}};export{u as intlayerOptimize};
2
2
  //# sourceMappingURL=intlayerOptimizePlugin.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerOptimizePlugin.mjs","names":[],"sources":["../../src/intlayerOptimizePlugin.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { transformSync } from '@babel/core';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport { DefaultValues } from '@intlayer/config/client';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { PluginOption } from 'vite';\nimport { intlayerVueAsyncPlugin } from './intlayerVueAsyncPlugin';\n\nconst INTLAYER_USAGE_REGEX = /\\b(use|get)Intlayer\\b/;\n\nexport const intlayerOptimize = async (\n intlayerConfig: IntlayerConfig\n): Promise<PluginOption[]> => {\n try {\n const logger = getAppLogger(intlayerConfig);\n\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const baseFilesList = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...baseFilesList,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> =\n {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ??\n importMode ??\n DefaultValues.Dictionary.IMPORT_MODE;\n });\n\n return [\n intlayerVueAsyncPlugin(intlayerConfig, filesList),\n {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\n apply: (_config, env) => {\n // Only apply babel plugin if optimize is enabled\n\n const isBuild = env.command === 'build';\n const isEnabled =\n (optimize === undefined && isBuild) || optimize === true;\n\n if (isEnabled) {\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prune-plugin-enabled.lock'\n ),\n () => logger('Build optimization enabled'),\n {\n cacheTimeoutMs: 1000 * 10, // 10 seconds\n }\n );\n }\n\n return isEnabled;\n },\n transform(code, id) {\n /**\n * Transform file as\n * .../HelloWorld.vue?vue&type=script&setup=true&lang.ts\n * Into\n * .../HelloWorld.vue\n *\n * Prevention for virtual file\n */\n const filename = id.split('?', 1)[0];\n\n if (!filesList.includes(filename)) return null;\n\n const isDictionaryEntry = [\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ].includes(filename);\n\n const isUsingIntlayer = INTLAYER_USAGE_REGEX.test(code);\n\n const shouldTransform = isUsingIntlayer || isDictionaryEntry;\n\n if (!shouldTransform) return null;\n\n const result = transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n },\n },\n ];\n } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return [];\n }\n};\n"],"mappings":"+cAYA,MAAM,EAAuB,wBAEhB,EAAmB,KAC9B,IAC4B,CAC5B,GAAI,CACF,IAAM,EAAS,EAAa,EAAe,CAErC,CAAE,YAAa,EAAe,MAC9B,EACJ,EAAe,MAAM,YAAc,EAAe,YAAY,WAE1D,CACJ,kBACA,yBACA,0BACA,uBACA,WACE,EAAe,OACb,CAAE,WAAY,EAAe,OAE7B,EAAwB,EAAK,EAAS,mBAAmB,CACzD,EAAgC,EACpC,EACA,4BACD,CACK,EAA+B,EACnC,EACA,2BACD,CAIK,EAAY,CAChB,GAHoB,EAAwB,EAAe,CAI3D,EACA,EACD,CAEK,EAAe,EAAgB,EAAe,CAE9C,EACJ,EAAE,CASJ,OAPC,OAAO,OAAO,EAAa,CAAkB,QAAS,GAAe,CACpE,EAAkB,EAAW,KAC3B,EAAW,YACX,GACA,EAAc,WAAW,aAC3B,CAEK,CACL,EAAuB,EAAgB,EAAU,CACjD,CACE,KAAM,gCACN,QAAS,OACT,OAAQ,EAAS,IAAQ,CAGvB,IAAM,EAAU,EAAI,UAAY,QAC1B,EACH,IAAa,IAAA,IAAa,GAAY,IAAa,GAiBtD,OAfI,GACF,EACE,EACE,EACA,YACA,QACA,qCACD,KACK,EAAO,6BAA6B,CAC1C,CACE,eAAgB,IAAO,GACxB,CACF,CAGI,GAET,UAAU,EAAM,EAAI,CASlB,IAAM,EAAW,EAAG,MAAM,IAAK,EAAE,CAAC,GAElC,GAAI,CAAC,EAAU,SAAS,EAAS,CAAE,OAAO,KAE1C,IAAM,EAAoB,CACxB,EACA,EACD,CAAC,SAAS,EAAS,CAMpB,GAAI,EAJoB,EAAqB,KAAK,EAAK,EAEZ,GAErB,OAAO,KAE7B,IAAM,EAAS,EAAc,EAAM,CACjC,WACA,QAAS,CACP,CACE,EACA,CACE,WACA,kBACA,wBACA,gCACA,0BACA,yBACA,+BACA,uBACA,aACA,YACA,uBAAwB,GACxB,oBACD,CACF,CACF,CACD,WAAY,CACV,WAAY,SACZ,4BAA6B,GAC7B,QAAS,CACP,aACA,MACA,oBACA,kBACA,mBACA,kBACA,eACA,oBACA,sBACA,gBACA,4BACA,mBACD,CACF,CACF,CAAC,CAEF,GAAI,GAAQ,KACV,MAAO,CACL,KAAM,EAAO,KACb,IAAK,EAAO,IACb,EAGN,CACF,OACM,EAAO,CAGd,OAFA,QAAQ,KAAK,yCAA0C,EAAM,CAEtD,EAAE"}
1
+ {"version":3,"file":"intlayerOptimizePlugin.mjs","names":[],"sources":["../../src/intlayerOptimizePlugin.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { transformSync } from '@babel/core';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { PluginOption } from 'vite';\nimport { intlayerVueAsyncPlugin } from './intlayerVueAsyncPlugin';\n\nconst INTLAYER_USAGE_REGEX = /\\b(use|get)Intlayer\\b/;\n\nexport const intlayerOptimize = async (\n intlayerConfig: IntlayerConfig\n): Promise<PluginOption[]> => {\n try {\n const logger = getAppLogger(intlayerConfig);\n\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const baseFilesList = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...baseFilesList,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> =\n {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return [\n intlayerVueAsyncPlugin(intlayerConfig, filesList),\n {\n name: 'vite-intlayer-babel-transform',\n enforce: 'post', // Run after other transformations as vue\n apply: (_config, env) => {\n // Only apply babel plugin if optimize is enabled\n\n const isBuild = env.command === 'build';\n const isEnabled =\n (optimize === undefined && isBuild) || optimize === true;\n\n if (isEnabled) {\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prune-plugin-enabled.lock'\n ),\n () => logger('Build optimization enabled'),\n {\n cacheTimeoutMs: 1000 * 10, // 10 seconds\n }\n );\n }\n\n return isEnabled;\n },\n transform(code, id) {\n /**\n * Transform file as\n * .../HelloWorld.vue?vue&type=script&setup=true&lang.ts\n * Into\n * .../HelloWorld.vue\n *\n * Prevention for virtual file\n */\n const filename = id.split('?', 1)[0];\n\n if (!filesList.includes(filename)) return null;\n\n const isDictionaryEntry = [\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ].includes(filename);\n\n const isUsingIntlayer = INTLAYER_USAGE_REGEX.test(code);\n\n const shouldTransform = isUsingIntlayer || isDictionaryEntry;\n\n if (!shouldTransform) return null;\n\n const result = transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n optimize,\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n },\n },\n ];\n } catch (error) {\n console.warn('Failed to transform with Babel plugin:', error);\n\n return [];\n }\n};\n"],"mappings":"odAYA,MAAM,EAAuB,wBAEhB,EAAmB,KAC9B,IAC4B,CAC5B,GAAI,CACF,IAAM,EAAS,EAAa,EAAe,CAErC,CAAE,YAAa,EAAe,MAC9B,EACJ,EAAe,MAAM,YAAc,EAAe,YAAY,WAE1D,CACJ,kBACA,yBACA,0BACA,uBACA,WACE,EAAe,OACb,CAAE,WAAY,EAAe,OAE7B,EAAwB,EAAK,EAAS,mBAAmB,CACzD,EAAgC,EACpC,EACA,4BACD,CACK,EAA+B,EACnC,EACA,2BACD,CAIK,EAAY,CAChB,GAHoB,EAAwB,EAAe,CAI3D,EACA,EACD,CAEK,EAAe,EAAgB,EAAe,CAE9C,EACJ,EAAE,CAOJ,OALC,OAAO,OAAO,EAAa,CAAkB,QAAS,GAAe,CACpE,EAAkB,EAAW,KAC3B,EAAW,YAAc,GAAc,GACzC,CAEK,CACL,EAAuB,EAAgB,EAAU,CACjD,CACE,KAAM,gCACN,QAAS,OACT,OAAQ,EAAS,IAAQ,CAGvB,IAAM,EAAU,EAAI,UAAY,QAC1B,EACH,IAAa,IAAA,IAAa,GAAY,IAAa,GAiBtD,OAfI,GACF,EACE,EACE,EACA,YACA,QACA,qCACD,KACK,EAAO,6BAA6B,CAC1C,CACE,eAAgB,IAAO,GACxB,CACF,CAGI,GAET,UAAU,EAAM,EAAI,CASlB,IAAM,EAAW,EAAG,MAAM,IAAK,EAAE,CAAC,GAElC,GAAI,CAAC,EAAU,SAAS,EAAS,CAAE,OAAO,KAE1C,IAAM,EAAoB,CACxB,EACA,EACD,CAAC,SAAS,EAAS,CAMpB,GAAI,EAJoB,EAAqB,KAAK,EAAK,EAEZ,GAErB,OAAO,KAE7B,IAAM,EAAS,EAAc,EAAM,CACjC,WACA,QAAS,CACP,CACE,EACA,CACE,WACA,kBACA,wBACA,gCACA,0BACA,yBACA,+BACA,uBACA,aACA,YACA,uBAAwB,GACxB,oBACD,CACF,CACF,CACD,WAAY,CACV,WAAY,SACZ,4BAA6B,GAC7B,QAAS,CACP,aACA,MACA,oBACA,kBACA,mBACA,kBACA,eACA,oBACA,sBACA,gBACA,4BACA,mBACD,CACF,CACF,CAAC,CAEF,GAAI,GAAQ,KACV,MAAO,CACL,KAAM,EAAO,KACb,IAAK,EAAO,IACb,EAGN,CACF,OACM,EAAO,CAGd,OAFA,QAAQ,KAAK,yCAA0C,EAAM,CAEtD,EAAE"}
@@ -1,2 +1,2 @@
1
- import{getConfiguration as e}from"@intlayer/config/node";import{DefaultValues as t}from"@intlayer/config/client";import{parse as n}from"node:url";import{getCanonicalPath as r,getLocalizedPath as i,getRewriteRules as a,localeDetector as o}from"@intlayer/core/localization";import{getCookie as s,getLocaleFromStorage as c,setLocaleInStorage as l}from"@intlayer/core/utils";const u=(u,d)=>{let{internationalization:f,routing:p}=e(u),{locales:m,defaultLocale:h}=f,{basePath:g=``,mode:_=t.Routing.ROUTING_MODE,rewrite:v}=p,y=new Map,b=_===`no-prefix`||_===`search-params`,x=_===`prefix-all`,S=a(v,`url`),C=e=>c({getCookie:t=>s(t,e.headers.cookie)}),w=(e,t)=>{if(_!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},T=e=>{let t=e.split(`/`).filter(Boolean)[0];if(t&&m.includes(t))return t},E=(e,t,n,r)=>{if(r){let i=(y.get(r)||0)+1;if(y.set(r,i),i>10)return console.error(`[REDIRECT LOOP DETECTED!]`,{originalUrl:r,redirectCount:i,lastRedirectTo:t,reason:n}),e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Redirect loop detected: ${i} redirects from ${r}`)}return e.writeHead(301,{Location:t}),e.end()},D=(e,t,n,r)=>{e.url!==n&&(e.url=n),r&&l(r,{setHeader:(n,r)=>{t.setHeader(n,r),e.headers[n]=r}})},O=(e,t,n)=>{let r=t.startsWith(`/${e}`)?t.slice(`/${e}`.length):t,i=g.startsWith(`/`)?g:`/${g}`,a=i.endsWith(`/`)?i.slice(0,-1):i;if(_===`no-prefix`||_===`search-params`)return n?`${r||`/`}${n}`:r||`/`;let o=`${a}${t.startsWith(`/${e}`)?t:`/${e}${t===`/`?``:t}`}`;return!x&&e===h&&(o=`${a}${r||`/`}`),n&&(o+=n),o},k=({req:e,res:t,next:n,originalPath:i,searchParams:a,storageLocale:s,originalUrl:c})=>{let l=T(i),u=s??h;if(s||(u=o(e.headers,m,h)),l){let e=r(i.slice(`/${l}`.length)||`/`,l,S),n=w(a,l);return E(t,n?`${e}${n}`:`${e}${a??``}`,void 0,c)}let d=r(i,u,S);if(_===`search-params`){if(new URLSearchParams(a??``).get(`locale`)===u)return D(e,t,`${`/${u}${d===`/`?``:d}`}${a??``}`,u),n();let r=w(a,u);return E(t,r?`${i}${r}`:`${i}${a??``}`,void 0,c)}let f=`/${u}${d===`/`?``:d}`,p=w(a,u);return D(e,t,p?`${f}${p}`:`${f}${a??``}`,u),n()},A=({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,storageLocale:o,originalUrl:s})=>{if(!a){j({req:e,res:t,next:n,originalPath:r,searchParams:i,storageLocale:o,originalUrl:s});return}M({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,originalUrl:s})},j=({req:e,res:t,next:n,originalPath:a,searchParams:s,storageLocale:c,originalUrl:l})=>{let u=c??o(e.headers,m,h);m.includes(u)||(u=h);let d=r(a,u,S),f=i(d,u,S),p=typeof f==`string`?f:f.path,g=w(s,u),_=O(u,p,g);return x||u!==h?E(t,_,void 0,l):(D(e,t,`/${u}${d===`/`?``:d}${s}`,u),n())},M=({req:e,res:t,next:n,originalPath:i,searchParams:a,pathLocale:o,originalUrl:s})=>{let c=i.slice(`/${o}`.length),l=r(c,o,S);if(l!==c){let e=`/${o}${l===`/`?``:l}`;return E(t,a?`${e}${a}`:e,void 0,s)}N({req:e,res:t,next:n,searchParams:a,pathLocale:o,canonicalPath:l,originalUrl:s})},N=({req:e,res:t,next:n,searchParams:r,pathLocale:a,canonicalPath:o,originalUrl:s})=>{if(!x&&a===h){let e=i(o,a,S),n=typeof e==`string`?e:e.path,c=g.startsWith(`/`)?g:`/${g}`,l=c.endsWith(`/`)?c.slice(0,-1):c,u=n;return u.startsWith(`/`)&&(u=u.slice(1)),E(t,`${l}/${u}`.replace(/\/+/g,`/`)+(r??``),void 0,s)}let c=`/${a}${o===`/`?``:o}`;return D(e,t,r?`${c}${r}`:c,a),n()};return{name:`vite-intlayer-middleware-plugin`,configureServer:e=>{e.middlewares.use((e,t,r)=>{if((d?.ignore?.(e)??!1)||e.url?.startsWith(`/node_modules`)||e.url?.startsWith(`/@`)||e.url?.startsWith(`/_`)||e.url?.split(`?`)[0].match(/\.[a-z]+$/i))return r();let i=n(e.url??`/`,!0),a=i.pathname??`/`,o=i.search??``,s=T(a),c=C(e),l=s&&m.includes(s)?s:c,u=e.url;if(b){k({req:e,res:t,next:r,originalPath:a,searchParams:o,storageLocale:l,originalUrl:u});return}A({req:e,res:t,next:r,originalPath:a,searchParams:o,pathLocale:s,storageLocale:l,originalUrl:u})}),y.size>100&&y.clear()}}},d=u,f=u;export{f as intLayerMiddlewarePlugin,d as intlayerMiddleware,u as intlayerProxy};
1
+ import{getConfiguration as e}from"@intlayer/config/node";import{ROUTING_MODE as t}from"@intlayer/config/defaultValues";import{parse as n}from"node:url";import{getCanonicalPath as r,getLocalizedPath as i,getRewriteRules as a,localeDetector as o}from"@intlayer/core/localization";import{getCookie as s,getLocaleFromStorage as c,setLocaleInStorage as l}from"@intlayer/core/utils";const u=(u,d)=>{let{internationalization:f,routing:p}=e(u),{locales:m,defaultLocale:h}=f,{basePath:g=``,mode:_=t,rewrite:v}=p,y=new Map,b=_===`no-prefix`||_===`search-params`,x=_===`prefix-all`,S=a(v,`url`),C=e=>c({getCookie:t=>s(t,e.headers.cookie)}),w=(e,t)=>{if(_!==`search-params`)return e;let n=new URLSearchParams(e??``);return n.set(`locale`,t),`?${n.toString()}`},T=e=>{let t=e.split(`/`).filter(Boolean)[0];if(t&&m.includes(t))return t},E=(e,t,n,r)=>{if(r){let i=(y.get(r)||0)+1;if(y.set(r,i),i>10)return console.error(`[REDIRECT LOOP DETECTED!]`,{originalUrl:r,redirectCount:i,lastRedirectTo:t,reason:n}),e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Redirect loop detected: ${i} redirects from ${r}`)}return e.writeHead(301,{Location:t}),e.end()},D=(e,t,n,r)=>{e.url!==n&&(e.url=n),r&&l(r,{setHeader:(n,r)=>{t.setHeader(n,r),e.headers[n]=r}})},O=(e,t,n)=>{let r=t.startsWith(`/${e}`)?t.slice(`/${e}`.length):t,i=g.startsWith(`/`)?g:`/${g}`,a=i.endsWith(`/`)?i.slice(0,-1):i;if(_===`no-prefix`||_===`search-params`)return n?`${r||`/`}${n}`:r||`/`;let o=`${a}${t.startsWith(`/${e}`)?t:`/${e}${t===`/`?``:t}`}`;return!x&&e===h&&(o=`${a}${r||`/`}`),n&&(o+=n),o},k=({req:e,res:t,next:n,originalPath:i,searchParams:a,storageLocale:s,originalUrl:c})=>{let l=T(i),u=s??h;if(s||(u=o(e.headers,m,h)),l){let e=r(i.slice(`/${l}`.length)||`/`,l,S),n=w(a,l);return E(t,n?`${e}${n}`:`${e}${a??``}`,void 0,c)}let d=r(i,u,S);if(_===`search-params`){if(new URLSearchParams(a??``).get(`locale`)===u)return D(e,t,`${`/${u}${d===`/`?``:d}`}${a??``}`,u),n();let r=w(a,u);return E(t,r?`${i}${r}`:`${i}${a??``}`,void 0,c)}let f=`/${u}${d===`/`?``:d}`,p=w(a,u);return D(e,t,p?`${f}${p}`:`${f}${a??``}`,u),n()},A=({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,storageLocale:o,originalUrl:s})=>{if(!a){j({req:e,res:t,next:n,originalPath:r,searchParams:i,storageLocale:o,originalUrl:s});return}M({req:e,res:t,next:n,originalPath:r,searchParams:i,pathLocale:a,originalUrl:s})},j=({req:e,res:t,next:n,originalPath:a,searchParams:s,storageLocale:c,originalUrl:l})=>{let u=c??o(e.headers,m,h);m.includes(u)||(u=h);let d=r(a,u,S),f=i(d,u,S),p=typeof f==`string`?f:f.path,g=w(s,u),_=O(u,p,g);return x||u!==h?E(t,_,void 0,l):(D(e,t,`/${u}${d===`/`?``:d}${s}`,u),n())},M=({req:e,res:t,next:n,originalPath:i,searchParams:a,pathLocale:o,originalUrl:s})=>{let c=i.slice(`/${o}`.length),l=r(c,o,S);if(l!==c){let e=`/${o}${l===`/`?``:l}`;return E(t,a?`${e}${a}`:e,void 0,s)}N({req:e,res:t,next:n,searchParams:a,pathLocale:o,canonicalPath:l,originalUrl:s})},N=({req:e,res:t,next:n,searchParams:r,pathLocale:a,canonicalPath:o,originalUrl:s})=>{if(!x&&a===h){let e=i(o,a,S),n=typeof e==`string`?e:e.path,c=g.startsWith(`/`)?g:`/${g}`,l=c.endsWith(`/`)?c.slice(0,-1):c,u=n;return u.startsWith(`/`)&&(u=u.slice(1)),E(t,`${l}/${u}`.replace(/\/+/g,`/`)+(r??``),void 0,s)}let c=`/${a}${o===`/`?``:o}`;return D(e,t,r?`${c}${r}`:c,a),n()};return{name:`vite-intlayer-middleware-plugin`,configureServer:e=>{e.middlewares.use((e,t,r)=>{if((d?.ignore?.(e)??!1)||e.url?.startsWith(`/node_modules`)||e.url?.startsWith(`/@`)||e.url?.startsWith(`/_`)||e.url?.split(`?`)[0].match(/\.[a-z]+$/i))return r();let i=n(e.url??`/`,!0),a=i.pathname??`/`,o=i.search??``,s=T(a),c=C(e),l=s&&m.includes(s)?s:c,u=e.url;if(b){k({req:e,res:t,next:r,originalPath:a,searchParams:o,storageLocale:l,originalUrl:u});return}A({req:e,res:t,next:r,originalPath:a,searchParams:o,pathLocale:s,storageLocale:l,originalUrl:u})}),y.size>100&&y.clear()}}},d=u,f=u;export{f as intLayerMiddlewarePlugin,d as intlayerMiddleware,u as intlayerProxy};
2
2
  //# sourceMappingURL=intlayerProxyPlugin.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n localeDetector,\n} from '@intlayer/core/localization';\nimport {\n getCookie,\n getLocaleFromStorage,\n setLocaleInStorage,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\ntype IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n};\n\n/**\n * Vite plugin that provides a development middleware for locale-based routing.\n *\n * This plugin mimics the behavior of the Intlayer middleware in Next.js,\n * handling locale detection, redirects, and rewrites during development.\n *\n * @param configOptions - Optional configuration for Intlayer.\n * @param options - Plugin-specific options, like ignoring certain paths.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n */\nexport const intlayerProxy = (\n configOptions?: GetConfigurationOptions,\n options?: IntlayerProxyPluginOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const {\n basePath = '',\n mode = DefaultValues.Routing.ROUTING_MODE,\n rewrite,\n } = routing;\n\n // Track redirect counts per request to detect loops\n const redirectCounts = new Map<string, number>();\n const MAX_REDIRECTS = 10;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => getCookie(name, req.headers.cookie),\n });\n return locale;\n };\n\n /**\n * Appends locale to search params when routing mode is 'search-params'.\n */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n reason?: string,\n originalUrl?: string\n ) => {\n // Track redirect count to detect loops\n if (originalUrl) {\n const count = (redirectCounts.get(originalUrl) || 0) + 1;\n redirectCounts.set(originalUrl, count);\n\n if (count > MAX_REDIRECTS) {\n console.error('[REDIRECT LOOP DETECTED!]', {\n originalUrl,\n redirectCount: count,\n lastRedirectTo: newUrl,\n reason,\n });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${count} redirects from ${originalUrl}`\n );\n }\n }\n\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n if (req.url !== newUrl) {\n req.url = newUrl;\n }\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n req.headers[name] = value;\n },\n });\n }\n };\n\n /**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath.slice(`/${locale}`.length)\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix' || mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix || '/'}${search}`\n : pathWithoutPrefix || '/';\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath === '/' ? '' : currentPath}`;\n\n let newPath = `${normalizedBasePath}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix || '/'}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n };\n\n /* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n /**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\n const handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n const pathLocale = getPathLocale(originalPath);\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${searchParams ?? ''}`;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n };\n\n /**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\n const handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n });\n };\n\n /**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\n const handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, targetLocalizedPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath, undefined, originalUrl);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place using canonical path for framework matching.\n // searchParams MUST be preserved here — dropping them causes the framework (e.g. TanStack Start) to\n // see a URL with no search params, trigger a validateSearch normalisation redirect to the prefixed URL\n // (e.g. /en?page=1&...), which the middleware then strips back to /?..., creating an infinite loop.\n rewriteUrl(\n req,\n res,\n `/${locale}${canonicalPath === '/' ? '' : canonicalPath}${searchParams}`,\n locale\n );\n return next();\n };\n\n /**\n * Handles requests where the locale prefix is present in the pathname.\n */\n const handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n originalUrl?: string;\n }) => {\n const rawPath = originalPath.slice(`/${pathLocale}`.length);\n\n // Identify the Canonical Path (Internal path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // Redirect Pretty URL to Canonical URL (Vite Specific Requirement)\n // If request is /fr/a-props (Pretty) -> Redirect to /fr/about (Canonical)\n // This allows the SPA router to handle the route naturally.\n if (canonicalPath !== rawPath) {\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const redirectPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n });\n };\n\n /**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\n const handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n searchParams: string;\n pathLocale: Locale;\n canonicalPath: string;\n originalUrl?: string;\n }) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const cleanBasePath = basePath.startsWith('/')\n ? basePath\n : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${normalizedBasePath}/${finalPath}`.replace(\n /\\/+/g,\n '/'\n );\n\n return redirectUrl(\n res,\n fullPath + (searchParams ?? ''),\n undefined,\n originalUrl\n );\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite to canonical internally\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const newPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n };\n\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // Bypass assets and special Vite endpoints\n if (\n // Custom ignore function\n (options?.ignore?.(req) ?? false) ||\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/_') ||\n /**\n * ./myFile.js\n */\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // Check if there's a locale prefix in the path FIRST\n const pathLocale = getPathLocale(originalPath);\n\n // Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // CRITICAL FIX: If there's a valid pathLocale, it takes precedence over storage\n // This prevents race conditions when cookies are stale during locale switches\n const effectiveStorageLocale =\n pathLocale && supportedLocales.includes(pathLocale)\n ? pathLocale\n : storageLocale;\n\n // Store original URL for redirect tracking\n const originalUrl = req.url;\n\n // If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n return;\n }\n\n // Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n });\n\n // Clean up redirect counts periodically (every 100 requests)\n if (redirectCounts.size > 100) {\n redirectCounts.clear();\n }\n },\n };\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = intlayerProxy;\n"],"mappings":"mXA0DA,MAAa,GACX,EACA,IACW,CAGX,GAAM,CAA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,EACf,cACD,CAAC,EACF,CAGE,EAAe,KAAO,KACxB,EAAe,OAAO,EAG3B,EAeU,EAAqB,EAcrB,EAA2B"}
1
+ {"version":3,"file":"intlayerProxyPlugin.mjs","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { parse } from 'node:url';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getCanonicalPath,\n getLocalizedPath,\n getRewriteRules,\n localeDetector,\n} from '@intlayer/core/localization';\nimport {\n getCookie,\n getLocaleFromStorage,\n setLocaleInStorage,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\ntype IntlayerProxyPluginOptions = {\n /**\n * A function that allows you to ignore specific requests from the intlayer proxy.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * plugins: [ intlayerProxyPlugin({ ignore: (req) => req.url?.startsWith('/api') }) ],\n * });\n * ```\n *\n * @param req - The incoming request.\n * @returns A boolean value indicating whether to ignore the request.\n */\n ignore?: (req: IncomingMessage) => boolean | undefined;\n};\n\n/**\n * Vite plugin that provides a development middleware for locale-based routing.\n *\n * This plugin mimics the behavior of the Intlayer middleware in Next.js,\n * handling locale detection, redirects, and rewrites during development.\n *\n * @param configOptions - Optional configuration for Intlayer.\n * @param options - Plugin-specific options, like ignoring certain paths.\n * @returns A Vite plugin.\n *\n * @example\n * ```ts\n * import { intlayerProxy } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerProxy()],\n * });\n * ```\n */\nexport const intlayerProxy = (\n configOptions?: GetConfigurationOptions,\n options?: IntlayerProxyPluginOptions\n): Plugin => {\n const intlayerConfig = getConfiguration(configOptions);\n\n const { internationalization, routing } = intlayerConfig;\n const { locales: supportedLocales, defaultLocale } = internationalization;\n\n const { basePath = '', mode = ROUTING_MODE, rewrite } = routing;\n\n // Track redirect counts per request to detect loops\n const redirectCounts = new Map<string, number>();\n const MAX_REDIRECTS = 10;\n\n // Derived flags from routing.mode\n const noPrefix = mode === 'no-prefix' || mode === 'search-params';\n const prefixDefault = mode === 'prefix-all';\n\n const rewriteRules = getRewriteRules(rewrite, 'url');\n\n /* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n /**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\n const getStorageLocale = (req: IncomingMessage): Locale | undefined => {\n const locale = getLocaleFromStorage({\n getCookie: (name: string) => getCookie(name, req.headers.cookie),\n });\n return locale;\n };\n\n /**\n * Appends locale to search params when routing mode is 'search-params'.\n */\n const appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n ): string | undefined => {\n if (mode !== 'search-params') return search;\n\n const params = new URLSearchParams(search ?? '');\n\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locale)) {\n return firstSegment as Locale;\n }\n return undefined;\n };\n\n /**\n * Writes a 301 redirect response with the given new URL.\n */\n const redirectUrl = (\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n reason?: string,\n originalUrl?: string\n ) => {\n // Track redirect count to detect loops\n if (originalUrl) {\n const count = (redirectCounts.get(originalUrl) || 0) + 1;\n redirectCounts.set(originalUrl, count);\n\n if (count > MAX_REDIRECTS) {\n console.error('[REDIRECT LOOP DETECTED!]', {\n originalUrl,\n redirectCount: count,\n lastRedirectTo: newUrl,\n reason,\n });\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n return res.end(\n `Redirect loop detected: ${count} redirects from ${originalUrl}`\n );\n }\n }\n\n res.writeHead(301, { Location: newUrl });\n return res.end();\n };\n\n /**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\n const rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locale\n ) => {\n if (req.url !== newUrl) {\n req.url = newUrl;\n }\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale) {\n setLocaleInStorage(locale, {\n setHeader: (name: string, value: string) => {\n res.setHeader(name, value);\n req.headers[name] = value;\n },\n });\n }\n };\n\n /**\n * Constructs a new path string, optionally including a locale prefix, basePath, and search parameters.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n * - search: (e.g., '?foo=bar')\n */\n const constructPath = (\n locale: Locale,\n currentPath: string,\n search?: string\n ) => {\n // Strip any incoming locale prefix if present\n const pathWithoutPrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath.slice(`/${locale}`.length)\n : currentPath;\n\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n // In 'search-params' and 'no-prefix' modes, do not prefix the path with the locale\n if (mode === 'no-prefix' || mode === 'search-params') {\n const newPath = search\n ? `${pathWithoutPrefix || '/'}${search}`\n : pathWithoutPrefix || '/';\n return newPath;\n }\n\n // Check if path already starts with locale to avoid double-prefixing\n const pathWithLocalePrefix = currentPath.startsWith(`/${locale}`)\n ? currentPath\n : `/${locale}${currentPath === '/' ? '' : currentPath}`;\n\n let newPath = `${normalizedBasePath}${pathWithLocalePrefix}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${pathWithoutPrefix || '/'}`;\n }\n\n // Append search parameters if provided\n if (search) {\n newPath += search;\n }\n\n return newPath;\n };\n\n /* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n /**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or search params if desired.\n */\n const handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n const pathLocale = getPathLocale(originalPath);\n // Determine the best locale\n let locale = storageLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no storage locale\n if (!storageLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locale;\n }\n\n if (pathLocale) {\n const pathWithoutLocale =\n originalPath.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(searchParams, pathLocale);\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${searchParams ?? ''}`;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // In search-params mode, we need to redirect to add the locale search param\n if (mode === 'search-params') {\n // Check if locale search param already exists and matches the detected locale\n const existingSearchParams = new URLSearchParams(searchParams ?? '');\n const existingLocale = existingSearchParams.get('locale');\n\n // If the existing locale matches the detected locale, no redirect needed\n if (existingLocale === locale) {\n // For internal routing, we need to add the locale prefix so the framework can match [locale] param\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const rewritePath = `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n return next();\n }\n\n // Locale param missing or doesn't match - redirect to add/update it\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const redirectPath = search\n ? `${originalPath}${search}`\n : `${originalPath}${searchParams ?? ''}`;\n\n // Redirect to add/update the locale search param (URL changes in browser)\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // For no-prefix mode (not search-params), add locale prefix internally for routing\n const internalPath = `/${locale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n\n // Add search params if needed\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${searchParams ?? ''}`;\n\n // Rewrite internally (URL stays the same in browser, but internally routes to /[locale]/path)\n rewriteUrl(req, res, rewritePath, locale);\n\n return next();\n };\n\n /**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle storage mismatch or default locale special cases\n */\n const handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale?: Locale;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle it\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n });\n };\n\n /**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from storage / headers / default, then either redirect or rewrite.\n */\n const handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n storageLocale?: Locale;\n originalUrl?: string;\n }) => {\n // 1. Choose the best locale\n let locale = (storageLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locale;\n\n // If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(originalPath, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct new path - preserving original search params\n const search = appendLocaleSearchIfNeeded(searchParams, locale);\n const newPath = constructPath(locale, targetLocalizedPath, search);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath, undefined, originalUrl);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place using canonical path for framework matching.\n // searchParams MUST be preserved here — dropping them causes the framework (e.g. TanStack Start) to\n // see a URL with no search params, trigger a validateSearch normalisation redirect to the prefixed URL\n // (e.g. /en?page=1&...), which the middleware then strips back to /?..., creating an infinite loop.\n rewriteUrl(\n req,\n res,\n `/${locale}${canonicalPath === '/' ? '' : canonicalPath}${searchParams}`,\n locale\n );\n return next();\n };\n\n /**\n * Handles requests where the locale prefix is present in the pathname.\n */\n const handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n searchParams: string;\n pathLocale: Locale;\n originalUrl?: string;\n }) => {\n const rawPath = originalPath.slice(`/${pathLocale}`.length);\n\n // Identify the Canonical Path (Internal path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // Redirect Pretty URL to Canonical URL (Vite Specific Requirement)\n // If request is /fr/a-props (Pretty) -> Redirect to /fr/about (Canonical)\n // This allows the SPA router to handle the route naturally.\n if (canonicalPath !== rawPath) {\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const redirectPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n return redirectUrl(res, redirectPath, undefined, originalUrl);\n }\n\n // In prefix modes, respect the URL path locale\n // The path locale takes precedence, and we'll update storage to match\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n });\n };\n\n /**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\n const handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n searchParams,\n pathLocale,\n canonicalPath,\n originalUrl,\n }: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n searchParams: string;\n pathLocale: Locale;\n canonicalPath: string;\n originalUrl?: string;\n }) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n // Construct path without prefix\n const cleanBasePath = basePath.startsWith('/')\n ? basePath\n : `/${basePath}`;\n const normalizedBasePath = cleanBasePath.endsWith('/')\n ? cleanBasePath.slice(0, -1)\n : cleanBasePath;\n\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${normalizedBasePath}/${finalPath}`.replace(\n /\\/+/g,\n '/'\n );\n\n return redirectUrl(\n res,\n fullPath + (searchParams ?? ''),\n undefined,\n originalUrl\n );\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite to canonical internally\n const internalUrl = `/${pathLocale}${\n canonicalPath === '/' ? '' : canonicalPath\n }`;\n const newPath = searchParams\n ? `${internalUrl}${searchParams}`\n : internalUrl;\n\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n };\n\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // Bypass assets and special Vite endpoints\n if (\n // Custom ignore function\n (options?.ignore?.(req) ?? false) ||\n req.url?.startsWith('/node_modules') ||\n /**\n * /^@vite/ # HMR client and helpers\n * /^@fs/ # file-system import serving\n * /^@id/ # virtual module ids\n * /^@tanstack/start-router-manifest # Tanstack Start Router manifest\n */\n req.url?.startsWith('/@') ||\n /**\n * /^__vite_ping$ # health ping\n * /^__open-in-editor$\n * /^__manifest$ # Remix/RR7 lazyRouteDiscovery\n */\n req.url?.startsWith('/_') ||\n /**\n * ./myFile.js\n */\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n const searchParams = parsedUrl.search ?? '';\n\n // Check if there's a locale prefix in the path FIRST\n const pathLocale = getPathLocale(originalPath);\n\n // Attempt to read the locale from storage (cookies, localStorage, etc.)\n const storageLocale = getStorageLocale(req);\n\n // CRITICAL FIX: If there's a valid pathLocale, it takes precedence over storage\n // This prevents race conditions when cookies are stale during locale switches\n const effectiveStorageLocale =\n pathLocale && supportedLocales.includes(pathLocale)\n ? pathLocale\n : storageLocale;\n\n // Store original URL for redirect tracking\n const originalUrl = req.url;\n\n // If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n return;\n }\n\n // Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n searchParams,\n pathLocale,\n storageLocale: effectiveStorageLocale,\n originalUrl,\n });\n });\n\n // Clean up redirect counts periodically (every 100 requests)\n if (redirectCounts.size > 100) {\n redirectCounts.clear();\n }\n },\n };\n};\n\n/**\n * @deprecated Rename to intlayerProxy instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerProxy;\n\n/**\n * @deprecated Rename to intlayerProxy instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = intlayerProxy;\n"],"mappings":"yXA0DA,MAAa,GACX,EACA,IACW,CAGX,GAAM,CAAE,uBAAsB,WAFP,EAAiB,EAAc,CAGhD,CAAE,QAAS,EAAkB,iBAAkB,EAE/C,CAAE,WAAW,GAAI,OAAO,EAAc,WAAY,EAGlD,EAAiB,IAAI,IAIrB,EAAW,IAAS,aAAe,IAAS,gBAC5C,EAAgB,IAAS,aAEzB,EAAe,EAAgB,EAAS,MAAM,CAU9C,EAAoB,GACT,EAAqB,CAClC,UAAY,GAAiB,EAAU,EAAM,EAAI,QAAQ,OAAO,CACjE,CAAC,CAOE,GACJ,EACA,IACuB,CACvB,GAAI,IAAS,gBAAiB,OAAO,EAErC,IAAM,EAAS,IAAI,gBAAgB,GAAU,GAAG,CAIhD,OAFA,EAAO,IAAI,SAAU,EAAO,CAErB,IAAI,EAAO,UAAU,IAMxB,EAAiB,GAAyC,CAI9D,IAAM,EADW,EAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CACtB,GAC9B,GAAI,GAAgB,EAAiB,SAAS,EA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"version":3,"file":"intlayerProxyPlugin.d.ts","names":[],"sources":["../../src/intlayerProxyPlugin.ts"],"mappings":";;;;;KAsBK,0BAAA;;AAFuC;;;;;;;;;AAsC5C;;;EAtBE,MAAA,IAAU,GAAA,EAAK,eAAA;AAAA;;;;;;;;;;;AAqoBjB;;;;;;;;;cA/mBa,aAAA,GACX,aAAA,GAAgB,uBAAA,EAChB,OAAA,GAAU,0BAAA,KACT,MAAA;;;;;;AA0nBH;;;;;;;cAda,kBAAA,GAAkB,aAAA,GA9mBb,uBAAA,EAAuB,OAAA,GAC7B,0BAAA,KACT,MAAA;;;;;;;;;;;;;cA0nBU,wBAAA,GAAwB,aAAA,GA5nBnB,uBAAA,EAAuB,OAAA,GAC7B,0BAAA,KACT,MAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-intlayer",
3
- "version": "8.4.2",
3
+ "version": "8.4.3",
4
4
  "private": false,
5
5
  "description": "A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration",
6
6
  "keywords": [
@@ -77,13 +77,13 @@
77
77
  },
78
78
  "dependencies": {
79
79
  "@babel/core": "7.29.0",
80
- "@intlayer/babel": "8.4.2",
81
- "@intlayer/chokidar": "8.4.2",
82
- "@intlayer/config": "8.4.2",
83
- "@intlayer/core": "8.4.2",
84
- "@intlayer/dictionaries-entry": "8.4.2",
85
- "@intlayer/types": "8.4.2",
86
- "intlayer": "8.4.2"
80
+ "@intlayer/babel": "8.4.3",
81
+ "@intlayer/chokidar": "8.4.3",
82
+ "@intlayer/config": "8.4.3",
83
+ "@intlayer/core": "8.4.3",
84
+ "@intlayer/dictionaries-entry": "8.4.3",
85
+ "@intlayer/types": "8.4.3",
86
+ "intlayer": "8.4.3"
87
87
  },
88
88
  "devDependencies": {
89
89
  "@types/babel__core": "7.20.5",