import type { Plugin } from 'vite'; import { promises as fs } from 'fs'; import { resolve } from 'path'; import { config as loadEnv } from 'dotenv'; interface WixBuildOptions { environment?: 'local' | 'production'; isFakeServer?: boolean; charLimit?: number; } interface PluginContext { minifyJS: (code: string) => string; injectEnvironmentVariables: (sourceCode: string) => string; } export function viteWixBuildPlugin(options: WixBuildOptions = {}): Plugin { const { environment = 'production', isFakeServer = false, charLimit = 15000 } = options; return { name: 'vite-wix-build', configResolved(config) { // Load environment-specific config const envFile = resolve(config.root, `.env.${environment}`); try { loadEnv({ path: envFile }); console.log(`šŸ“‹ Loaded Vite config: ${envFile}`); } catch { console.warn(`āš ļø Environment file not found: ${envFile}`); } }, generateBundle: { order: 'post', async handler() { console.log('šŸ”Ø Generating Wix custom code with Vite...'); try { // Use the existing build logic but integrate with Vite const buildSuffix = isFakeServer ? `${environment}-fake` : environment; // Read the source files const srcFile = resolve(this.meta.watchMode ? 'src' : '', 'wix-demo.js'); const sharedDemoPath = resolve(this.meta.watchMode ? 'src' : '', 'shared-demo.js'); let sourceCode = await fs.readFile(srcFile, 'utf8'); let wixOptimizedShared = ''; // Extract shared components (same logic as build-wix.js) if (await fs.access(sharedDemoPath).then(() => true).catch(() => false)) { const sharedCode = await fs.readFile(sharedDemoPath, 'utf8'); const cssGeneratorMatch = sharedCode.match(/export function generateBuzzTrailCSS\\(sectionId\\) \\{[\\s\\S]*?\\n\\}/); const htmlGeneratorMatch = sharedCode.match(/export function generateBuzzTrailHTML\\(videoUrl, buttonText\\) \\{[\\s\\S]*?\\n\\}/); const autoJoinMatch = sharedCode.match(/export function addAutoJoinParams\\(roomUrl\\) \\{[\\s\\S]*?\\n\\}/); const redirectMatch = sharedCode.match(/export function redirectAfterConversation\\(\\) \\{[\\s\\S]*?\\n\\}/); const envConfigsMatch = sharedCode.match(/export const ENV_CONFIGS = \\{[\\s\\S]*?\\};/); const getEnvConfigMatch = sharedCode.match(/export function getEnvironmentConfig\\(\\) \\{[\\s\\S]*?\\n\\}/); const buttonStylesMatch = sharedCode.match(/export const BUTTON_STYLES = \\{[\\s\\S]*?\\};/); if (cssGeneratorMatch && htmlGeneratorMatch && autoJoinMatch && redirectMatch && envConfigsMatch && getEnvConfigMatch && buttonStylesMatch) { wixOptimizedShared = `// Shared functions from shared-demo.js - SINGLE SOURCE OF TRUTH ${buttonStylesMatch[0].replace('export ', '')} ${envConfigsMatch[0].replace('export ', '')} ${getEnvConfigMatch[0].replace('export ', '')} ${cssGeneratorMatch[0].replace('export ', '')} ${htmlGeneratorMatch[0].replace('export ', '')} ${autoJoinMatch[0].replace('export ', '')} ${redirectMatch[0].replace('export ', '')}`; } } // Combine shared code with source code sourceCode = wixOptimizedShared + '\\n\\n' + sourceCode; // Inject environment variables sourceCode = this.injectEnvironmentVariables(sourceCode); // Minify const minifiedJS = this.minifyJS(sourceCode); // Wrap in HTML const finalCode = ` `; // Create development version const devCode = ` `; // Emit the files this.emitFile({ type: 'asset', fileName: `wix-custom-code-${buildSuffix}.html`, source: finalCode }); this.emitFile({ type: 'asset', fileName: `wix-custom-code-dev-${buildSuffix}.html`, source: devCode }); // Character analysis const charCount = finalCode.length; const percentage = Math.round((charCount / charLimit) * 100); const remaining = charLimit - charCount; console.log('\\nšŸ“Š Vite Wix Build Analysis:'); console.log(` Characters: ${charCount}/${charLimit} (${percentage}%)`); if (charCount > charLimit) { console.log(` āŒ OVER LIMIT by ${charCount - charLimit} characters`); throw new Error(`Wix build exceeds character limit by ${charCount - charLimit} characters`); } else { console.log(` āœ… Within limit (${remaining} characters remaining)`); if (remaining < 500) { console.log(` āš ļø Warning: Less than 500 characters remaining`); } } } catch (error) { console.error('āŒ Vite Wix build failed:', error); throw error; } } } }; } // Helper methods (same as build-wix.js) declare module 'rollup' { interface PluginContext { minifyJS(code: string): string; injectEnvironmentVariables(sourceCode: string): string; } } // Add the helper methods to the plugin context function addHelperMethods(plugin: Plugin): Plugin { const originalHandler = (plugin.generateBundle as unknown as { handler: () => unknown }).handler; (plugin.generateBundle as unknown as { handler: () => unknown }).handler = function(this: PluginContext) { this.minifyJS = (code: string) => { const strings: string[] = []; let stringIndex = 0; const protectedCode = code.replace(/(["'`])(?:(?=(\\?))\2.)*?\1/g, (match) => { const placeholder = `__STRING_${stringIndex}__`; strings[stringIndex] = match; stringIndex++; return placeholder; }); let minified = protectedCode .replace(/\/\/[^\r\n]*/g, '') .replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\s+/g, ' ') .replace(/\s*([{}();,])\s*/g, '$1') .replace(/\s*:\s*/g, ':') .replace(/\s*([=!<>+\-*&|])\s*/g, '$1') .replace(/\s*\.\s*/g, '.') .trim(); for (let i = 0; i < strings.length; i++) { minified = minified.replace(`__STRING_${i}__`, strings[i]); } return minified; }; this.injectEnvironmentVariables = (sourceCode: string) => { const productionOnlyEnvConfigs = `const ENV_CONFIGS = { production: { proxyUrl: '${process.env.PROXY_URL || 'https://buzztrail-proxy.vercel.app/api'}', name: 'Production', useRealTavus: true, dailyDomain: 'tavusapi.daily.co', redirectUrl: 'https://www.buzztrail.ai/meet-buzz' } };`; const envConfigsPattern = /const ENV_CONFIGS = \\{[\\s\\S]*?\\};/; const updatedCode = sourceCode.replace(envConfigsPattern, productionOnlyEnvConfigs); const configPattern = /const CONFIG = \\{[\\s\\S]*?\\};/; const newConfig = `const CONFIG = { sectionId: '${process.env.SECTION_ID || 'comp-mfdtv4rf5'}', proxyUrl: '${process.env.PROXY_URL || 'https://buzztrail-proxy.vercel.app/api'}', personaId: '${process.env.PERSONA_ID || 'p527c5d8b826'}', replicaId: '${process.env.REPLICA_ID || 'rca8a38779a8'}', conversationDuration: ${parseInt(process.env.CONVERSATION_DURATION || '300')}, videoUrl: '${process.env.VIDEO_URL || 'https://video.wixstatic.com/video/878890_9ada079151a14e1ca7cfc09930f3177f/1080p/mp4/file.mp4'}', buttonText: '${process.env.BUTTON_TEXT || 'Talk with Tom'}', redirectUrl: '${process.env.REDIRECT_URL || 'https://www.buzztrail.ai/meet-buzz'}', initDelay: ${parseInt(process.env.INIT_DELAY || '2000')} };`; return updatedCode.replace(configPattern, newConfig); }; return originalHandler.call(this); }; return plugin; } export { addHelperMethods };