bini-server 1.0.10 → 2.0.1

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