forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.ts
103 lines (88 loc) · 2.66 KB
/
cli.ts
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
102
103
#!/usr/bin/env node
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import type { ServerBuild } from "react-router";
import { createRequestHandler } from "@react-router/express";
import compression from "compression";
import express from "express";
import morgan from "morgan";
import sourceMapSupport from "source-map-support";
import getPort from "get-port";
process.env.NODE_ENV = process.env.NODE_ENV ?? "production";
sourceMapSupport.install({
retrieveSourceMap: function (source) {
let match = source.startsWith("file://");
if (match) {
let filePath = url.fileURLToPath(source);
let sourceMapPath = `${filePath}.map`;
if (fs.existsSync(sourceMapPath)) {
return {
url: source,
map: fs.readFileSync(sourceMapPath, "utf8"),
};
}
}
return null;
},
});
run();
function parseNumber(raw?: string) {
if (raw === undefined) return undefined;
let maybe = Number(raw);
if (Number.isNaN(maybe)) return undefined;
return maybe;
}
async function run() {
let port = parseNumber(process.env.PORT) ?? (await getPort({ port: 3000 }));
let buildPathArg = process.argv[2];
if (!buildPathArg) {
console.error(`
Usage: react-router-serve <server-build-path> - e.g. react-router-serve build/server/index.js`);
process.exit(1);
}
let buildPath = path.resolve(buildPathArg);
let build: ServerBuild = await import(url.pathToFileURL(buildPath).href);
let onListen = () => {
let address =
process.env.HOST ||
Object.values(os.networkInterfaces())
.flat()
.find((ip) => String(ip?.family).includes("4") && !ip?.internal)
?.address;
if (!address) {
console.log(`[react-router-serve] http://localhost:${port}`);
} else {
console.log(
`[react-router-serve] http://localhost:${port} (http://${address}:${port})`
);
}
};
let app = express();
app.disable("x-powered-by");
app.use(compression());
app.use(
path.posix.join(build.publicPath, "assets"),
express.static(path.join(build.assetsBuildDirectory, "assets"), {
immutable: true,
maxAge: "1y",
})
);
app.use(build.publicPath, express.static(build.assetsBuildDirectory));
app.use(express.static("public", { maxAge: "1h" }));
app.use(morgan("tiny"));
app.all(
"*",
createRequestHandler({
build,
mode: process.env.NODE_ENV,
})
);
let server = process.env.HOST
? app.listen(port, process.env.HOST, onListen)
: app.listen(port, onListen);
["SIGTERM", "SIGINT"].forEach((signal) => {
process.once(signal, () => server?.close(console.error));
});
}