Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import fs from 'fs';import path from 'path';import { runBuild } from './build.js';import { generateKundaliPdfBuffer } from '../src/pdf_kit_engine.js';
const PORT = Number(process.env.PORT) || 3000;const ROOT_DIR = process.cwd();const SRC_DIR = path.join(ROOT_DIR, 'src');const DIST_DIR = path.join(ROOT_DIR, 'dist');
// Set of active SSE client stream controllers for Live-Reloadconst sseClients = new Set();
function broadcastReload() { for (const controller of sseClients) { try { controller.enqueue(new TextEncoder().encode('data: reload\n\n')); } catch { sseClients.delete(controller); } }}
// Perform initial build before starting the serverconsole.log('⚡ Performing initial build for dev server...');await runBuild({ isDev: true, silent: false });
// Live-reload client script injected into HTML during dev modeconst LIVE_RELOAD_SNIPPET = `<script id="__divya_live_reload__">(function() { let es; function connect() { es = new EventSource('/live-reload'); es.onopen = function() { console.log('%c⚡ [LiveReload] Connected to dev server', 'color: #10b981; font-weight: bold;'); }; es.onmessage = function(e) { if (e.data === 'reload') { console.log('%c🔄 [LiveReload] Changes detected. Reloading...', 'color: #f59e0b; font-weight: bold;'); window.location.reload(); } }; es.onerror = function() { es.close(); setTimeout(connect, 1500); }; } connect();})();</script>`;
// Start Bun Live HTTP Development Serverconst server = Bun.serve({ port: PORT, async fetch(req) { const url = new URL(req.url); let pathname = url.pathname;
// 1. PDFKit Kundali Generation API Endpoint if (pathname === '/api/generate-pdf' && req.method === 'POST') { try { const body = await req.json(); const { data, lang } = body;
if (!data) { return new Response(JSON.stringify({ error: 'Missing horoscope data payload' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); }
const pdfBuffer = await generateKundaliPdfBuffer(data, lang || 'te'); const sanitizedName = (data.fullName || 'Jathakam').replace(/[\s\/\:\*\?\"\<\>\|]+/g, '_');
return new Response(pdfBuffer, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': `attachment; filename="${encodeURIComponent(sanitizedName)}_Kundali.pdf"`, 'Cache-Control': 'no-cache' } }); } catch (err) { console.error('❌ [PDFKit API Error]:', err); return new Response(JSON.stringify({ error: (err && err.message) ? err.message : 'PDF Generation Failed' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } }
// 2. Live-Reload Server-Sent Events (SSE) Endpoint if (pathname === '/live-reload') { const stream = new ReadableStream({ start(controller) { sseClients.add(controller); controller.enqueue(new TextEncoder().encode('data: connected\n\n')); }, cancel(controller) { sseClients.delete(controller); } });
return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', 'Connection': 'keep-alive' } }); }
// 3. Route root to index.html if (pathname === '/' || pathname === '') { pathname = '/index.html'; }
// 4. Try dist folder first let filePath = path.join(DIST_DIR, pathname); let file = Bun.file(filePath);
if (!(await file.exists())) { // Try root directory filePath = path.join(ROOT_DIR, pathname); file = Bun.file(filePath); }
if (await file.exists()) { // Inject live-reload snippet into HTML files if (pathname.endsWith('.html')) { let htmlContent = await file.text(); if (!htmlContent.includes('__divya_live_reload__')) { if (htmlContent.includes('</body>')) { htmlContent = htmlContent.replace('</body>', `${LIVE_RELOAD_SNIPPET}\n</body>`); } else { htmlContent += LIVE_RELOAD_SNIPPET; } } return new Response(htmlContent, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate' } }); }
// Other assets (CSS, JS, Fonts, Images) return new Response(file, { headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate' } }); }
return new Response('404 Not Found', { status: 404 }); }});
console.log(`\n================================================================`);console.log(`🚀 Divya Jyotisham Live Development Server running!`);console.log(`📡 Local URL: http://localhost:${PORT}`);console.log(`📄 PDF Engine: PDFKit on Bun (Native /api/generate-pdf)`);console.log(`👀 Watching: src/ for automatic builds & instant live reload`);console.log(`================================================================\n`);
// 5. File Watcher on src/ with Debounced Rebuild & Live Reloadlet debounceTimer = null;let isBuilding = false;
function onFileChange(eventType, filename) { if (!filename) return;
// Ignore temporary files and editor artifacts if (filename.includes('~') || filename.startsWith('.') || filename.endsWith('.swp')) return;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => { if (isBuilding) return; isBuilding = true;
const startTime = Date.now(); console.log(`\n🔄 [Watch] File changed: src/${filename} -> Rebuilding...`);
try { const success = await runBuild({ isDev: true, silent: true }); const duration = Date.now() - startTime; if (success) { console.log(`✅ [Watch] Rebuilt in ${duration}ms. Triggering live reload across ${sseClients.size} client(s)...`); broadcastReload(); } } catch (err) { console.error('❌ [Watch] Rebuild error:', err); } finally { isBuilding = false; } }, 80);}
try { fs.watch(SRC_DIR, { recursive: true }, onFileChange); console.log(`👀 File watcher actively monitoring ${SRC_DIR}`);} catch (err) { console.error('Failed to start recursive file watcher on src/:', err);}