refactor: initial moves
This commit is contained in:
85
web/src/server.ts
Normal file
85
web/src/server.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Web server factory module.
|
||||
* Exports a function to create and start the web server.
|
||||
* This allows the server to be started in-process from the main application.
|
||||
*/
|
||||
|
||||
import { serve } from "bun";
|
||||
|
||||
export interface WebServerConfig {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
}
|
||||
|
||||
export interface WebServerInstance {
|
||||
server: ReturnType<typeof serve>;
|
||||
stop: () => Promise<void>;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and starts the web server.
|
||||
*
|
||||
* IMPORTANT: This function must be called from within the web project directory
|
||||
* or the bundler won't resolve paths correctly. Use `startWebServerFromRoot`
|
||||
* if calling from the main application.
|
||||
*/
|
||||
export async function createWebServer(config: WebServerConfig = {}): Promise<WebServerInstance> {
|
||||
const { port = 3000, hostname = "localhost" } = config;
|
||||
|
||||
// Dynamic import of the HTML to ensure bundler context is correct
|
||||
const index = await import("./index.html");
|
||||
|
||||
const server = serve({
|
||||
port,
|
||||
hostname,
|
||||
routes: {
|
||||
// Serve index.html for all unmatched routes (SPA catch-all)
|
||||
"/*": index.default,
|
||||
|
||||
|
||||
|
||||
"/api/health": () => Response.json({ status: "ok", timestamp: Date.now() }),
|
||||
},
|
||||
|
||||
development: process.env.NODE_ENV !== "production" && {
|
||||
hmr: true,
|
||||
console: true,
|
||||
},
|
||||
});
|
||||
|
||||
const url = `http://${hostname}:${port}`;
|
||||
|
||||
return {
|
||||
server,
|
||||
url,
|
||||
stop: async () => {
|
||||
server.stop(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the web server from the main application root.
|
||||
* Handles the working directory context switch needed for bundler resolution.
|
||||
*/
|
||||
export async function startWebServerFromRoot(
|
||||
webProjectPath: string,
|
||||
config: WebServerConfig = {}
|
||||
): Promise<WebServerInstance> {
|
||||
const originalCwd = process.cwd();
|
||||
|
||||
try {
|
||||
// Change to web project directory for correct bundler resolution
|
||||
process.chdir(webProjectPath);
|
||||
|
||||
const instance = await createWebServer(config);
|
||||
|
||||
console.log(`🌐 Web server running at ${instance.url}`);
|
||||
|
||||
return instance;
|
||||
} finally {
|
||||
// Restore original working directory
|
||||
process.chdir(originalCwd);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user