bini-server 2.0.0 → 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/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,17 +23,9 @@ 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
30
  const biniKey = `BINI_${key}`;
39
31
  if (process.env[biniKey] !== void 0) return process.env[biniKey];
@@ -42,26 +34,53 @@ function getEnvVar(key, defaultValue) {
42
34
  if (process.env[key] !== void 0) return process.env[key];
43
35
  return defaultValue;
44
36
  }
45
- function getEnvVarBoolean(key, defaultValue) {
46
- const value = getEnvVar(key);
47
- if (value === void 0) return defaultValue;
48
- return value !== "false" && value !== "0" && value !== "";
49
- }
50
37
  function getEnvVarNumber(key, defaultValue) {
51
38
  const value = getEnvVar(key);
52
39
  if (value === void 0) return defaultValue;
53
40
  const parsed = parseInt(value, 10);
54
41
  return isNaN(parsed) ? defaultValue : parsed;
55
42
  }
43
+ function readConfig() {
44
+ const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
45
+ const apiDir = path.join(distDir, "api");
46
+ const apiEntry = path.join(apiDir, "index.mjs");
47
+ const rawBase = (getEnvVar("BASE") ?? "").trim();
48
+ const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + rawBase.replace(/^\/+|\/+$/g, "");
49
+ return {
50
+ defaultPort: getEnvVarNumber("PORT", 3e3),
51
+ bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
52
+ handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
53
+ bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
54
+ distDir,
55
+ compiledApiDir: apiDir + path.sep,
56
+ apiDir,
57
+ apiEntry,
58
+ base,
59
+ isProd: process.env.NODE_ENV === "production"
60
+ };
61
+ }
62
+ function refreshConfig() {
63
+ config = readConfig();
64
+ }
65
+ function resolveApiEntry() {
66
+ return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
67
+ }
68
+ function stripBase(pathname) {
69
+ const base = config.base;
70
+ if (!base) return pathname || "/";
71
+ if (pathname === base || pathname === base + "/") return "/";
72
+ if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
73
+ return null;
74
+ }
56
75
  function scanShellRoutes() {
57
76
  const shellRoutes = /* @__PURE__ */ new Set();
58
- const rootDir = DIST_DIR;
77
+ const rootDir = config.distDir;
59
78
  function walkDir(dir, currentPath) {
60
79
  try {
61
80
  const entries = fs.readdirSync(dir, { withFileTypes: true });
62
81
  for (const entry of entries) {
63
82
  if (!entry.isDirectory()) continue;
64
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
83
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
65
84
  const fullPath = path.join(dir, entry.name);
66
85
  const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
67
86
  if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
@@ -89,26 +108,41 @@ function getShellRoutes() {
89
108
  }
90
109
  function findMatchingShellRoute(pathname) {
91
110
  const shellRoutes = getShellRoutes();
92
- const cleanPath = pathname.replace(/^\/|\/$/g, "");
93
- const pathSegments = cleanPath.split("/").filter(Boolean);
111
+ const pathSegments = pathname.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
94
112
  for (const shellRoute of shellRoutes) {
95
- const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
96
- const shellSegments = cleanShell.split("/").filter(Boolean);
113
+ const shellSegments = shellRoute.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
114
+ if (shellSegments.length === 0) continue;
115
+ const last = shellSegments[shellSegments.length - 1];
116
+ const isRequiredCatchAll = last.startsWith("[...") && !last.startsWith("[[...");
117
+ const isOptionalCatchAll = last.startsWith("[[...");
118
+ const isCatchAll = isRequiredCatchAll || isOptionalCatchAll;
119
+ if (isCatchAll) {
120
+ const prefix = shellSegments.slice(0, -1);
121
+ if (pathSegments.length < prefix.length) continue;
122
+ if (isRequiredCatchAll && pathSegments.length === prefix.length) continue;
123
+ let matches2 = true;
124
+ for (let i = 0; i < prefix.length; i++) {
125
+ const seg = prefix[i];
126
+ if (seg.startsWith("[") && seg.endsWith("]")) continue;
127
+ if (seg !== pathSegments[i]) {
128
+ matches2 = false;
129
+ break;
130
+ }
131
+ }
132
+ if (matches2) return shellRoute;
133
+ continue;
134
+ }
97
135
  if (shellSegments.length !== pathSegments.length) continue;
98
136
  let matches = true;
99
137
  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]) {
138
+ const seg = shellSegments[i];
139
+ if (seg.startsWith("[") && seg.endsWith("]")) continue;
140
+ if (seg !== pathSegments[i]) {
105
141
  matches = false;
106
142
  break;
107
143
  }
108
144
  }
109
- if (matches) {
110
- return shellRoute;
111
- }
145
+ if (matches) return shellRoute;
112
146
  }
113
147
  return null;
114
148
  }
@@ -134,17 +168,21 @@ function getNetworkIp() {
134
168
  return null;
135
169
  }
136
170
  function printBanner(port) {
137
- const envFiles2 = detectEnvFiles(process.cwd());
171
+ const envFiles2 = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
138
172
  const networkIp = getNetworkIp();
139
173
  console.log(`
140
- ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
174
+ ${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
141
175
  if (envFiles2.length > 0) {
142
- console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles2.join(", ")}`);
176
+ const rel = envFiles2.map((f) => path.relative(process.cwd(), f));
177
+ console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
143
178
  }
144
179
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
145
180
  if (networkIp) {
146
181
  console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
147
182
  }
183
+ if (config.base) {
184
+ console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
185
+ }
148
186
  console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
149
187
  console.log("");
150
188
  }
@@ -159,12 +197,9 @@ async function isPortFree(port) {
159
197
  async function findFreePort(start3) {
160
198
  for (let port = start3; port < start3 + 100; port++) {
161
199
  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
200
  return port;
167
201
  }
202
+ console.log(`Port ${port} is in use, trying another one...`);
168
203
  }
169
204
  throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
170
205
  }
@@ -181,7 +216,7 @@ function startKeyboardLoop(port) {
181
216
  console.log("");
182
217
  break;
183
218
  case "o": {
184
- const url = `http://localhost:${port}/`;
219
+ const url = `http://localhost:${port}${config.base || ""}/`;
185
220
  const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
186
221
  exec(cmd);
187
222
  break;
@@ -192,102 +227,6 @@ function startKeyboardLoop(port) {
192
227
  });
193
228
  rl.on("close", () => process.exit(0));
194
229
  }
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
230
  function readBody(req) {
292
231
  return new Promise((resolve, reject) => {
293
232
  const chunks = [];
@@ -295,10 +234,10 @@ function readBody(req) {
295
234
  const timer = setTimeout(() => {
296
235
  req.destroy();
297
236
  reject(new Error("Request body timeout"));
298
- }, BODY_TIMEOUT);
237
+ }, config.bodyTimeout);
299
238
  req.on("data", (chunk) => {
300
239
  size += chunk.byteLength;
301
- if (size > BODY_SIZE_LIMIT) {
240
+ if (size > config.bodySizeLimit) {
302
241
  clearTimeout(timer);
303
242
  req.destroy();
304
243
  reject(new Error("Request body too large"));
@@ -324,115 +263,137 @@ function normalizeHeaders(raw) {
324
263
  }
325
264
  return out;
326
265
  }
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);
331
- res.end();
332
- return;
333
- }
334
- const routes = getRouteCache();
335
- const host = req.headers.host ?? "localhost";
336
- const rawUrl = `http://${host}${req.url ?? "/"}`;
337
- const method = (req.method ?? "GET").toUpperCase();
338
- let parsedUrl;
266
+ function toApiPath(pathname) {
267
+ let p = pathname;
268
+ const base = config.base;
269
+ if (base) {
270
+ if (p === base || p.startsWith(base + "/")) p = p.slice(base.length) || "/";
271
+ else return null;
272
+ }
273
+ if (p === "/api") return "/";
274
+ if (p.startsWith("/api/")) return p.slice(4);
275
+ return null;
276
+ }
277
+ function isApiRequest(url) {
278
+ if (!url) return false;
339
279
  try {
340
- parsedUrl = new URL(rawUrl);
280
+ return toApiPath(new URL(url, "http://localhost").pathname) !== null;
341
281
  } catch {
342
- res.writeHead(400, { "Content-Type": "application/json" });
343
- res.end(JSON.stringify({ error: "Bad request URL" }));
344
- return;
282
+ return false;
345
283
  }
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;
284
+ }
285
+ async function loadApiFetch() {
286
+ if (apiFetch) return apiFetch;
287
+ if (apiLoadPromise) return apiLoadPromise;
288
+ apiLoadPromise = (async () => {
289
+ try {
290
+ const entry = resolveApiEntry();
291
+ if (!entry) throw new Error(`${config.apiEntry} not found`);
292
+ const mod = await import(pathToFileURL(entry).href);
293
+ if (typeof mod.fetch !== "function") {
294
+ throw new Error(`${entry} does not export fetch()`);
359
295
  }
296
+ apiFetch = mod.fetch;
297
+ } catch (err) {
298
+ const msg = err instanceof Error ? err.message : String(err);
299
+ console.warn(
300
+ `
301
+ ${C.YELLOW}\u26A0${C.RESET} No compiled API in ${config.apiDir}.
302
+ ${C.DIM}${msg}${C.RESET}
303
+ API requests will return 404. Run ${C.CYAN}npm run build${C.RESET} to compile it.
304
+ `
305
+ );
306
+ apiFetch = async () => new Response(
307
+ JSON.stringify({ error: "No API routes compiled" }),
308
+ { status: 404, headers: { "content-type": "application/json" } }
309
+ );
360
310
  }
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}` }));
311
+ return apiFetch;
312
+ })();
313
+ return apiLoadPromise;
314
+ }
315
+ async function toWebRequest(req, host) {
316
+ const method = (req.method ?? "GET").toUpperCase();
317
+ const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
318
+ return new Request(`http://${host}${req.url ?? "/"}`, {
319
+ method,
320
+ headers: normalizeHeaders(req.headers),
321
+ body: body ? new Uint8Array(body) : null
322
+ });
323
+ }
324
+ function sendJson(res, status, body, extra = {}) {
325
+ res.writeHead(status, { "content-type": "application/json", ...extra });
326
+ res.end(JSON.stringify(body));
327
+ }
328
+ async function sendWebResponse(res, webRes, method) {
329
+ const headers = {};
330
+ webRes.headers.forEach((v, k) => {
331
+ if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
332
+ });
333
+ const cookies = webRes.headers.getSetCookie?.();
334
+ if (cookies && cookies.length > 0) headers["set-cookie"] = cookies;
335
+ res.writeHead(webRes.status, headers);
336
+ if (method === "HEAD" || !webRes.body) {
337
+ res.end();
366
338
  return;
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
+ try {
341
+ await pipeline(Readable.fromWeb(webRes.body), res);
342
+ } catch {
378
343
  }
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;
344
+ }
345
+ function withTimeout(p, ms) {
346
+ let timer;
347
+ return Promise.race([
348
+ p,
349
+ new Promise((_, reject) => {
350
+ timer = setTimeout(() => reject(new Error("Handler timeout")), ms);
351
+ })
352
+ ]).finally(() => clearTimeout(timer));
353
+ }
354
+ function publicErrorMessage(e) {
355
+ return config.isProd ? "Internal server error" : e instanceof Error ? e.message : String(e);
356
+ }
357
+ async function handleApiRequest(req, res) {
358
+ const method = (req.method ?? "GET").toUpperCase();
359
+ const host = req.headers.host ?? "localhost";
360
+ let parsedUrl;
361
+ try {
362
+ parsedUrl = new URL(`http://${host}${req.url ?? "/"}`);
363
+ } catch {
364
+ return sendJson(res, 400, { error: "Bad request URL" });
385
365
  }
386
- const normalizedHeaders = normalizeHeaders(req.headers);
387
- let webRes;
366
+ if (toApiPath(parsedUrl.pathname) === null) return sendJson(res, 404, { error: "Not Found" });
367
+ const fetchApi = await loadApiFetch();
368
+ let webReq;
388
369
  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" }
370
+ webReq = await toWebRequest(req, host);
371
+ } catch (e) {
372
+ const message = e?.message ?? "Bad request";
373
+ return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
374
+ }
375
+ const ctx = {
376
+ waitUntil(p) {
377
+ p.catch(() => {
411
378
  });
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
379
  }
380
+ };
381
+ try {
382
+ const webRes = await withTimeout(
383
+ fetchApi(webReq, process.env, ctx),
384
+ config.handlerTimeout
385
+ );
386
+ await sendWebResponse(res, webRes, method);
418
387
  } 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;
388
+ console.error("[bini-api] handler error:", e);
389
+ if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
390
+ else res.end();
424
391
  }
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
392
  }
432
393
  function getETag(stat) {
433
394
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
434
395
  }
435
- async function sendFile(filePath, req, res) {
396
+ async function sendFile(filePath, req, res, status = 200) {
436
397
  const ext = path.extname(filePath).toLowerCase();
437
398
  const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
438
399
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -445,12 +406,12 @@ async function sendFile(filePath, req, res) {
445
406
  return;
446
407
  }
447
408
  const etag = getETag(stat);
448
- if (req.headers["if-none-match"] === etag) {
409
+ if (status === 200 && req.headers["if-none-match"] === etag) {
449
410
  res.writeHead(304);
450
411
  res.end();
451
412
  return;
452
413
  }
453
- res.writeHead(200, {
414
+ res.writeHead(status, {
454
415
  "Content-Type": mimeType,
455
416
  "Content-Length": stat.size,
456
417
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
@@ -467,11 +428,17 @@ async function sendFile(filePath, req, res) {
467
428
  }
468
429
  }
469
430
  async function serveStatic(req, res, next) {
470
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
471
- if (pathname.startsWith("/api")) return next();
431
+ const rawPathname = new URL(req.url ?? "/", "http://localhost").pathname;
432
+ if (toApiPath(rawPathname) !== null) return next();
433
+ const pathname = stripBase(rawPathname);
434
+ if (pathname === null) return next();
435
+ if (pathname.includes("\0") || pathname.split("/").some((s) => s === "..")) {
436
+ return next();
437
+ }
472
438
  const hasExtension = path.extname(pathname).length > 0;
473
439
  if (hasExtension) {
474
- const filePath = path.join(DIST_DIR, pathname);
440
+ const filePath = path.join(config.distDir, pathname);
441
+ if (filePath.startsWith(config.compiledApiDir)) return next();
475
442
  try {
476
443
  const stat = await fs.promises.stat(filePath);
477
444
  if (stat.isFile()) {
@@ -482,7 +449,7 @@ async function serveStatic(req, res, next) {
482
449
  }
483
450
  return next();
484
451
  }
485
- const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
452
+ const staticFilePath = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
486
453
  try {
487
454
  const stat = await fs.promises.stat(staticFilePath);
488
455
  if (stat.isFile()) {
@@ -493,7 +460,7 @@ async function serveStatic(req, res, next) {
493
460
  }
494
461
  const matchingShell = findMatchingShellRoute(pathname);
495
462
  if (matchingShell) {
496
- const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
463
+ const shellPath = path.join(config.distDir, matchingShell, "index.html");
497
464
  try {
498
465
  const stat = await fs.promises.stat(shellPath);
499
466
  if (stat.isFile()) {
@@ -503,7 +470,16 @@ async function serveStatic(req, res, next) {
503
470
  } catch {
504
471
  }
505
472
  }
506
- const indexPath = path.join(DIST_DIR, "index.html");
473
+ const notFoundPath = path.join(config.distDir, "404.html");
474
+ try {
475
+ const stat = await fs.promises.stat(notFoundPath);
476
+ if (stat.isFile()) {
477
+ await sendFile(notFoundPath, req, res, 404);
478
+ return;
479
+ }
480
+ } catch {
481
+ }
482
+ const indexPath = path.join(config.distDir, "index.html");
507
483
  try {
508
484
  await fs.promises.access(indexPath);
509
485
  await sendFile(indexPath, req, res);
@@ -522,7 +498,7 @@ function compose(middlewares) {
522
498
  } catch (e) {
523
499
  if (!res.headersSent) {
524
500
  res.writeHead(500, { "Content-Type": "application/json" });
525
- res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
501
+ res.end(JSON.stringify({ error: publicErrorMessage(e) }));
526
502
  }
527
503
  }
528
504
  };
@@ -530,19 +506,22 @@ function compose(middlewares) {
530
506
  };
531
507
  }
532
508
  async function start() {
533
- if (!fs.existsSync(DIST_DIR)) {
509
+ loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
510
+ refreshConfig();
511
+ if (!fs.existsSync(config.distDir)) {
534
512
  console.error(`
535
- ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
513
+ ${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
536
514
  Run ${C.CYAN}npm run build${C.RESET} first.
537
515
  `);
538
516
  process.exit(1);
539
517
  }
518
+ await loadApiFetch();
540
519
  getShellRoutes();
541
- const port = await findFreePort(DEFAULT_PORT);
520
+ const port = await findFreePort(config.defaultPort);
542
521
  const handler = compose([
543
522
  async (req, res, next) => {
544
- if (!req.url?.startsWith("/api")) return next();
545
- await handleApiRequest(req, res, next);
523
+ if (!isApiRequest(req.url)) return next();
524
+ await handleApiRequest(req, res);
546
525
  },
547
526
  serveStatic,
548
527
  (_req, res) => {
@@ -573,17 +552,11 @@ async function start() {
573
552
  process.on("SIGTERM", shutdown);
574
553
  process.on("SIGINT", shutdown);
575
554
  }
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;
555
+ var config, C, shellRouteCache, apiFetch, apiLoadPromise, MIME_TYPES;
577
556
  var init_src = __esm({
578
557
  "src/index.ts"() {
579
558
  "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);
559
+ config = readConfig();
587
560
  C = {
588
561
  CYAN: "\x1B[36m",
589
562
  RESET: "\x1B[0m",
@@ -594,19 +567,8 @@ var init_src = __esm({
594
567
  DIM: "\x1B[2m"
595
568
  };
596
569
  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
- };
570
+ apiFetch = null;
571
+ apiLoadPromise = null;
610
572
  MIME_TYPES = {
611
573
  ".html": "text/html; charset=utf-8",
612
574
  ".js": "application/javascript",
@@ -650,3 +612,4 @@ start2().catch((err) => {
650
612
  console.error(err);
651
613
  process.exit(1);
652
614
  });
615
+ //# sourceMappingURL=cli.js.map