-
-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathcli.ts
More file actions
234 lines (201 loc) · 6.17 KB
/
Copy pathcli.ts
File metadata and controls
234 lines (201 loc) · 6.17 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env node
import fs from "node:fs";
import net from "node:net";
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 { createRequestListener } from "@remix-run/node-fetch-server";
import compression from "compression";
import express from "express";
import type { RequestHandler as ExpressRequestHandler } from "express";
import morgan from "morgan";
import sourceMapSupport from "source-map-support";
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();
type RSCServerBuildModule = {
default: {
fetch: (request: Request) => Response | Promise<Response>;
};
unstable_reactRouterServeConfig?: {
publicPath: string;
assetsBuildDirectory: string;
};
};
type NormalizedBuild = {
fetch?: (request: Request) => Response | Promise<Response>;
publicPath: string;
assetsBuildDirectory: string;
};
function isRSCServerBuild(build: unknown): build is RSCServerBuildModule {
return Boolean(
typeof build === "object" &&
build &&
"default" in build &&
typeof build.default === "object" &&
build.default &&
"fetch" in build.default &&
typeof build.default.fetch === "function",
);
}
function parseNumber(raw?: string) {
if (raw === undefined) return undefined;
let maybe = Number(raw);
if (Number.isNaN(maybe)) return undefined;
return maybe;
}
async function getAvailablePort(
preferredPort: number,
host?: string,
): Promise<number> {
let preferredAvailablePort = await checkPort(preferredPort, host);
let availablePort = preferredAvailablePort ?? (await checkPort(0, host));
if (availablePort === undefined) {
throw new Error("No available port found");
}
return availablePort;
}
function checkPort(port: number, host?: string): Promise<number | undefined> {
return new Promise((resolve, reject) => {
let server = net.createServer();
let listenOptions = host ? { port, host } : { port };
server.unref();
server.once("error", (error: NodeJS.ErrnoException) => {
if (error.code === "EADDRINUSE" || error.code === "EACCES") {
resolve(undefined);
} else {
reject(error);
}
});
server.listen(listenOptions, () => {
let address = server.address();
let availablePort =
typeof address === "object" && address ? address.port : port;
server.close((error) => {
if (error) {
reject(error);
} else {
resolve(availablePort);
}
});
});
});
}
function getExpressPath(publicPath: string) {
// Vite allows `base` to be an absolute URL, but Express route paths must be
// pathnames. Strip any origin before mounting static asset middleware.
let pathname: string;
try {
pathname = new URL(publicPath).pathname;
} catch {
pathname = publicPath;
}
return pathname.startsWith("/") ? pathname : `/${pathname}`;
}
async function run() {
let port =
parseNumber(process.env.PORT) ??
(await getAvailablePort(3000, process.env.HOST));
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 buildModule = await import(url.pathToFileURL(buildPath).href);
let build: NormalizedBuild;
let isRSCBuild = false;
if ((isRSCBuild = isRSCServerBuild(buildModule))) {
const config = {
publicPath: "/",
assetsBuildDirectory: path.join("..", "client"),
...(buildModule.unstable_reactRouterServeConfig || {}),
};
build = {
fetch: buildModule.default.fetch,
publicPath: config.publicPath,
assetsBuildDirectory: path.resolve(
path.dirname(buildPath),
config.assetsBuildDirectory,
),
} satisfies NormalizedBuild;
} else {
build = buildModule as ServerBuild;
}
let onListen = (error: unknown) => {
if (error) {
throw error;
}
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");
if (!isRSCBuild) {
// `compression` may resolve to Express 4 types from transitive deps while
// `react-router-serve` uses Express 5, but the runtime middleware signature
// is compatible.
app.use(compression() as unknown as ExpressRequestHandler);
}
let expressPublicPath = getExpressPath(build.publicPath);
app.use(
path.posix.join(expressPublicPath, "assets"),
express.static(path.join(build.assetsBuildDirectory, "assets"), {
immutable: true,
maxAge: "1y",
}),
);
app.use(expressPublicPath, express.static(build.assetsBuildDirectory));
app.use(express.static("public", { maxAge: "1h" }));
app.use(
"/.well-known",
express.static(path.join(build.assetsBuildDirectory, ".well-known")),
);
app.use(morgan("tiny"));
if (build.fetch) {
app.all("/{*splat}", createRequestListener(build.fetch));
} else {
app.all(
"/{*splat}",
createRequestHandler({
build: buildModule,
mode: process.env.NODE_ENV,
}) as unknown as ExpressRequestHandler,
);
}
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));
});
}