bini-server 2.0.0 → 2.0.2

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/dist/cli.js CHANGED
@@ -15,7 +15,7 @@ __export(src_exports, {
15
15
  start: () => start
16
16
  });
17
17
  import http from "http";
18
- import fs from "fs";
18
+ import fs, { createReadStream } from "fs";
19
19
  import path from "path";
20
20
  import os from "os";
21
21
  import net from "net";
@@ -23,98 +23,120 @@ import crypto from "crypto";
23
23
  import readline from "readline";
24
24
  import { exec } from "child_process";
25
25
  import { pathToFileURL } from "url";
26
+ import { Readable } from "stream";
26
27
  import { pipeline } from "stream/promises";
27
- import { createReadStream } from "fs";
28
- function detectEnvFiles(root) {
29
- const nodeEnv = process.env.NODE_ENV ?? "production";
30
- return [
31
- ".env.local",
32
- `.env.${nodeEnv}.local`,
33
- `.env.${nodeEnv}`,
34
- ".env"
35
- ].filter((f) => fs.existsSync(path.join(root, f)));
36
- }
28
+ import { loadEnvFiles, envFilesFor } from "bini-env/node";
37
29
  function getEnvVar(key, defaultValue) {
38
- const biniKey = `BINI_${key}`;
39
- if (process.env[biniKey] !== void 0) return process.env[biniKey];
40
- const viteKey = `VITE_${key}`;
41
- if (process.env[viteKey] !== void 0) return process.env[viteKey];
42
- if (process.env[key] !== void 0) return process.env[key];
43
- return defaultValue;
44
- }
45
- function getEnvVarBoolean(key, defaultValue) {
46
- const value = getEnvVar(key);
47
- if (value === void 0) return defaultValue;
48
- return value !== "false" && value !== "0" && value !== "";
30
+ return process.env[`BINI_${key}`] ?? process.env[`VITE_${key}`] ?? process.env[key] ?? defaultValue;
49
31
  }
50
32
  function getEnvVarNumber(key, defaultValue) {
51
- const value = getEnvVar(key);
52
- if (value === void 0) return defaultValue;
53
- const parsed = parseInt(value, 10);
54
- return isNaN(parsed) ? defaultValue : parsed;
33
+ const raw = getEnvVar(key);
34
+ if (raw === void 0) return defaultValue;
35
+ const n = parseInt(raw, 10);
36
+ return isNaN(n) ? defaultValue : n;
37
+ }
38
+ function readConfig() {
39
+ const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
40
+ const apiDir = path.join(distDir, "api");
41
+ const rawBase = (getEnvVar("BASE") ?? "").trim();
42
+ const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + rawBase.replace(/^\/+|\/+$/g, "");
43
+ return {
44
+ defaultPort: getEnvVarNumber("PORT", 3e3),
45
+ bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
46
+ handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
47
+ bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
48
+ distDir,
49
+ compiledApiDir: apiDir + path.sep,
50
+ apiDir,
51
+ apiEntry: path.join(apiDir, "index.mjs"),
52
+ base,
53
+ isProd: process.env.NODE_ENV === "production"
54
+ };
55
+ }
56
+ function refreshConfig() {
57
+ config = readConfig();
58
+ }
59
+ function resolveApiEntry() {
60
+ return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
61
+ }
62
+ function stripBase(pathname) {
63
+ const { base } = config;
64
+ if (!base) return pathname || "/";
65
+ if (pathname === base || pathname === base + "/") return "/";
66
+ if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
67
+ return null;
68
+ }
69
+ function toApiPath(pathname) {
70
+ let p = pathname;
71
+ const { base } = config;
72
+ if (base) {
73
+ if (p === base || p.startsWith(base + "/")) p = p.slice(base.length) || "/";
74
+ else return null;
75
+ }
76
+ if (p === "/api") return "/";
77
+ if (p.startsWith("/api/")) return p.slice(4);
78
+ return null;
79
+ }
80
+ function isApiRequest(url) {
81
+ if (!url) return false;
82
+ try {
83
+ return toApiPath(new URL(url, "http://localhost").pathname) !== null;
84
+ } catch {
85
+ return false;
86
+ }
55
87
  }
