Files
UDN/index.ts
T

75 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-07-05 12:48:42 +02:00
import { ServerWebSocket, write } from "bun";
import {
addConnection,
audit,
connectionCount,
forgetConnection,
processMessage,
subscriptions,
} from "./websocket-handler";
2024-07-05 13:17:19 +02:00
import { writeInfo, writeStat } from "./utility";
2024-07-04 17:27:46 +02:00
2024-07-05 12:48:42 +02:00
import Colors from "colors";
2024-07-05 13:17:19 +02:00
import IP from "ip";
2024-07-04 16:11:02 +02:00
import Path from "path";
// CONFIG
const staticDir = "static/dist";
const defaultPage = "index.html";
2024-07-04 17:27:46 +02:00
// TYPES
export type WS = ServerWebSocket<unknown>;
2024-07-04 16:11:02 +02:00
// SERVER
const server = Bun.serve({
fetch(request, server) {
2024-07-04 16:18:40 +02:00
// allow websockets
server.upgrade(request);
2024-07-04 16:11:02 +02:00
2024-07-04 16:18:40 +02:00
// respond
const requestPath = new URL(request.url).pathname;
2024-07-04 18:02:53 +02:00
switch (requestPath) {
case "/":
return createFileResponse(defaultPage);
default:
return createFileResponse(requestPath);
2024-07-04 16:11:02 +02:00
}
},
2024-07-04 16:18:40 +02:00
websocket: {
2024-07-05 12:48:42 +02:00
open() {
addConnection();
},
2024-07-04 16:18:40 +02:00
message(ws, message) {
2024-07-04 17:27:46 +02:00
processMessage(ws, message.toString());
},
2024-07-05 12:48:42 +02:00
close(ws) {
2024-07-04 18:18:44 +02:00
forgetConnection(ws);
2024-07-04 16:18:40 +02:00
},
},
2024-07-04 16:11:02 +02:00
});
function createFileResponse(requestPath: string): Response {
const fullPath = Path.join(staticDir, requestPath);
return new Response(Bun.file(fullPath));
}
2024-07-05 12:48:42 +02:00
// CLI
2024-07-05 13:17:19 +02:00
function updateCLI() {
2024-07-05 12:48:42 +02:00
console.clear();
2024-07-05 13:17:19 +02:00
console.log(Colors.bold.bgWhite("UNIVERSAL DECENTRALIZED NETWORK"));
2024-07-05 12:48:42 +02:00
console.log();
2024-07-05 13:17:19 +02:00
2024-07-05 12:48:42 +02:00
console.log(new Date().toLocaleString());
console.log();
2024-07-05 13:17:19 +02:00
writeInfo("server url", Colors.bold.green(server.url.toString()));
writeInfo("server ip address", Colors.bold.green(IP.address()));
console.log();
2024-07-05 12:48:42 +02:00
audit().forEach((entry) => writeStat(...entry));
}
2024-07-05 13:17:19 +02:00
updateCLI();
setInterval(updateCLI, 5000);