-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathserver.js
101 lines (89 loc) · 2.88 KB
/
server.js
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
import withFlokServer from "@flok-editor/server-middleware";
import express from "express";
import compression from "compression";
import fs from "fs";
import http from "http";
import https from "https";
import { networkInterfaces } from "os";
import pc from "picocolors";
import process from "process";
import ViteExpress from "./vite-express.js";
import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function info(msg) {
const timestamp = new Date().toLocaleString("en-US").split(",")[1].trim();
console.log(
`${pc.dim(timestamp)} ${pc.bold(pc.cyan("[flok-web]"))} ${pc.green(msg)}`,
);
}
export async function startServer({ onReady, staticDir, ...opts }) {
try {
const app = express();
app.use(compression());
if (staticDir) {
info(`Serving extra static files at ${pc.gray(staticDir)}`);
app.use(express.static(staticDir));
}
let viteServer;
if (opts.secure) {
info(
`Using SSL certificate at ${pc.gray(opts.sslCert)} (key at ${pc.gray(opts.sslKey)})`,
);
const key = fs.readFileSync(opts.sslKey);
const cert = fs.readFileSync(opts.sslCert);
viteServer = https.createServer({ key, cert }, app);
} else {
viteServer = http.createServer(app);
}
ViteExpress.config({
mode: opts?.mode || "development",
inlineViteConfig: {
root: path.resolve(__dirname),
},
viteConfigFile: path.resolve(__dirname, "vite.config.ts"),
vitePort: opts.port,
});
ViteExpress.bind(app, viteServer);
const server = withFlokServer(viteServer);
server.listen(
opts.port,
onReady ||
(() => {
const netResults = getPossibleIpAddresses();
const schema = opts.secure ? "https" : "http";
info(`Listening on ${schema}://localhost:${opts.port}`);
if (netResults.length > 1) {
info("If on LAN, try sharing with your friends one of these URLs:");
Object.entries(netResults).map(([k, v]) => {
info(`\t${k}: ${schema}://${v}:${opts.port}`);
});
} else {
info(
`If on LAN, try sharing with your friends ${schema}://${Object.values(netResults)[0]}:${opts.port}`,
);
}
}),
);
} catch (err) {
console.error(err);
process.exit(1);
}
}
const getPossibleIpAddresses = () => {
const nets = networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
if (net.family === "IPv4" && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
return results;
};