56
88
  function scanShellRoutes() {
57
- const shellRoutes = /* @__PURE__ */ new Set();
58
- const rootDir = DIST_DIR;
59
- function walkDir(dir, currentPath) {
89
+ const routes = /* @__PURE__ */ new Set();
90
+ function walk(dir, prefix) {
91
+ let entries;
60
92
  try {
61
- const entries = fs.readdirSync(dir, { withFileTypes: true });
62
- for (const entry of entries) {
63
- if (!entry.isDirectory()) continue;
64
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
65
- const fullPath = path.join(dir, entry.name);
66
- const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
67
- if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
68
- const indexPath = path.join(fullPath, "index.html");
69
- if (fs.existsSync(indexPath)) {
70
- shellRoutes.add(`/${routePath}`);
71
- }
72
- }
73
- walkDir(fullPath, routePath);
74
- }
93
+ entries = fs.readdirSync(dir, { withFileTypes: true });
75
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);
76
106
  }
77
107
  }
78
- try {
79
- walkDir(rootDir, "");
80
- } catch {
81
- }
82
- return shellRoutes;
108
+ walk(config.distDir, "");
109
+ return routes;
83
110
  }
84
111
  function getShellRoutes() {
85
- if (!shellRouteCache) {
86
- shellRouteCache = scanShellRoutes();
87
- }
88
- return shellRouteCache;
112
+ return shellRouteCache ??= scanShellRoutes();
89
113
  }
