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