bini-server 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +135 -83
- package/dist/cli.js +439 -213
- package/dist/cli.js.map +1 -1
- package/dist/index.js +439 -213
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
package/dist/index.js
CHANGED
|
@@ -6,11 +6,20 @@ import os from "os";
|
|
|
6
6
|
import net from "net";
|
|
7
7
|
import crypto from "crypto";
|
|
8
8
|
import readline from "readline";
|
|
9
|
-
import
|
|
9
|
+
import zlib from "zlib";
|
|
10
|
+
import { spawn } from "child_process";
|
|
10
11
|
import { pathToFileURL } from "url";
|
|
11
12
|
import { Readable } from "stream";
|
|
12
13
|
import { pipeline } from "stream/promises";
|
|
13
14
|
import { loadEnvFiles, envFilesFor } from "bini-env/node";
|
|
15
|
+
import { toApiPath as runtimeToApiPath } from "bini-router/runtime";
|
|
16
|
+
var HttpError = class extends Error {
|
|
17
|
+
status;
|
|
18
|
+
constructor(status, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
14
23
|
function getEnvVar(key, defaultValue) {
|
|
15
24
|
return process.env[`BINI_${key}`] ?? process.env[`VITE_${key}`] ?? process.env[key] ?? defaultValue;
|
|
16
25
|
}
|
|
@@ -20,21 +29,31 @@ function getEnvVarNumber(key, defaultValue) {
|
|
|
20
29
|
const n = parseInt(raw, 10);
|
|
21
30
|
return isNaN(n) ? defaultValue : n;
|
|
22
31
|
}
|
|
32
|
+
function getBiniFlag(name) {
|
|
33
|
+
const v = process.env[`BINI_${name}`]?.trim().toLowerCase();
|
|
34
|
+
return v === "1" || v === "true" || v === "yes" || v === "on";
|
|
35
|
+
}
|
|
23
36
|
function readConfig() {
|
|
24
|
-
const distDir = path.
|
|
37
|
+
const distDir = path.resolve(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
|
|
25
38
|
const apiDir = path.join(distDir, "api");
|
|
26
|
-
const
|
|
27
|
-
const
|
|
39
|
+
const prefixedBase = process.env.BINI_BASE ?? process.env.VITE_BASE;
|
|
40
|
+
const legacyBase = prefixedBase === void 0 && process.env.BASE !== void 0;
|
|
41
|
+
const rawBase = (prefixedBase ?? process.env.BASE ?? "").trim();
|
|
42
|
+
const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + trimSlashes(rawBase);
|
|
28
43
|
return {
|
|
29
44
|
defaultPort: getEnvVarNumber("PORT", 3e3),
|
|
45
|
+
portExplicit: getEnvVar("PORT") !== void 0,
|
|
46
|
+
host: process.env.BINI_HOST?.trim() || "0.0.0.0",
|
|
47
|
+
trustProxy: getBiniFlag("TRUST_PROXY"),
|
|
48
|
+
compress: getBiniFlag("COMPRESS"),
|
|
30
49
|
bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
|
|
31
50
|
handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
|
|
32
51
|
bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
|
|
33
52
|
distDir,
|
|
34
|
-
compiledApiDir: apiDir + path.sep,
|
|
35
53
|
apiDir,
|
|
36
54
|
apiEntry: path.join(apiDir, "index.mjs"),
|
|
37
55
|
base,
|
|
56
|
+
legacyBase,
|
|
38
57
|
isProd: process.env.NODE_ENV === "production"
|
|
39
58
|
};
|
|
40
59
|
}
|
|
@@ -42,9 +61,6 @@ var config = readConfig();
|
|
|
42
61
|
function refreshConfig() {
|
|
43
62
|
config = readConfig();
|
|
44
63
|
}
|
|
45
|
-
function resolveApiEntry() {
|
|
46
|
-
return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
|
|
47
|
-
}
|
|
48
64
|
var C = {
|
|
49
65
|
CYAN: "\x1B[36m",
|
|
50
66
|
RESET: "\x1B[0m",
|
|
@@ -53,6 +69,25 @@ var C = {
|
|
|
53
69
|
YELLOW: "\x1B[33m",
|
|
54
70
|
DIM: "\x1B[2m"
|
|
55
71
|
};
|
|
72
|
+
function warnTag() {
|
|
73
|
+
return process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
|
|
74
|
+
}
|
|
75
|
+
function trimSlashes(s) {
|
|
76
|
+
let a = 0;
|
|
77
|
+
let b = s.length;
|
|
78
|
+
while (a < b && s[a] === "/") a++;
|
|
79
|
+
while (b > a && s[b - 1] === "/") b--;
|
|
80
|
+
return s.slice(a, b);
|
|
81
|
+
}
|
|
82
|
+
function stripQuery(s) {
|
|
83
|
+
const q = s.indexOf("?");
|
|
84
|
+
const h = s.indexOf("#");
|
|
85
|
+
const i = q === -1 ? h : h === -1 ? q : Math.min(q, h);
|
|
86
|
+
return i === -1 ? s : s.slice(0, i);
|
|
87
|
+
}
|
|
88
|
+
function getRawPath(url) {
|
|
89
|
+
return stripQuery(url);
|
|
90
|
+
}
|
|
56
91
|
function stripBase(pathname) {
|
|
57
92
|
const { base } = config;
|
|
58
93
|
if (!base) return pathname || "/";
|
|
@@ -61,79 +96,33 @@ function stripBase(pathname) {
|
|
|
61
96
|
return null;
|
|
62
97
|
}
|
|
63
98
|
function toApiPath(pathname) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (
|
|
72
|
-
return
|
|
73
|
-
}
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
function
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
let entries;
|
|
86
|
-
try {
|
|
87
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
88
|
-
} catch {
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
for (const entry of entries) {
|
|
92
|
-
if (!entry.isDirectory()) continue;
|
|
93
|
-
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
|
|
94
|
-
const fullPath = path.join(dir, entry.name);
|
|
95
|
-
const routePath = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
96
|
-
if (entry.name.startsWith("[") && entry.name.endsWith("]") && fs.existsSync(path.join(fullPath, "index.html"))) {
|
|
97
|
-
routes.add(`/${routePath}`);
|
|
98
|
-
}
|
|
99
|
-
walk(fullPath, routePath);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
walk(config.distDir, "");
|
|
103
|
-
return routes;
|
|
104
|
-
}
|
|
105
|
-
var shellRouteCache = null;
|
|
106
|
-
function getShellRoutes() {
|
|
107
|
-
return shellRouteCache ??= scanShellRoutes();
|
|
108
|
-
}
|
|
109
|
-
function findMatchingShellRoute(pathname) {
|
|
110
|
-
const pathSegments = pathname.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
|
|
111
|
-
for (const shellRoute of getShellRoutes()) {
|
|
112
|
-
const shellSegments = shellRoute.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
|
|
113
|
-
if (shellSegments.length === 0) continue;
|
|
114
|
-
const last = shellSegments[shellSegments.length - 1];
|
|
115
|
-
const isRequiredCatchAll = last.startsWith("[...") && !last.startsWith("[[...");
|
|
116
|
-
const isOptionalCatchAll = last.startsWith("[[") && last.endsWith("]]");
|
|
117
|
-
if (isRequiredCatchAll || isOptionalCatchAll) {
|
|
118
|
-
const prefix = shellSegments.slice(0, -1);
|
|
119
|
-
if (pathSegments.length < prefix.length) continue;
|
|
120
|
-
if (isRequiredCatchAll && pathSegments.length === prefix.length) continue;
|
|
121
|
-
const matches2 = prefix.every((seg, i) => seg.startsWith("[") && seg.endsWith("]") || seg === pathSegments[i]);
|
|
122
|
-
if (matches2) return shellRoute;
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
if (shellSegments.length !== pathSegments.length) continue;
|
|
126
|
-
const matches = shellSegments.every((seg, i) => seg.startsWith("[") && seg.endsWith("]") || seg === pathSegments[i]);
|
|
127
|
-
if (matches) return shellRoute;
|
|
128
|
-
}
|
|
129
|
-
return null;
|
|
99
|
+
return runtimeToApiPath(pathname, config.base);
|
|
100
|
+
}
|
|
101
|
+
function resolveInDist(pathname) {
|
|
102
|
+
if (pathname.includes("\0") || pathname.includes("\\")) return null;
|
|
103
|
+
if (pathname.split("/").some((s) => s === "..")) return null;
|
|
104
|
+
const root = path.resolve(config.distDir);
|
|
105
|
+
const abs = path.resolve(root, "." + pathname);
|
|
106
|
+
if (abs !== root && !abs.startsWith(root + path.sep)) return null;
|
|
107
|
+
return abs;
|
|
108
|
+
}
|
|
109
|
+
function isDenied(pathname) {
|
|
110
|
+
const segs = pathname.split("/").filter(Boolean);
|
|
111
|
+
const first = segs[0]?.toLowerCase();
|
|
112
|
+
if (first === "api") return true;
|
|
113
|
+
return segs.some((s) => s.startsWith(".") && s !== ".well-known");
|
|
114
|
+
}
|
|
115
|
+
var SKIP_IFACE_PREFIXES = ["veth", "br-", "utun", "tun", "tap"];
|
|
116
|
+
var SKIP_IFACE_PARTS = ["docker", "vmnet", "vbox"];
|
|
117
|
+
function isVirtualInterface(name) {
|
|
118
|
+
const n = name.toLowerCase();
|
|
119
|
+
return SKIP_IFACE_PREFIXES.some((p) => n.startsWith(p)) || SKIP_IFACE_PARTS.some((p) => n.includes(p));
|
|
130
120
|
}
|
|
131
121
|
function getNetworkIp() {
|
|
132
122
|
const ifaces = os.networkInterfaces();
|
|
133
|
-
const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
|
|
134
123
|
const candidates = [];
|
|
135
124
|
for (const name in ifaces) {
|
|
136
|
-
if (
|
|
125
|
+
if (isVirtualInterface(name)) continue;
|
|
137
126
|
for (const iface of ifaces[name] ?? []) {
|
|
138
127
|
if (iface.internal || iface.family !== "IPv4") continue;
|
|
139
128
|
const [a, b] = iface.address.split(".").map(Number);
|
|
@@ -147,38 +136,58 @@ function getNetworkIp() {
|
|
|
147
136
|
}
|
|
148
137
|
function printBanner(port) {
|
|
149
138
|
const envFiles = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
|
|
150
|
-
const
|
|
139
|
+
const { host } = config;
|
|
140
|
+
const wildcard = host === "0.0.0.0" || host === "::";
|
|
141
|
+
const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
|
|
142
|
+
const networkIp = wildcard ? getNetworkIp() : null;
|
|
143
|
+
const localHost = wildcard || loopback ? "localhost" : host.includes(":") ? `[${host}]` : host;
|
|
151
144
|
console.log(`
|
|
152
145
|
${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
|
|
153
146
|
if (envFiles.length > 0) {
|
|
154
147
|
const rel = envFiles.map((f) => path.relative(process.cwd(), f));
|
|
155
148
|
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
|
|
156
149
|
}
|
|
157
|
-
console.log(
|
|
150
|
+
console.log(
|
|
151
|
+
` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://${localHost}:${port}${config.base}/${C.RESET}`
|
|
152
|
+
);
|
|
158
153
|
if (networkIp) {
|
|
159
|
-
console.log(
|
|
154
|
+
console.log(
|
|
155
|
+
` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}${config.base}/${C.RESET}`
|
|
156
|
+
);
|
|
160
157
|
}
|
|
161
158
|
if (config.base) {
|
|
162
159
|
console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
|
|
163
160
|
}
|
|
164
|
-
console.log(
|
|
161
|
+
console.log(
|
|
162
|
+
` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`
|
|
163
|
+
);
|
|
165
164
|
console.log("");
|
|
166
165
|
}
|
|
167
|
-
function isPortFree(port) {
|
|
166
|
+
function isPortFree(port, host) {
|
|
168
167
|
return new Promise((resolve) => {
|
|
169
168
|
const server = net.createServer();
|
|
170
169
|
server.once("error", () => resolve(false));
|
|
171
170
|
server.once("listening", () => server.close(() => resolve(true)));
|
|
172
|
-
server.listen(port,
|
|
171
|
+
server.listen(port, host);
|
|
173
172
|
});
|
|
174
173
|
}
|
|
175
|
-
async function findFreePort(start2) {
|
|
174
|
+
async function findFreePort(start2, host) {
|
|
176
175
|
for (let port = start2; port < start2 + 100; port++) {
|
|
177
|
-
if (await isPortFree(port)) return port;
|
|
176
|
+
if (await isPortFree(port, host)) return port;
|
|
178
177
|
console.log(`Port ${port} is in use, trying another one...`);
|
|
179
178
|
}
|
|
180
179
|
throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
|
|
181
180
|
}
|
|
181
|
+
function openInBrowser(url) {
|
|
182
|
+
const [bin, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
|
|
183
|
+
try {
|
|
184
|
+
const child = spawn(bin, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
185
|
+
child.on("error", () => {
|
|
186
|
+
});
|
|
187
|
+
child.unref();
|
|
188
|
+
} catch {
|
|
189
|
+
}
|
|
190
|
+
}
|
|
182
191
|
function startKeyboardLoop(port) {
|
|
183
192
|
if (!process.stdin.isTTY) return;
|
|
184
193
|
const rl = readline.createInterface({ input: process.stdin });
|
|
@@ -187,16 +196,15 @@ function startKeyboardLoop(port) {
|
|
|
187
196
|
case "h":
|
|
188
197
|
console.log("");
|
|
189
198
|
console.log(" Shortcuts");
|
|
190
|
-
console.log(
|
|
191
|
-
|
|
199
|
+
console.log(
|
|
200
|
+
` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`
|
|
201
|
+
);
|
|
202
|
+
console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
|
|
192
203
|
console.log("");
|
|
193
204
|
break;
|
|
194
|
-
case "o":
|
|
195
|
-
|
|
196
|
-
const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
|
|
197
|
-
exec(cmd);
|
|
205
|
+
case "o":
|
|
206
|
+
openInBrowser(`http://localhost:${port}${config.base}/`);
|
|
198
207
|
break;
|
|
199
|
-
}
|
|
200
208
|
case "q":
|
|
201
209
|
process.exit(0);
|
|
202
210
|
}
|
|
@@ -207,28 +215,41 @@ function readBody(req) {
|
|
|
207
215
|
return new Promise((resolve, reject) => {
|
|
208
216
|
const chunks = [];
|
|
209
217
|
let size = 0;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
218
|
+
let settled = false;
|
|
219
|
+
let timer;
|
|
220
|
+
const stop = () => {
|
|
221
|
+
if (settled) return false;
|
|
222
|
+
settled = true;
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
req.off("data", onData);
|
|
225
|
+
req.off("end", onEnd);
|
|
226
|
+
return true;
|
|
227
|
+
};
|
|
228
|
+
const onData = (chunk) => {
|
|
215
229
|
size += chunk.byteLength;
|
|
216
230
|
if (size > config.bodySizeLimit) {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
231
|
+
if (stop()) {
|
|
232
|
+
req.pause();
|
|
233
|
+
reject(new HttpError(413, "Request body too large"));
|
|
234
|
+
}
|
|
220
235
|
return;
|
|
221
236
|
}
|
|
222
237
|
chunks.push(chunk);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
});
|
|
238
|
+
};
|
|
239
|
+
const onEnd = () => {
|
|
240
|
+
if (stop()) resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
|
|
241
|
+
};
|
|
228
242
|
req.on("error", (err) => {
|
|
229
|
-
|
|
230
|
-
reject(err);
|
|
243
|
+
if (stop()) reject(err);
|
|
231
244
|
});
|
|
245
|
+
timer = setTimeout(() => {
|
|
246
|
+
if (stop()) {
|
|
247
|
+
req.pause();
|
|
248
|
+
reject(new HttpError(408, "Request body timeout"));
|
|
249
|
+
}
|
|
250
|
+
}, config.bodyTimeout);
|
|
251
|
+
req.on("data", onData);
|
|
252
|
+
req.on("end", onEnd);
|
|
232
253
|
});
|
|
233
254
|
}
|
|
234
255
|
function normalizeHeaders(raw) {
|
|
@@ -239,10 +260,39 @@ function normalizeHeaders(raw) {
|
|
|
239
260
|
}
|
|
240
261
|
return out;
|
|
241
262
|
}
|
|
242
|
-
|
|
263
|
+
function firstHeaderValue(v) {
|
|
264
|
+
const s = Array.isArray(v) ? v[0] : v;
|
|
265
|
+
return s?.split(",")[0].trim().toLowerCase() || void 0;
|
|
266
|
+
}
|
|
267
|
+
function requestOrigin(req) {
|
|
268
|
+
let proto = "http";
|
|
269
|
+
let host = req.headers.host ?? "localhost";
|
|
270
|
+
if (config.trustProxy) {
|
|
271
|
+
const fp = firstHeaderValue(req.headers["x-forwarded-proto"]);
|
|
272
|
+
if (fp === "http" || fp === "https") proto = fp;
|
|
273
|
+
const fh = firstHeaderValue(req.headers["x-forwarded-host"]);
|
|
274
|
+
if (fh && allHostChars(fh)) host = fh;
|
|
275
|
+
}
|
|
276
|
+
return `${proto}://${host}`;
|
|
277
|
+
}
|
|
278
|
+
function allHostChars(s) {
|
|
279
|
+
for (let i = 0; i < s.length; i++) {
|
|
280
|
+
const c = s.charCodeAt(i);
|
|
281
|
+
const ok = c >= 48 && c <= 57 || // 0-9
|
|
282
|
+
c >= 97 && c <= 122 || // a-z
|
|
283
|
+
c === 46 || // .
|
|
284
|
+
c === 45 || // -
|
|
285
|
+
c === 58 || // :
|
|
286
|
+
c === 91 || // [
|
|
287
|
+
c === 93;
|
|
288
|
+
if (!ok) return false;
|
|
289
|
+
}
|
|
290
|
+
return s.length > 0;
|
|
291
|
+
}
|
|
292
|
+
async function toWebRequest(req, url) {
|
|
243
293
|
const method = (req.method ?? "GET").toUpperCase();
|
|
244
294
|
const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
|
|
245
|
-
return new Request(
|
|
295
|
+
return new Request(url, {
|
|
246
296
|
method,
|
|
247
297
|
headers: normalizeHeaders(req.headers),
|
|
248
298
|
body: body ? new Uint8Array(body) : null
|
|
@@ -250,52 +300,44 @@ async function toWebRequest(req, host) {
|
|
|
250
300
|
}
|
|
251
301
|
var apiFetch = null;
|
|
252
302
|
var apiLoadPromise = null;
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
JSON.stringify({ error: "No API routes compiled" }),
|
|
256
|
-
{ status: 503, headers: { "content-type": "application/json" } }
|
|
257
|
-
);
|
|
258
|
-
}
|
|
259
|
-
function failedApiFetch() {
|
|
260
|
-
return async () => new Response(
|
|
261
|
-
JSON.stringify({ error: "API failed to load" }),
|
|
262
|
-
{ status: 500, headers: { "content-type": "application/json" } }
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
async function loadApiFetch() {
|
|
303
|
+
var apiLoadError = null;
|
|
304
|
+
async function ensureApiFetch() {
|
|
266
305
|
if (apiFetch) return apiFetch;
|
|
267
306
|
if (apiLoadPromise) return apiLoadPromise;
|
|
307
|
+
const entry = config.apiEntry;
|
|
268
308
|
apiLoadPromise = (async () => {
|
|
269
|
-
const entry = resolveApiEntry();
|
|
270
|
-
if (!entry) {
|
|
271
|
-
try {
|
|
272
|
-
await import(pathToFileURL(config.apiEntry).href);
|
|
273
|
-
} catch (e) {
|
|
274
|
-
const tag = process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
|
|
275
|
-
console.warn(`
|
|
276
|
-
${tag} failed to load handler for /api:`, e);
|
|
277
|
-
}
|
|
278
|
-
apiFetch = noApiFetch();
|
|
279
|
-
return apiFetch;
|
|
280
|
-
}
|
|
281
309
|
try {
|
|
282
310
|
const mod = await import(pathToFileURL(entry).href);
|
|
283
|
-
if (typeof mod.fetch
|
|
284
|
-
|
|
285
|
-
} else {
|
|
286
|
-
apiFetch = failedApiFetch();
|
|
311
|
+
if (typeof mod.fetch !== "function") {
|
|
312
|
+
throw new Error(`${path.relative(process.cwd(), entry)} does not export a fetch function`);
|
|
287
313
|
}
|
|
288
|
-
|
|
289
|
-
|
|
314
|
+
apiFetch = mod.fetch;
|
|
315
|
+
apiLoadError = null;
|
|
316
|
+
return apiFetch;
|
|
317
|
+
} catch (e) {
|
|
318
|
+
apiLoadError = e;
|
|
319
|
+
apiLoadPromise = null;
|
|
320
|
+
return null;
|
|
290
321
|
}
|
|
291
|
-
return apiFetch;
|
|
292
322
|
})();
|
|
293
323
|
return apiLoadPromise;
|
|
294
324
|
}
|
|
295
325
|
function sendJson(res, status, body, extra = {}) {
|
|
296
|
-
res.writeHead(status, {
|
|
326
|
+
res.writeHead(status, {
|
|
327
|
+
"content-type": "application/json; charset=utf-8",
|
|
328
|
+
"x-content-type-options": "nosniff",
|
|
329
|
+
...extra
|
|
330
|
+
});
|
|
297
331
|
res.end(JSON.stringify(body));
|
|
298
332
|
}
|
|
333
|
+
function sendText(res, status, text, extra = {}) {
|
|
334
|
+
res.writeHead(status, {
|
|
335
|
+
"content-type": "text/plain; charset=utf-8",
|
|
336
|
+
"x-content-type-options": "nosniff",
|
|
337
|
+
...extra
|
|
338
|
+
});
|
|
339
|
+
res.end(text);
|
|
340
|
+
}
|
|
299
341
|
async function sendWebResponse(res, webRes, method) {
|
|
300
342
|
const headers = {};
|
|
301
343
|
webRes.headers.forEach((v, k) => {
|
|
@@ -327,98 +369,220 @@ function publicErrorMessage(e) {
|
|
|
327
369
|
}
|
|
328
370
|
async function handleApiRequest(req, res) {
|
|
329
371
|
const method = (req.method ?? "GET").toUpperCase();
|
|
330
|
-
const
|
|
372
|
+
const fetchFn = await ensureApiFetch();
|
|
373
|
+
if (!fetchFn) {
|
|
374
|
+
const pathLabel = (req.url ?? "/api").split("?")[0] || "/api";
|
|
375
|
+
console.error(`
|
|
376
|
+
${warnTag()} failed to load handler for ${pathLabel}:`, apiLoadError);
|
|
377
|
+
return sendJson(res, 503, {
|
|
378
|
+
error: "failed to load handler",
|
|
379
|
+
path: pathLabel,
|
|
380
|
+
detail: apiLoadError instanceof Error ? apiLoadError.message : String(apiLoadError ?? "API bundle not found")
|
|
381
|
+
});
|
|
382
|
+
}
|
|
331
383
|
let parsedUrl;
|
|
332
384
|
try {
|
|
333
|
-
parsedUrl = new URL(
|
|
385
|
+
parsedUrl = new URL(`${requestOrigin(req)}${req.url ?? "/"}`);
|
|
334
386
|
} catch {
|
|
335
387
|
return sendJson(res, 400, { error: "Bad request URL" });
|
|
336
388
|
}
|
|
337
|
-
|
|
338
|
-
|
|
389
|
+
const declared = Number(req.headers["content-length"]);
|
|
390
|
+
if (Number.isFinite(declared) && declared > config.bodySizeLimit) {
|
|
391
|
+
return sendJson(res, 413, { error: "Request body too large" }, { connection: "close" });
|
|
339
392
|
}
|
|
340
|
-
await loadApiFetch();
|
|
341
393
|
let webReq;
|
|
342
394
|
try {
|
|
343
|
-
webReq = await toWebRequest(req,
|
|
395
|
+
webReq = await toWebRequest(req, parsedUrl.href);
|
|
344
396
|
} catch (e) {
|
|
345
|
-
|
|
346
|
-
|
|
397
|
+
if (e instanceof HttpError) {
|
|
398
|
+
return sendJson(res, e.status, { error: e.message }, { connection: "close" });
|
|
399
|
+
}
|
|
400
|
+
return sendJson(res, 400, { error: e?.message ?? "Bad request" });
|
|
347
401
|
}
|
|
348
|
-
const ctx = {
|
|
349
|
-
p
|
|
350
|
-
|
|
351
|
-
|
|
402
|
+
const ctx = {
|
|
403
|
+
waitUntil(p) {
|
|
404
|
+
p.catch(() => {
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
};
|
|
352
408
|
try {
|
|
353
409
|
const webRes = await withTimeout(
|
|
354
|
-
|
|
410
|
+
fetchFn(webReq, process.env, ctx),
|
|
355
411
|
config.handlerTimeout
|
|
356
412
|
);
|
|
357
413
|
await sendWebResponse(res, webRes, method);
|
|
358
414
|
} catch (e) {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
${
|
|
415
|
+
console.error(
|
|
416
|
+
`
|
|
417
|
+
${warnTag()} failed to handle ${method} ${parsedUrl.pathname}:`,
|
|
418
|
+
e
|
|
419
|
+
);
|
|
362
420
|
if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
|
|
363
421
|
else res.end();
|
|
364
422
|
}
|
|
365
423
|
}
|
|
366
424
|
var MIME_TYPES = {
|
|
367
425
|
".html": "text/html; charset=utf-8",
|
|
368
|
-
".js": "
|
|
369
|
-
".mjs": "
|
|
370
|
-
".css": "text/css",
|
|
371
|
-
".json": "application/json",
|
|
426
|
+
".js": "text/javascript; charset=utf-8",
|
|
427
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
428
|
+
".css": "text/css; charset=utf-8",
|
|
429
|
+
".json": "application/json; charset=utf-8",
|
|
372
430
|
".png": "image/png",
|
|
373
431
|
".jpg": "image/jpeg",
|
|
374
432
|
".jpeg": "image/jpeg",
|
|
375
433
|
".gif": "image/gif",
|
|
376
|
-
".svg": "image/svg+xml",
|
|
434
|
+
".svg": "image/svg+xml; charset=utf-8",
|
|
377
435
|
".ico": "image/x-icon",
|
|
378
436
|
".webp": "image/webp",
|
|
379
437
|
".avif": "image/avif",
|
|
380
438
|
".woff": "font/woff",
|
|
381
439
|
".woff2": "font/woff2",
|
|
382
440
|
".ttf": "font/ttf",
|
|
441
|
+
".otf": "font/otf",
|
|
383
442
|
".eot": "application/vnd.ms-fontobject",
|
|
384
|
-
".txt": "text/plain",
|
|
385
|
-
".xml": "application/xml",
|
|
386
|
-
".webmanifest": "application/manifest+json",
|
|
387
|
-
".map": "application/json"
|
|
443
|
+
".txt": "text/plain; charset=utf-8",
|
|
444
|
+
".xml": "application/xml; charset=utf-8",
|
|
445
|
+
".webmanifest": "application/manifest+json; charset=utf-8",
|
|
446
|
+
".map": "application/json; charset=utf-8",
|
|
447
|
+
".pdf": "application/pdf",
|
|
448
|
+
".wasm": "application/wasm",
|
|
449
|
+
".mp4": "video/mp4",
|
|
450
|
+
".webm": "video/webm",
|
|
451
|
+
".mp3": "audio/mpeg"
|
|
388
452
|
};
|
|
453
|
+
var ASSET_EXTS = /* @__PURE__ */ new Set([
|
|
454
|
+
".js",
|
|
455
|
+
".mjs",
|
|
456
|
+
".css",
|
|
457
|
+
".map",
|
|
458
|
+
".json",
|
|
459
|
+
".txt",
|
|
460
|
+
".xml",
|
|
461
|
+
".webmanifest",
|
|
462
|
+
".png",
|
|
463
|
+
".jpg",
|
|
464
|
+
".jpeg",
|
|
465
|
+
".gif",
|
|
466
|
+
".svg",
|
|
467
|
+
".ico",
|
|
468
|
+
".webp",
|
|
469
|
+
".avif",
|
|
470
|
+
".woff",
|
|
471
|
+
".woff2",
|
|
472
|
+
".ttf",
|
|
473
|
+
".otf",
|
|
474
|
+
".eot",
|
|
475
|
+
".pdf",
|
|
476
|
+
".wasm",
|
|
477
|
+
".mp4",
|
|
478
|
+
".webm",
|
|
479
|
+
".mp3"
|
|
480
|
+
]);
|
|
481
|
+
var COMPRESSIBLE_EXTS = /* @__PURE__ */ new Set([
|
|
482
|
+
".html",
|
|
483
|
+
".js",
|
|
484
|
+
".mjs",
|
|
485
|
+
".css",
|
|
486
|
+
".json",
|
|
487
|
+
".svg",
|
|
488
|
+
".txt",
|
|
489
|
+
".xml",
|
|
490
|
+
".webmanifest",
|
|
491
|
+
".map"
|
|
492
|
+
]);
|
|
389
493
|
function getETag(stat) {
|
|
390
494
|
return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
|
|
391
495
|
}
|
|
496
|
+
function isHashedAsset(relPath) {
|
|
497
|
+
const HASH_LEN = 8;
|
|
498
|
+
if (!relPath.startsWith("assets/")) return false;
|
|
499
|
+
const stem = path.posix.basename(relPath, path.posix.extname(relPath));
|
|
500
|
+
if (stem.length <= HASH_LEN + 1) return false;
|
|
501
|
+
const sep = stem[stem.length - HASH_LEN - 1];
|
|
502
|
+
if (sep !== "-" && sep !== ".") return false;
|
|
503
|
+
let hasDigit = false;
|
|
504
|
+
for (const ch of stem.slice(-HASH_LEN)) {
|
|
505
|
+
const digit = ch >= "0" && ch <= "9";
|
|
506
|
+
const ok = digit || ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_" || ch === "-";
|
|
507
|
+
if (!ok) return false;
|
|
508
|
+
if (digit) hasDigit = true;
|
|
509
|
+
}
|
|
510
|
+
return hasDigit;
|
|
511
|
+
}
|
|
512
|
+
function etagMatches(header, etag) {
|
|
513
|
+
if (!header) return false;
|
|
514
|
+
if (header.trim() === "*") return true;
|
|
515
|
+
const strip = (t) => {
|
|
516
|
+
const s = t.trim();
|
|
517
|
+
return s.startsWith("W/") ? s.slice(2) : s;
|
|
518
|
+
};
|
|
519
|
+
const mine = strip(etag);
|
|
520
|
+
return header.split(",").some((t) => strip(t) === mine);
|
|
521
|
+
}
|
|
522
|
+
function pickEncoding(req) {
|
|
523
|
+
const header = String(req.headers["accept-encoding"] ?? "");
|
|
524
|
+
const accepted = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const part of header.split(",")) {
|
|
526
|
+
const [name, ...params] = part.trim().split(";");
|
|
527
|
+
if (!name) continue;
|
|
528
|
+
const qp = params.map((s) => s.trim()).find((s) => s.startsWith("q="));
|
|
529
|
+
const q = qp ? parseFloat(qp.slice(2)) : 1;
|
|
530
|
+
accepted.set(name.trim().toLowerCase(), isNaN(q) ? 1 : q);
|
|
531
|
+
}
|
|
532
|
+
if ((accepted.get("br") ?? 0) > 0) return "br";
|
|
533
|
+
if ((accepted.get("gzip") ?? 0) > 0) return "gzip";
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
392
536
|
async function sendFile(filePath, req, res, status = 200) {
|
|
393
537
|
const ext = path.extname(filePath).toLowerCase();
|
|
394
|
-
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
395
538
|
let stat;
|
|
396
539
|
try {
|
|
397
540
|
stat = await fs.promises.stat(filePath);
|
|
398
541
|
} catch {
|
|
399
|
-
res
|
|
400
|
-
res.end("Not found");
|
|
542
|
+
sendText(res, 404, "Not found");
|
|
401
543
|
return;
|
|
402
544
|
}
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
545
|
+
const rel = path.relative(config.distDir, filePath).split(path.sep).join("/");
|
|
546
|
+
const compressible = config.compress && COMPRESSIBLE_EXTS.has(ext);
|
|
547
|
+
const encoding = compressible && stat.size >= 1024 ? pickEncoding(req) : null;
|
|
548
|
+
const etag = `"${getETag(stat)}${encoding ? `-${encoding}` : ""}"`;
|
|
549
|
+
const validators = {
|
|
550
|
+
"Cache-Control": isHashedAsset(rel) ? "public, max-age=31536000, immutable" : "no-cache",
|
|
551
|
+
ETag: etag,
|
|
552
|
+
"X-Content-Type-Options": "nosniff"
|
|
553
|
+
};
|
|
554
|
+
if (compressible) validators["Vary"] = "Accept-Encoding";
|
|
555
|
+
if (status === 200 && etagMatches(req.headers["if-none-match"], etag)) {
|
|
556
|
+
res.writeHead(304, validators);
|
|
406
557
|
res.end();
|
|
407
558
|
return;
|
|
408
559
|
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
"Content-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
560
|
+
const headers = {
|
|
561
|
+
...validators,
|
|
562
|
+
"Content-Type": MIME_TYPES[ext] ?? "application/octet-stream"
|
|
563
|
+
};
|
|
564
|
+
if (encoding) headers["Content-Encoding"] = encoding;
|
|
565
|
+
else headers["Content-Length"] = stat.size;
|
|
566
|
+
res.writeHead(status, headers);
|
|
416
567
|
if (req.method === "HEAD") {
|
|
417
568
|
res.end();
|
|
418
569
|
return;
|
|
419
570
|
}
|
|
571
|
+
const source = createReadStream(filePath);
|
|
420
572
|
try {
|
|
421
|
-
|
|
573
|
+
if (encoding === "br") {
|
|
574
|
+
await pipeline(
|
|
575
|
+
source,
|
|
576
|
+
zlib.createBrotliCompress({
|
|
577
|
+
params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 }
|
|
578
|
+
}),
|
|
579
|
+
res
|
|
580
|
+
);
|
|
581
|
+
} else if (encoding === "gzip") {
|
|
582
|
+
await pipeline(source, zlib.createGzip(), res);
|
|
583
|
+
} else {
|
|
584
|
+
await pipeline(source, res);
|
|
585
|
+
}
|
|
422
586
|
} catch {
|
|
423
587
|
}
|
|
424
588
|
}
|
|
@@ -433,27 +597,47 @@ async function trySendFile(filePath, req, res, status = 200) {
|
|
|
433
597
|
}
|
|
434
598
|
}
|
|
435
599
|
async function serveStatic(req, res, next) {
|
|
436
|
-
const
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
if (await trySendFile(shellIndex, req, res)) return;
|
|
600
|
+
const rawPath = getRawPath(req.url ?? "/");
|
|
601
|
+
const stripped = stripBase(rawPath);
|
|
602
|
+
if (stripped === null) return next();
|
|
603
|
+
let pathname;
|
|
604
|
+
try {
|
|
605
|
+
pathname = decodeURIComponent(stripped);
|
|
606
|
+
} catch {
|
|
607
|
+
return sendText(res, 400, "Bad request");
|
|
608
|
+
}
|
|
609
|
+
const abs = resolveInDist(pathname);
|
|
610
|
+
if (abs === null) return sendText(res, 400, "Bad request");
|
|
611
|
+
if (isDenied(pathname)) return sendText(res, 404, "Not found");
|
|
612
|
+
const ext = path.extname(pathname).toLowerCase();
|
|
613
|
+
let stat = null;
|
|
614
|
+
try {
|
|
615
|
+
stat = await fs.promises.stat(abs);
|
|
616
|
+
} catch {
|
|
454
617
|
}
|
|
618
|
+
if (stat?.isFile()) {
|
|
619
|
+
if (await trySendFile(abs, req, res)) return;
|
|
620
|
+
} else if (stat?.isDirectory()) {
|
|
621
|
+
if (await trySendFile(path.join(abs, "index.html"), req, res)) return;
|
|
622
|
+
}
|
|
623
|
+
if (!ext && pathname !== "/" && await trySendFile(`${abs.replace(/[\\/]+$/, "")}.html`, req, res)) return;
|
|
624
|
+
if (ASSET_EXTS.has(ext)) return sendText(res, 404, "Not found");
|
|
625
|
+
if (await trySendFile(path.join(config.distDir, "200.html"), req, res)) return;
|
|
455
626
|
if (await trySendFile(path.join(config.distDir, "404.html"), req, res, 404)) return;
|
|
456
627
|
if (await trySendFile(path.join(config.distDir, "index.html"), req, res)) return;
|
|
628
|
+
return sendText(res, 404, "Not found");
|
|
629
|
+
}
|
|
630
|
+
async function gateway(req, res, next) {
|
|
631
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
632
|
+
const rawPath = getRawPath(req.url ?? "/");
|
|
633
|
+
if (toApiPath(rawPath) !== null) return handleApiRequest(req, res);
|
|
634
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
635
|
+
return sendText(res, 405, "Method Not Allowed", { Allow: "GET, HEAD" });
|
|
636
|
+
}
|
|
637
|
+
if (rawPath === "/__health" || stripBase(rawPath) === "/__health") {
|
|
638
|
+
return sendText(res, 200, "ok", { "Cache-Control": "no-store" });
|
|
639
|
+
}
|
|
640
|
+
if (!rawPath.startsWith("/")) return sendText(res, 400, "Bad request");
|
|
457
641
|
next();
|
|
458
642
|
}
|
|
459
643
|
function compose(middlewares) {
|
|
@@ -477,28 +661,39 @@ function compose(middlewares) {
|
|
|
477
661
|
async function start() {
|
|
478
662
|
loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
|
|
479
663
|
refreshConfig();
|
|
664
|
+
if (config.legacyBase) {
|
|
665
|
+
console.warn(
|
|
666
|
+
`
|
|
667
|
+
${warnTag()} reading base from the unprefixed BASE variable. Other tools set it too; use BINI_BASE instead.`
|
|
668
|
+
);
|
|
669
|
+
}
|
|
480
670
|
if (!fs.existsSync(config.distDir)) {
|
|
481
|
-
console.error(
|
|
671
|
+
console.error(
|
|
672
|
+
`
|
|
482
673
|
${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
|
|
483
674
|
Run ${C.CYAN}npm run build${C.RESET} first.
|
|
484
|
-
`
|
|
675
|
+
`
|
|
676
|
+
);
|
|
485
677
|
process.exit(1);
|
|
486
678
|
}
|
|
487
|
-
|
|
488
|
-
|
|
679
|
+
let port;
|
|
680
|
+
if (config.portExplicit) {
|
|
681
|
+
port = config.defaultPort;
|
|
682
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
683
|
+
console.error(`
|
|
684
|
+
${C.RED}\u2717${C.RESET} invalid port: ${getEnvVar("PORT")}
|
|
685
|
+
`);
|
|
686
|
+
process.exit(1);
|
|
687
|
+
}
|
|
688
|
+
} else {
|
|
689
|
+
port = await findFreePort(config.defaultPort, config.host);
|
|
690
|
+
}
|
|
489
691
|
const handler = compose([
|
|
490
|
-
|
|
491
|
-
if (!isApiRequest(req.url)) return next();
|
|
492
|
-
await handleApiRequest(req, res);
|
|
493
|
-
},
|
|
692
|
+
gateway,
|
|
494
693
|
serveStatic,
|
|
495
|
-
(_req, res) =>
|
|
496
|
-
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
497
|
-
res.end("Not found");
|
|
498
|
-
}
|
|
694
|
+
(_req, res) => sendText(res, 404, "Not found")
|
|
499
695
|
]);
|
|
500
696
|
const server = http.createServer((req, res) => {
|
|
501
|
-
res.setHeader("Connection", "keep-alive");
|
|
502
697
|
handler(req, res).catch(() => {
|
|
503
698
|
if (!res.headersSent) {
|
|
504
699
|
res.writeHead(500);
|
|
@@ -509,14 +704,45 @@ async function start() {
|
|
|
509
704
|
server.keepAliveTimeout = 65e3;
|
|
510
705
|
server.headersTimeout = 66e3;
|
|
511
706
|
server.maxHeadersCount = 2e3;
|
|
707
|
+
server.once("error", (err) => {
|
|
708
|
+
if (err.code === "EADDRINUSE") {
|
|
709
|
+
console.error(
|
|
710
|
+
`
|
|
711
|
+
${C.RED}\u2717${C.RESET} port ${port} is already in use on ${config.host}.
|
|
712
|
+
`
|
|
713
|
+
);
|
|
714
|
+
} else {
|
|
715
|
+
console.error(`
|
|
716
|
+
${C.RED}\u2717${C.RESET} server error:`, err);
|
|
717
|
+
}
|
|
718
|
+
process.exit(1);
|
|
719
|
+
});
|
|
512
720
|
startKeyboardLoop(port);
|
|
513
|
-
server.listen(port,
|
|
721
|
+
server.listen(port, config.host, () => printBanner(port));
|
|
722
|
+
let shuttingDown = false;
|
|
514
723
|
const shutdown = () => {
|
|
724
|
+
if (shuttingDown) process.exit(1);
|
|
725
|
+
shuttingDown = true;
|
|
515
726
|
server.close(() => process.exit(0));
|
|
516
|
-
|
|
727
|
+
server.closeIdleConnections();
|
|
728
|
+
setInterval(() => server.closeIdleConnections(), 1e3).unref();
|
|
729
|
+
setTimeout(() => {
|
|
730
|
+
server.closeAllConnections();
|
|
731
|
+
setTimeout(() => process.exit(1), 1e3).unref();
|
|
732
|
+
}, 1e4).unref();
|
|
517
733
|
};
|
|
518
734
|
process.on("SIGTERM", shutdown);
|
|
519
735
|
process.on("SIGINT", shutdown);
|
|
736
|
+
process.on("unhandledRejection", (reason) => {
|
|
737
|
+
console.error(`
|
|
738
|
+
${warnTag()} unhandledRejection:`, reason);
|
|
739
|
+
process.exit(1);
|
|
740
|
+
});
|
|
741
|
+
process.on("uncaughtException", (err) => {
|
|
742
|
+
console.error(`
|
|
743
|
+
${warnTag()} uncaughtException:`, err);
|
|
744
|
+
process.exit(1);
|
|
745
|
+
});
|
|
520
746
|
}
|
|
521
747
|
export {
|
|
522
748
|
start
|