90
114
  function findMatchingShellRoute(pathname) {
91
- const shellRoutes = getShellRoutes();
92
- const cleanPath = pathname.replace(/^\/|\/$/g, "");
93
- const pathSegments = cleanPath.split("/").filter(Boolean);
94
- for (const shellRoute of shellRoutes) {
95
- const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
96
- const shellSegments = cleanShell.split("/").filter(Boolean);
97
- if (shellSegments.length !== pathSegments.length) continue;
98
- let matches = true;
99
- for (let i = 0; i < shellSegments.length; i++) {
100
- const segment = shellSegments[i];
101
- if (segment.startsWith("[") && segment.endsWith("]")) {
102
- continue;
103
- }
104
- if (segment !== pathSegments[i]) {
105
- matches = false;
106
- break;
107
- }
108
- }
109
- if (matches) {
110
- return shellRoute;
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;
111
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;
112
133
  }
113
134
  return null;
114
135
  }
115
136
  function getNetworkIp() {
116
137
  const ifaces = os.networkInterfaces();
117
138
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
139
+ const candidates = [];
118
140
  for (const name in ifaces) {
119
141
  if (SKIP.test(name)) continue;
120
142
  for (const iface of ifaces[name] ?? []) {
@@ -123,32 +145,31 @@ function getNetworkIp() {
123
145
  if (a === 169 && b === 254) continue;
124
146
  const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
125
147
  if (isPrivate) return iface.address;
148
+ candidates.push(iface.address);
126
149
  }
127
150
  }
128
- for (const name in ifaces) {
129
- if (SKIP.test(name)) continue;
130
- for (const iface of ifaces[name] ?? []) {
131
- if (!iface.internal && iface.family === "IPv4") return iface.address;
132
- }
133
- }
134
- return null;
151
+ return candidates[0] ?? null;
135
152
  }
136
153
  function printBanner(port) {
137
- const envFiles2 = detectEnvFiles(process.cwd());
154
+ const envFiles2 = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
138
155
  const networkIp = getNetworkIp();
139
156
  console.log(`
140
- ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
157
+ ${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
141
158
  if (envFiles2.length > 0) {
142
- console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles2.join(", ")}`);
159
+ const rel = envFiles2.map((f) => path.relative(process.cwd(), f));
160
+ console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
143
161
  }
144
162
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
145
163
  if (networkIp) {
146
164
  console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
147
165
  }
166
+ if (config.base) {
167
+ console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
168
+ }
148
169
  console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
149
170
  console.log("");
150
171
  }
151
- async function isPortFree(port) {
172
+ function isPortFree(port) {
152
173
  return new Promise((resolve) => {
153
174
  const server = net.createServer();
154
175
  server.once("error", () => resolve(false));
@@ -158,13 +179,8 @@ async function isPortFree(port) {
158
179
  }
159
180
  async function findFreePort(start3) {
160
181
  for (let port = start3; port < start3 + 100; port++) {
161
- if (await isPortFree(port)) {
162
- if (port !== start3) {
163
- console.log(`
164
- ${C.YELLOW}\u26A0${C.RESET} Port ${start3} in use \u2014 using ${port} instead.`);
165
- }
166
- return port;
167
- }
182
+ if (await isPortFree(port)) return port;
183
+ console.log(`Port ${port} is in use, trying another one...`);
168
184
  }
169
185
  throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
170
186
  }
@@ -181,7 +197,7 @@ function startKeyboardLoop(port) {
181
197
  console.log("");
182
198
  break;
183
199
  case "o": {
184
- const url = `http://localhost:${port}/`;
200
+ const url = `http://localhost:${port}${config.base || ""}/`;
185
201
  const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
186
202
  exec(cmd);
187
203
  break;
@@ -192,102 +208,6 @@ function startKeyboardLoop(port) {
192
208
  });
193
209
  rl.on("close", () => process.exit(0));
194
210
  }
195
- function getRouteCache() {
196
- if (!routeCache) {
197
- const start3 = Date.now();
198
- routeCache = scanApiRoutes(API_DIR);
199
- routeIndex.clear();
200
- for (let i = 0; i < routeCache.length; i++) {
201
- routeIndex.set(routeCache[i].routePath, routeCache[i]);
202
- }
203
- if (process.env.NODE_ENV === "development") {
204
- console.log(`[bini-server] API routes scanned in ${Date.now() - start3}ms`);
205
- }
206
- }
207
- return routeCache;
208
- }
209
- function scanApiRoutes(dir, baseRoute = "", depth = 0) {
210
- const routes = [];
211
- if (depth > 100 || !fs.existsSync(dir)) return routes;
212
- let entries;
213
- try {
214
- entries = fs.readdirSync(dir, { withFileTypes: true });
215
- } catch {
216
- return routes;
217
- }
218
- for (let i = 0; i < entries.length; i++) {
219
- const entry = entries[i];
220
- if (SKIP_PATTERN.test(entry.name)) continue;
221
- const fullPath = path.join(dir, entry.name);
222
- if (entry.isDirectory()) {
223
- const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
224
- const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
225
- const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
226
- const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
227
- for (let j = 0; j < childRoutes.length; j++) {
228
- routes.push(childRoutes[j]);
229
- }
230
- continue;
231
- }
232
- const ext = path.extname(entry.name);
233
- if (!API_EXTS.has(ext)) continue;
234
- const base = path.basename(entry.name, ext);
235
- const isCatchAll = base.startsWith("[...") && base.endsWith("]");
236
- const isDynamic = base.startsWith("[") && base.endsWith("]");
237
- let routePath;
238
- if (isCatchAll) routePath = `${baseRoute}/*`;
239
- else if (base === "index") routePath = baseRoute || "/";
240
- else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
241
- else routePath = `${baseRoute}/${base}`;
242
- routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
243
- }
244
- return routes;
245
- }
246
- function matchRoute(pattern, pathname) {
247
- const patParts = pattern.split("/").filter(Boolean);
248
- const urlParts = pathname.split("/").filter(Boolean);
249
- const isCatchAll = patParts[patParts.length - 1] === "*";
250
- if (isCatchAll) {
251
- const prefix = patParts.slice(0, -1);
252
- if (urlParts.length < prefix.length) return null;
253
- for (let i = 0; i < prefix.length; i++) {
254
- if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
255
- }
256
- return { "*": urlParts.slice(prefix.length).join("/") };
257
- }
258
- if (patParts.length !== urlParts.length) return null;
259
- const params = {};
260
- for (let i = 0; i < patParts.length; i++) {
261
- if (patParts[i].startsWith(":")) {
262
- const value = decodeURIComponent(urlParts[i]);
263
- if (value.includes("..") || value.includes("//")) return null;
264
- params[patParts[i].slice(1)] = value;
265
- } else if (patParts[i] !== urlParts[i]) {
266
- return null;
267
- }
268
- }
269
- return params;
270
- }
271
- async function importHandler(filePath) {
272
- let mtime = 0;
273
- try {
274
- mtime = fs.statSync(filePath).mtimeMs;
275
- } catch {
276
- return null;
277
- }
278
- const cached = moduleCache.get(filePath);
279
- if (cached?.mtime === mtime) return cached.handler;
280
- try {
281
- const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
282
- const handler = mod.default ?? null;
283
- moduleCache.set(filePath, { mtime, handler });
284
- return handler;
285
- } catch (e) {
286
- console.error(`[bini-api] import error: ${filePath}`, e?.message);
287
- moduleCache.delete(filePath);
288
- return null;
289
- }
290
- }
291
211
  function readBody(req) {
292
212
  return new Promise((resolve, reject) => {
293
213
  const chunks = [];
@@ -295,10 +215,10 @@ function readBody(req) {
295
215
  const timer = setTimeout(() => {
296
216
  req.destroy();
297
217
  reject(new Error("Request body timeout"));
298
- }, BODY_TIMEOUT);
218
+ }, config.bodyTimeout);
299
219
  req.on("data", (chunk) => {
300
220
  size += chunk.byteLength;
301
- if (size > BODY_SIZE_LIMIT) {
221
+ if (size > config.bodySizeLimit) {
302
222
  clearTimeout(timer);
303
223
  req.destroy();
304
224
  reject(new Error("Request body too large"));
@@ -324,117 +244,133 @@ function normalizeHeaders(raw) {
324
244
  }
325
245
  return out;
326
246
  }
327
- async function handleApiRequest(req, res, next) {
328
- if (req.method === "OPTIONS") {
329
- const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
330
- res.writeHead(204, headers);
247
+ async function toWebRequest(req, host) {
248
+ const method = (req.method ?? "GET").toUpperCase();
249
+ const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
250
+ return new Request(`http://${host}${req.url ?? "/"}`, {
251
+ method,
252
+ headers: normalizeHeaders(req.headers),
253
+ body: body ? new Uint8Array(body) : null
254
+ });
255
+ }
256
+ function noApiFetch() {
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() {
269
+ if (apiFetch) return apiFetch;
270
+ if (apiLoadPromise) return apiLoadPromise;
271
+ 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
+ try {
285
+ const mod = await import(pathToFileURL(entry).href);
286
+ if (typeof mod.fetch === "function") {
287
+ apiFetch = mod.fetch;
288
+ } else {
289
+ apiFetch = failedApiFetch();
290
+ }
291
+ } catch {
292
+ apiFetch = failedApiFetch();
293
+ }
294
+ return apiFetch;
295
+ })();
296
+ return apiLoadPromise;
297
+ }
298
+ function sendJson(res, status, body, extra = {}) {
299
+ res.writeHead(status, { "content-type": "application/json", ...extra });
300
+ res.end(JSON.stringify(body));
301
+ }
302
+ async function sendWebResponse(res, webRes, method) {
303
+ const headers = {};
304
+ webRes.headers.forEach((v, k) => {
305
+ if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
306
+ });
307
+ const cookies = webRes.headers.getSetCookie?.();
308
+ if (cookies && cookies.length > 0) headers["set-cookie"] = cookies;
309
+ res.writeHead(webRes.status, headers);
310
+ if (method === "HEAD" || !webRes.body) {
331
311
  res.end();
332
312
  return;
333
313
  }
334
- const routes = getRouteCache();
335
- const host = req.headers.host ?? "localhost";
336
- const rawUrl = `http://${host}${req.url ?? "/"}`;
314
+ try {
315
+ await pipeline(Readable.fromWeb(webRes.body), res);
316
+ } catch {
317
+ }
318
+ }
319
+ function withTimeout(p, ms) {
320
+ let timer;
321
+ return Promise.race([
322
+ p,
323
+ new Promise((_, reject) => {
324
+ timer = setTimeout(() => reject(new Error("Handler timeout")), ms);
325
+ })
326
+ ]).finally(() => clearTimeout(timer));
327
+ }
328
+ function publicErrorMessage(e) {
329
+ return config.isProd ? "Internal server error" : e instanceof Error ? e.message : String(e);
330
+ }
331
+ async function handleApiRequest(req, res) {
337
332
  const method = (req.method ?? "GET").toUpperCase();
333
+ const host = req.headers.host ?? "localhost";
338
334
  let parsedUrl;
339
335
  try {
340
- parsedUrl = new URL(rawUrl);
336
+ parsedUrl = new URL(`http://${host}${req.url ?? "/"}`);
341
337
  } catch {
342
- res.writeHead(400, { "Content-Type": "application/json" });
343
- res.end(JSON.stringify({ error: "Bad request URL" }));
344
- return;
345
- }
346
- const { pathname, search } = parsedUrl;
347
- let matchedRoute = null;
348
- let params = null;
349
- if (routeIndex.has(pathname)) {
350
- matchedRoute = routeIndex.get(pathname);
351
- params = {};
352
- } else {
353
- for (let i = 0; i < routes.length; i++) {
354
- const route = routes[i];
355
- params = matchRoute(route.routePath, pathname);
356
- if (params !== null) {
357
- matchedRoute = route;
358
- break;
359
- }
360
- }
361
- }
362
- if (!matchedRoute) {
363
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
364
- res.writeHead(404, { "Content-Type": "application/json", ...headers });
365
- res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
366
- return;
338
+ return sendJson(res, 400, { error: "Bad request URL" });
367
339
  }
368
- let body;
369
- if (!["GET", "HEAD"].includes(method)) {
370
- try {
371
- body = await readBody(req);
372
- } catch (e) {
373
- const status = e.message.includes("too large") ? 413 : 408;
374
- res.writeHead(status, { "Content-Type": "application/json" });
375
- res.end(JSON.stringify({ error: e.message }));
376
- return;
377
- }
340
+ if (toApiPath(parsedUrl.pathname) === null) {
341
+ return sendJson(res, 404, { error: "Not Found" });
378
342
  }
379
- const handler = await importHandler(matchedRoute.filePath);
380
- if (!handler) {
381
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
382
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
383
- res.end(JSON.stringify({ error: "Failed to load handler" }));
384
- return;
343
+ await loadApiFetch();
344
+ let webReq;
345
+ try {
346
+ webReq = await toWebRequest(req, host);
347
+ } catch (e) {
348
+ const message = e?.message ?? "Bad request";
349
+ return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
385
350
  }
386
- const normalizedHeaders = normalizeHeaders(req.headers);
387
- let webRes;
351
+ const ctx = { waitUntil(p) {
352
+ p.catch(() => {
353
+ });
354
+ } };
388
355
  try {
389
- if (typeof handler.fetch === "function") {
390
- const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
391
- webRes = await handler.fetch(new Request(honoUrl, {
392
- method,
393
- headers: normalizedHeaders,
394
- body: body ? new Uint8Array(body) : null
395
- }));
396
- } else if (typeof handler === "function") {
397
- const reqWithParams = new Request(rawUrl, {
398
- method,
399
- headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
400
- body: body ? new Uint8Array(body) : null
401
- });
402
- const result = await Promise.race([
403
- handler(reqWithParams),
404
- new Promise(
405
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
406
- )
407
- ]);
408
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
409
- status: 200,
410
- headers: { "Content-Type": "application/json" }
411
- });
412
- } else {
413
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
414
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
415
- res.end(JSON.stringify({ error: "Handler has no valid default export" }));
416
- return;
417
- }
356
+ const webRes = await withTimeout(
357
+ apiFetch(webReq, process.env, ctx),
358
+ config.handlerTimeout
359
+ );
360
+ await sendWebResponse(res, webRes, method);
418
361
  } catch (e) {
419
- console.error("[bini-api] handler error:", e?.message ?? e);
420
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
421
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
422
- res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
423
- return;
362
+ const tag = process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
363
+ console.error(`
364
+ ${tag} failed to handle ${method} ${parsedUrl.pathname}:`, e);
365
+ if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
366
+ else res.end();
424
367
  }
425
- const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
426
- webRes.headers.forEach((v, k) => {
427
- finalHeaders[k] = v;
428
- });
429
- res.writeHead(webRes.status, finalHeaders);
430
- res.end(Buffer.from(await webRes.arrayBuffer()));
431
368
  }
432
369
  function getETag(stat) {
433
370
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
434
371
  }
435
- async function sendFile(filePath, req, res) {
372
+ async function sendFile(filePath, req, res, status = 200) {
436
373
  const ext = path.extname(filePath).toLowerCase();
437
- const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
438
374
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
439
375
  let stat;
440
376
  try {
@@ -445,13 +381,13 @@ async function sendFile(filePath, req, res) {
445
381
  return;
446
382
  }
447
383
  const etag = getETag(stat);
448
- if (req.headers["if-none-match"] === etag) {
384
+ if (status === 200 && req.headers["if-none-match"] === etag) {
449
385
  res.writeHead(304);
450
386
  res.end();
451
387
  return;
452
388
  }
453
- res.writeHead(200, {
454
- "Content-Type": mimeType,
389
+ res.writeHead(status, {
390
+ "Content-Type": MIME_TYPES[ext] ?? "application/octet-stream",
455
391
  "Content-Length": stat.size,
456
392
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
457
393
  "ETag": etag,
@@ -466,50 +402,39 @@ async function sendFile(filePath, req, res) {
466
402
  } catch {
467
403
  }
468
404
  }
405
+ async function trySendFile(filePath, req, res, status = 200) {
406
+ try {
407
+ const stat = await fs.promises.stat(filePath);
408
+ if (!stat.isFile()) return false;
409
+ await sendFile(filePath, req, res, status);
410
+ return true;
411
+ } catch {
412
+ return false;
413
+ }
414
+ }
469
415
  async function serveStatic(req, res, next) {
470
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
471
- if (pathname.startsWith("/api")) return next();
416
+ const rawPathname = new URL(req.url ?? "/", "http://localhost").pathname;
417
+ if (toApiPath(rawPathname) !== null) return next();
418
+ const pathname = stripBase(rawPathname);
419
+ if (pathname === null) return next();
420
+ if (pathname.includes("\0") || pathname.split("/").some((s) => s === "..")) return next();
472
421
  const hasExtension = path.extname(pathname).length > 0;
473
422
  if (hasExtension) {
474
- const filePath = path.join(DIST_DIR, pathname);
475
- try {
476
- const stat = await fs.promises.stat(filePath);
477
- if (stat.isFile()) {
478
- await sendFile(filePath, req, res);
479
- return;
480
- }
481
- } catch {
482
- }
423
+ const filePath = path.join(config.distDir, pathname);
424
+ if (filePath.startsWith(config.compiledApiDir)) return next();
425
+ if (await trySendFile(filePath, req, res)) return;
483
426
  return next();
484
427
  }
485
- const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
486
- try {
487
- const stat = await fs.promises.stat(staticFilePath);
488
- if (stat.isFile()) {
489
- await sendFile(staticFilePath, req, res);
490
- return;
491
- }
492
- } catch {
493
- }
428
+ const staticIndex = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
429
+ if (await trySendFile(staticIndex, req, res)) return;
494
430
  const matchingShell = findMatchingShellRoute(pathname);
495
431
  if (matchingShell) {
496
- const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
497
- try {
498
- const stat = await fs.promises.stat(shellPath);
499
- if (stat.isFile()) {
500
- await sendFile(shellPath, req, res);
501
- return;
502
- }
503
- } catch {
504
- }
505
- }
506
- const indexPath = path.join(DIST_DIR, "index.html");
507
- try {
508
- await fs.promises.access(indexPath);
509
- await sendFile(indexPath, req, res);
510
- } catch {
511
- next();
432
+ const shellIndex = path.join(config.distDir, matchingShell, "index.html");
433
+ if (await trySendFile(shellIndex, req, res)) return;
512
434
  }
435
+ if (await trySendFile(path.join(config.distDir, "404.html"), req, res, 404)) return;
436
+ if (await trySendFile(path.join(config.distDir, "index.html"), req, res)) return;
437
+ next();
513
438
  }
514
439
  function compose(middlewares) {
515
440
  return async (req, res) => {
@@ -522,7 +447,7 @@ function compose(middlewares) {
522
447
  } catch (e) {
523
448
  if (!res.headersSent) {
524
449
  res.writeHead(500, { "Content-Type": "application/json" });
525
- res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
450
+ res.end(JSON.stringify({ error: publicErrorMessage(e) }));
526
451
  }
527
452
  }
528
453
  };
@@ -530,19 +455,21 @@ function compose(middlewares) {
530
455
  };
531
456
  }
532
457
  async function start() {
533
- if (!fs.existsSync(DIST_DIR)) {
458
+ loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
459
+ refreshConfig();
460
+ if (!fs.existsSync(config.distDir)) {
534
461
  console.error(`
535
- ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
462
+ ${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
536
463
  Run ${C.CYAN}npm run build${C.RESET} first.
537
464
  `);
538
465
  process.exit(1);
539
466
  }
540
467
  getShellRoutes();
541
- const port = await findFreePort(DEFAULT_PORT);
468
+ const port = await findFreePort(config.defaultPort);
542
469
  const handler = compose([
543
470
  async (req, res, next) => {
544
- if (!req.url?.startsWith("/api")) return next();
545
- await handleApiRequest(req, res, next);
471
+ if (!isApiRequest(req.url)) return next();
472
+ await handleApiRequest(req, res);
546
473
  },
547
474
  serveStatic,
548
475
  (_req, res) => {
@@ -563,9 +490,7 @@ async function start() {
563
490
  server.headersTimeout = 66e3;
564
491
  server.maxHeadersCount = 2e3;
565
492
  startKeyboardLoop(port);
566
- server.listen(port, "0.0.0.0", () => {
567
- printBanner(port);
568
- });
493
+ server.listen(port, "0.0.0.0", () => printBanner(port));
569
494
  const shutdown = () => {
570
495
  server.close(() => process.exit(0));
571
496
  setTimeout(() => process.exit(1), 1e4).unref();
@@ -573,40 +498,22 @@ async function start() {
573
498
  process.on("SIGTERM", shutdown);
574
499
  process.on("SIGINT", shutdown);
575
500
  }
576
- var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, CORS_ENABLED, C, shellRouteCache, routeCache, routeIndex, API_EXTS, CATCH_ALL_PATTERN, DYNAMIC_PATTERN, SKIP_PATTERN, moduleCache, CORS_HEADERS, MIME_TYPES;
501
+ var config, C, shellRouteCache, apiFetch, apiLoadPromise, MIME_TYPES;
577
502
  var init_src = __esm({
578
503
  "src/index.ts"() {
579
504
  "use strict";
580
- DEFAULT_PORT = getEnvVarNumber("PORT", 3e3);
581
- BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
582
- HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
583
- BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
584
- API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
585
- DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
586
- CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
505
+ config = readConfig();
587
506
  C = {
588
507
  CYAN: "\x1B[36m",
589
508
  RESET: "\x1B[0m",
590
509
  GREEN: "\x1B[32m",
591
510
  RED: "\x1B[31m",
592
511
  YELLOW: "\x1B[33m",
593
- BOLD: "\x1B[1m",
594
512
  DIM: "\x1B[2m"
595
513
  };
596
514
  shellRouteCache = null;
597
- routeCache = null;
598
- routeIndex = /* @__PURE__ */ new Map();
599
- API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
600
- CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
601
- DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
602
- SKIP_PATTERN = /^[_.]/;
603
- moduleCache = /* @__PURE__ */ new Map();
604
- CORS_HEADERS = {
605
- "Access-Control-Allow-Origin": "*",
606
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
607
- "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
608
- "Vary": "Origin"
609
- };
515
+ apiFetch = null;
516
+ apiLoadPromise = null;
610
517
  MIME_TYPES = {
611
518
  ".html": "text/html; charset=utf-8",
612
519
  ".js": "application/javascript",
@@ -650,3 +557,4 @@ start2().catch((err) => {
650
557
  console.error(err);
651
558
  process.exit(1);
652
559
  });
560
+ //# sourceMappingURL=cli.js.map