-
Notifications
You must be signed in to change notification settings - Fork 158
/
index.js
78 lines (72 loc) · 2.67 KB
/
index.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
import Fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import fastifyCompress from '@fastify/compress';
import { createBareServer } from '@tomphttp/bare-server-node';
import { createServer } from 'http';
import chalk from 'chalk';
import open from 'open';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const gitCommitInfo = require('git-commit-info');
if (!existsSync("./dist")) await import("./esbuild.prod.js");
const __dirname = dirname(fileURLToPath(import.meta.url));
const port = process.env.PORT || 3000;
const _v = process.env.npm_package_version;
const info = {
hashShort: `${JSON.stringify(gitCommitInfo().shortHash).replace('"', "").replace("/", "").replace('\"', "")}`,
hash: `${JSON.stringify(gitCommitInfo().hash).replace('"', "").replace("/", "").replace('\"', "")}`,
version: _v,
}
const bare = createBareServer('/bare/');
const serverFactory = (handler, opts) => {
return createServer()
.on("request", (req, res) => {
if (req.url === "/info") {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(info));
} else if (bare.shouldRoute(req)) {
bare.routeRequest(req, res);
} else {
handler(req, res)
}
}).on("upgrade", (req, socket, head) => {
if (bare.shouldRoute(req)) {
bare.routeUpgrade(req, socket, head);
} else {
socket.end();
}
});
}
const fastify = Fastify({ serverFactory });
fastify.register(fastifyStatic, {
root: join(__dirname, "./static"),
decorateReply: false
});
fastify.register(fastifyStatic, {
root: join(__dirname, "./dist"),
prefix: "/dynamic/",
decorateReply: false
});
fastify.register(fastifyCompress, {
encodings: ["br"]
});
const URL = `http://localhost:${port}/`;
fastify.listen({ port }, async (err) => {
if (err && err.code === "EADDRINUSE") {
console.log(chalk.red.bold(`[Dynamic ${_v}] `) + "Port is already in use! Please close any apps using port " + chalk.bold.underline.red(port) + " and try again.");
process.exit(1);
} else if (err) {
console.log(chalk.bold.red(`[Dynamic ${_v}] `) + "An error occurred while starting the server! \n" + err);
process.exit(1);
}
console.log(chalk.bold('Thanks for using Dynamic!'), chalk.red(`Please notice that ${chalk.red.bold('dynamic is currently in public BETA')}. please report all issues to the GitHub page. `))
console.log(chalk.green.bold(`Dynamic ${_v} `) + "live at port " + chalk.bold.green(port));
try {
await open(URL);
} catch (ERR) {
console.error(ERR);
}
});