File size: 5,916 Bytes
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353a9b9
 
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76dbde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import express, { type Express } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { createServer as createViteServer, createLogger } from "vite";
import { type Server } from "http";
import viteConfig from "../vite.config";
import { nanoid } from "nanoid";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const viteLogger = createLogger();

export function log(message: string, source = "express") {
  const formattedTime = new Date().toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit",
    second: "2-digit",
    hour12: true,
  });

  console.log(`${formattedTime} [${source}] ${message}`);
}

export async function setupVite(app: Express, server: Server) {
  const serverOptions = {
    middlewareMode: true,
    hmr: { server },
    allowedHosts: ["*"],
  };

  const vite = await createViteServer({
    ...viteConfig,
    configFile: false,
    customLogger: {
      ...viteLogger,
      error: (msg, options) => {
        console.warn('Vite error (non-fatal):', msg);
        // Don't exit on Vite errors - they're often non-critical
      },
    },
    server: serverOptions,
    appType: "custom",
  });

  app.use(vite.middlewares);
  app.use("*", async (req, res, next) => {
    const url = req.originalUrl;

    try {
      const clientTemplate = path.resolve(
        __dirname,
        "..",
        "client",
        "index.html",
      );

      // always reload the index.html file from disk incase it changes
      let template = await fs.promises.readFile(clientTemplate, "utf-8");
      template = template.replace(
        `src="/src/main.tsx"`,
        `src="/src/main.tsx?v=${nanoid()}"`,
      );
      const page = await vite.transformIndexHtml(url, template);
      res.status(200).set({ "Content-Type": "text/html" }).end(page);
    } catch (e) {
      vite.ssrFixStacktrace(e as Error);
      next(e);
    }
  });
}

export function serveStatic(app: Express) {
  // Debug: log current working directory and __dirname
  console.log("πŸ” Current working directory:", process.cwd());
  console.log("πŸ” __dirname:", __dirname);
  
  // Try multiple possible paths for the static files
  const possiblePaths = [
    path.resolve(__dirname, "../dist/public"),
    path.resolve(__dirname, "public"),
    path.resolve(process.cwd(), "dist/public"),
    path.resolve(process.cwd(), "public")
  ];
  
  let distPath: string | null = null;
  
  for (const testPath of possiblePaths) {
    console.log("🧩 Testing path:", testPath, "- exists:", fs.existsSync(testPath));
    if (fs.existsSync(testPath)) {
      distPath = testPath;
      console.log("βœ… Found static files at:", distPath);
      break;
    }
  }

  if (!distPath) {
    console.warn(`❌ Build directory not found. Tested paths:`, possiblePaths);
    
    // Fallback: serve a basic HTML response
    app.get('/', (_req, res) => {
      res.send(`
        <!DOCTYPE html>
        <html>
          <head>
            <title>KnowledgeBridge</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style>
              body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; background: #f8fafc; }
              .container { max-width: 800px; margin: 0 auto; text-align: center; }
              .status { background: #10b981; color: white; padding: 1rem; border-radius: 8px; margin: 2rem 0; }
              .api-links { background: white; padding: 2rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
              a { color: #3b82f6; text-decoration: none; }
              a:hover { text-decoration: underline; }
            </style>
          </head>
          <body>
            <div class="container">
              <h1>πŸš€ KnowledgeBridge</h1>
              <div class="status">βœ… Server is running successfully!</div>
              <div class="api-links">
                <h3>API Endpoints Available:</h3>
                <p><a href="/api/health">Health Check</a></p>
                <p><a href="/api/documents">Documents API</a></p>
                <p>POST /api/search - Search endpoint</p>
                <p>POST /api/analyze-document - Document analysis</p>
                <p>POST /api/enhance-query - Query enhancement</p>
              </div>
              <p><em>Frontend build not found. The API is fully functional.</em></p>
            </div>
          </body>
        </html>
      `);
    });
    
    // Catch all other routes
    app.use("*", (_req, res) => {
      res.redirect('/');
    });
    
    return;
  }

  console.log("πŸš€ Serving static files from:", distPath);
  app.use(express.static(distPath));

  // Explicit root route
  app.get("/", (_req, res) => {
    const indexPath = path.resolve(distPath, "index.html");
    console.log("🏠 Root route: serving index.html from:", indexPath);
    if (fs.existsSync(indexPath)) {
      res.sendFile(indexPath);
    } else {
      res.status(500).send("Frontend build not found");
    }
  });

  // SPA fallback - serve index.html for non-API routes
  app.get("*", (req, res) => {
    // Don't intercept API routes
    if (req.path.startsWith('/api/')) {
      return res.status(404).json({ error: 'API endpoint not found' });
    }
    const indexPath = path.resolve(distPath, "index.html");
    console.log("πŸ” Fallback serving: index.html from:", indexPath);
    
    // Verify the index.html file exists before serving
    if (fs.existsSync(indexPath)) {
      console.log("βœ… index.html exists, serving file");
      res.sendFile(indexPath);
    } else {
      console.error("❌ index.html not found at:", indexPath);
      res.status(404).send(`
        <h1>❌ Frontend Not Found</h1>
        <p>Expected index.html at: ${indexPath}</p>
        <p>Available files: ${fs.readdirSync(distPath).join(', ')}</p>
      `);
    }
  });
}