Skip to content
This repository has been archived by the owner on Jan 20, 2025. It is now read-only.

Commit

Permalink
redoing index.ts, formatting, and installing new packages to pnpm
Browse files Browse the repository at this point in the history
  • Loading branch information
bearcattt committed Oct 25, 2024
1 parent b0b5965 commit d43506e
Show file tree
Hide file tree
Showing 7 changed files with 1,889 additions and 3,894 deletions.
106 changes: 62 additions & 44 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,64 +5,83 @@ import fastifyCompress from "@fastify/compress";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { exec } from "child_process";
import { libcurlPath } from "@mercuryworkshop/libcurl-transport";
import { promisify } from "node:util";
import chalk from "chalk";
import { IncomingMessage, ServerResponse, createServer, Server } from "http";
import { Socket } from "net";
import { epoxyPath } from "@mercuryworkshop/epoxy-transport";
import { libcurlPath } from "@mercuryworkshop/libcurl-transport";
import { baremuxPath } from "@mercuryworkshop/bare-mux/node";
import { server as wisp } from "@mercuryworkshop/wisp-js/server";

// wisp settings
// See https://github.com/lunar-proxy/lunar/wiki for more details
// wisp.options.dns_method = "resolve";
// wisp.options.dns_servers = ["1.1.1.3", "1.0.0.3"];
// wisp.options.dns_result_order = "ipv4first";

const execPromise = promisify(exec);
const port: number = Number(process.env.PORT) || 8080;
const host: string = process.env.HOST || "localhost";

const serverFactory = (
handler: (req: IncomingMessage, res: ServerResponse) => void,
): Server =>
createServer(handler).on("upgrade", (req, socket: Socket, head) => {
if (req.url?.startsWith("/ws")) {
wisp.routeRequest(req, socket, head);
} else {
socket.destroy();
const build = async () => {
if (!fs.existsSync("dist")) {
console.log(
chalk.yellow.bold("🚧 Cannot find dist folder, building lunar..."),
);
try {
const Process = exec("npm run build");
Process.stdout?.on("data", (data) => {
process.stdout.write(chalk.cyan(data));
});
Process.stderr?.on("data", (data) => {
process.stderr.write(chalk.red(data));
});
await new Promise((resolve, reject) => {
Process.on("close", (code) => {
if (code === 0) {
resolve(true);
} else {
reject(
new Error(
`⚠️ Lunar failed to build failed with exit code ${code}`,
),
);
}
});
});
console.log(chalk.green.bold("βœ… Dist folder was successfully built."));
} catch (error) {
throw new Error(
`${chalk.red.bold("❌ Failed to build the dist folder:")} ${error instanceof Error ? error.message : error}`,
);
}
});
}
};

const app = Fastify({
logger: false, // Set to true to enable logging
serverFactory,
logger: false,
serverFactory: (
handler: (req: IncomingMessage, res: ServerResponse) => void,
): Server =>
createServer(handler).on(
"upgrade",
(req: IncomingMessage, socket: Socket, head: Buffer) => {
if (req.url?.startsWith("/ws")) {
wisp.routeRequest(req, socket, head);
} else {
socket.destroy();
}
},
),
});

try {
if (!fs.existsSync("dist")) {
console.log(chalk.blue.bold("Cannot find dist folder, building..."));
await execPromise("npm run build");
console.log(chalk.green.bold("Dist folder successfully built."));
}

await build();
await app.register(fastifyMiddie);
await app.register(fastifyCompress, {
encodings: ["deflate", "gzip", "br"],
});
await app.register(fastifyCompress, { encodings: ["deflate", "gzip", "br"] });

let Handler;
if (fs.existsSync("./dist/server/entry.mjs")) {
// @ts-ignore
//@ts-ignore
const module = await import("./dist/server/entry.mjs");
Handler = module.handler;
app.use(Handler);
app.use(module.handler);
}

await app.register(fastifyStatic, {
app.register(fastifyStatic, {
root: fileURLToPath(new URL("./dist/client", import.meta.url)),
});

app.register(fastifyStatic, {
root: epoxyPath,
prefix: "/ep/",
Expand All @@ -78,24 +97,23 @@ try {
prefix: "/bm/",
decorateReply: false,
});
app.listen({ port }, (err, address) => {

app.listen({ host, port }, (err, address) => {
if (err) {
console.error(chalk.red.bold(err));
console.error(chalk.red.bold(`❌ Failed to start lunar: ${err.message}`));
process.exit(1);
} else {
console.log(
chalk.blue.bold(
`Lunar v${process.env.npm_package_version} is running on:`,
chalk.green.bold(
`πŸŒ™ Lunar v${process.env.npm_package_version} is running on:`,
),
);
console.log(chalk.blue.bold(`http://localhost:${port}`));
console.log(chalk.blue.bold(`${address}`));
console.log(chalk.blue(`🌐 Local: http://${host}:${port}`));
console.log(chalk.blue(`🌍 Network: ${address}`));
}
});
} catch (error: unknown) {
// console.error() just prints out a red message to the console.
// throw ... raises an exception in the current code block and causes it to exit, or to flow to next catch statement if raised in a try block.
throw new Error(
`${chalk.red.bold(`Unable to start or build server: `)} ${error instanceof Error ? error.message : error}`,
`${chalk.red.bold("❌ An error happend while trying to start lunar:")} ${error instanceof Error ? error.message : error}`,
);
}
Loading

0 comments on commit d43506e

Please sign in to comment.