bini-server 1.0.4 → 1.0.7

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 CHANGED
@@ -4,8 +4,7 @@
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/bini-server?style=flat-square&logo=npm&logoColor=white&label=npm&color=CB3837&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green?style=flat-square&logo=opensourceinitiative&logoColor=white&labelColor=0a0a0a)](./LICENSE)
7
- [![node](https://img.shields.io/badge/node-%3E%3D18-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
8
- [![bini-env](https://img.shields.io/badge/bini--env-powered-00CFFF?style=flat-square&logo=vite&logoColor=white&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-env)
7
+ [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
9
8
 
10
9
  **Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
11
10
  Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` handlers — just like `vite preview`, but production-grade.
@@ -19,7 +18,7 @@ Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` han
19
18
  - 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
20
19
  - 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
21
20
  - 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
22
- - 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env)
21
+ - 🌿 **Auto env loading** — `.env` files detected and listed automatically at startup
23
22
  - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
24
23
  - 🛡️ **CORS** — enabled by default on all API responses
25
24
  - ⏱️ **Timeouts** — configurable body read + handler timeouts (default 30s each)
@@ -33,7 +32,7 @@ Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` han
33
32
 
34
33
  ## Requirements
35
34
 
36
- - Node.js **≥ 18**
35
+ - Node.js **≥ 20**
37
36
  - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
38
37
 
39
38
  ---
@@ -92,7 +91,7 @@ Once the server is running, type a key and press `enter`:
92
91
 
93
92
  ## Environment Variables
94
93
 
95
- `.env` is loaded automatically at startup — all vars are available in `process.env` in your API handlers with no imports needed.
94
+ `.env` files are detected automatically at startup and listed in the banner. All vars are available in `process.env` in your API handlers with no imports needed.
96
95
 
97
96
  ```env
98
97
  PORT=3000
@@ -193,7 +192,7 @@ Set start command to `npm start`. Render injects `PORT` automatically.
193
192
  | Body size limit | ❌ | ✅ 10MB |
194
193
  | Handler timeout | ❌ | ✅ 30s |
195
194
  | Graceful shutdown | ❌ | ✅ |
196
- | Keyboard shortcuts | ❌ | ✅ |
195
+ | Handler module cache | ❌ | ✅ |
197
196
  | Configurable dirs | ❌ | ✅ |
198
197
 
199
198
  ---
package/dist/cli.js CHANGED
@@ -1,6 +1,19 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
2
11
 
3
12
  // src/index.ts
13
+ var src_exports = {};
14
+ __export(src_exports, {
15
+ start: () => start
16
+ });
4
17
  import http from "http";
5
18
  import fs from "fs";
6
19
  import path from "path";
@@ -12,38 +25,15 @@ import { exec } from "child_process";
12
25
  import { pathToFileURL } from "url";
13
26
  import { pipeline } from "stream/promises";
14
27
  import { createReadStream } from "fs";
15
- import { loadEnv, detectEnvFiles } from "bini-env";
16
- process.env.NODE_ENV = "production";
17
- (function suppressDotenv() {
18
- const _log = console.log.bind(console);
19
- const _err = console.error.bind(console);
20
- const isDotenv = (...args) => {
21
- const msg = args.join(" ");
22
- return msg.includes("[dotenv@") || msg.includes("[bini-env] Loaded");
23
- };
24
- console.log = (...args) => {
25
- if (!isDotenv(...args)) _log(...args);
26
- };
27
- console.error = (...args) => {
28
- if (!isDotenv(...args)) _err(...args);
29
- };
30
- })();
31
- var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
32
- var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
33
- var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
34
- var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
35
- var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
36
- var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
37
- var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
38
- var C = {
39
- CYAN: "\x1B[36m",
40
- RESET: "\x1B[0m",
41
- GREEN: "\x1B[32m",
42
- RED: "\x1B[31m",
43
- YELLOW: "\x1B[33m",
44
- BOLD: "\x1B[1m",
45
- DIM: "\x1B[2m"
46
- };
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
+ }
47
37
  function getNetworkIp() {
48
38
  const ifaces = os.networkInterfaces();
49
39
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
@@ -66,18 +56,18 @@ function getNetworkIp() {
66
56
  return null;
67
57
  }
68
58
  function printBanner(port) {
69
- const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
59
+ const envFiles2 = detectEnvFiles(process.cwd());
70
60
  const networkIp = getNetworkIp();
71
61
  console.log(`
72
62
  ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
73
- if (envFiles.length > 0) {
74
- console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
63
+ if (envFiles2.length > 0) {
64
+ console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles2.join(", ")}`);
75
65
  }
76
66
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
77
67
  if (networkIp) {
78
68
  console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
79
69
  }
80
- console.log(` ${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h${C.DIM} + ${C.RESET}enter${C.DIM} to show help${C.RESET}`);
70
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
81
71
  console.log("");
82
72
  }
83
73
  async function isPortFree(port) {
@@ -88,17 +78,17 @@ async function isPortFree(port) {
88
78
  server.listen(port, "0.0.0.0");
89
79
  });
90
80
  }
91
- async function findFreePort(start2) {
92
- for (let port = start2; port < start2 + 100; port++) {
81
+ async function findFreePort(start3) {
82
+ for (let port = start3; port < start3 + 100; port++) {
93
83
  if (await isPortFree(port)) {
94
- if (port !== start2) {
84
+ if (port !== start3) {
95
85
  console.log(`
96
- ${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
86
+ ${C.YELLOW}\u26A0${C.RESET} Port ${start3} in use \u2014 using ${port} instead.`);
97
87
  }
98
88
  return port;
99
89
  }
100
90
  }
101
- throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
91
+ throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
102
92
  }
103
93
  function startKeyboardLoop(port) {
104
94
  const rl = readline.createInterface({ input: process.stdin });
@@ -107,8 +97,8 @@ function startKeyboardLoop(port) {
107
97
  case "h":
108
98
  console.log("");
109
99
  console.log(" Shortcuts");
110
- console.log(` ${C.DIM}press ${C.RESET}o${C.DIM} + ${C.RESET}enter${C.DIM} to open in browser${C.RESET}`);
111
- console.log(` ${C.DIM}press ${C.RESET}q${C.DIM} + ${C.RESET}enter${C.DIM} to quit${C.RESET}`);
100
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
101
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
112
102
  console.log("");
113
103
  break;
114
104
  case "o": {
@@ -181,7 +171,6 @@ function matchRoute(pattern, pathname) {
181
171
  }
182
172
  return params;
183
173
  }
184
- var moduleCache = /* @__PURE__ */ new Map();
185
174
  async function importHandler(filePath) {
186
175
  let mtime = 0;
187
176
  try {
@@ -238,13 +227,9 @@ function normalizeHeaders(raw) {
238
227
  }
239
228
  return out;
240
229
  }
241
- var CORS_HEADERS = {
242
- "Access-Control-Allow-Origin": "*",
243
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
244
- "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
245
- "Vary": "Origin"
246
- };
247
- var routeCache = null;
230
+ function invokeHono(honoApp, request) {
231
+ return honoApp.fetch(request, process.env);
232
+ }
248
233
  async function handleApiRequest(req, res, next) {
249
234
  if (req.method === "OPTIONS") {
250
235
  res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
@@ -300,7 +285,7 @@ async function handleApiRequest(req, res, next) {
300
285
  try {
301
286
  if (typeof handler.fetch === "function") {
302
287
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
303
- webRes = await handler.fetch(new Request(honoUrl, {
288
+ webRes = await invokeHono(handler, new Request(honoUrl, {
304
289
  method,
305
290
  headers: normalizedHeaders,
306
291
  body: body ? new Uint8Array(body) : null
@@ -339,29 +324,6 @@ async function handleApiRequest(req, res, next) {
339
324
  res.writeHead(webRes.status, finalHeaders);
340
325
  res.end(Buffer.from(await webRes.arrayBuffer()));
341
326
  }
342
- var MIME = {
343
- ".html": "text/html; charset=utf-8",
344
- ".js": "application/javascript",
345
- ".mjs": "application/javascript",
346
- ".css": "text/css",
347
- ".json": "application/json",
348
- ".png": "image/png",
349
- ".jpg": "image/jpeg",
350
- ".jpeg": "image/jpeg",
351
- ".gif": "image/gif",
352
- ".svg": "image/svg+xml",
353
- ".ico": "image/x-icon",
354
- ".webp": "image/webp",
355
- ".avif": "image/avif",
356
- ".woff": "font/woff",
357
- ".woff2": "font/woff2",
358
- ".ttf": "font/ttf",
359
- ".eot": "application/vnd.ms-fontobject",
360
- ".txt": "text/plain",
361
- ".xml": "application/xml",
362
- ".webmanifest": "application/manifest+json",
363
- ".map": "application/json"
364
- };
365
327
  function getETag(stat) {
366
328
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
367
329
  }
@@ -438,7 +400,6 @@ function compose(middlewares) {
438
400
  };
439
401
  }
440
402
  async function start() {
441
- await loadEnv(process.cwd());
442
403
  if (!fs.existsSync(DIST_DIR)) {
443
404
  console.error(`
444
405
  ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
@@ -480,9 +441,74 @@ async function start() {
480
441
  process.on("SIGTERM", shutdown);
481
442
  process.on("SIGINT", shutdown);
482
443
  }
444
+ var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, API_EXTS, C, moduleCache, CORS_HEADERS, routeCache, MIME;
445
+ var init_src = __esm({
446
+ "src/index.ts"() {
447
+ "use strict";
448
+ DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
449
+ BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
450
+ HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
451
+ BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
452
+ API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
453
+ DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
454
+ API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
455
+ C = {
456
+ CYAN: "\x1B[36m",
457
+ RESET: "\x1B[0m",
458
+ GREEN: "\x1B[32m",
459
+ RED: "\x1B[31m",
460
+ YELLOW: "\x1B[33m",
461
+ BOLD: "\x1B[1m",
462
+ DIM: "\x1B[2m"
463
+ };
464
+ moduleCache = /* @__PURE__ */ new Map();
465
+ CORS_HEADERS = {
466
+ "Access-Control-Allow-Origin": "*",
467
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
468
+ "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
469
+ "Vary": "Origin"
470
+ };
471
+ routeCache = null;
472
+ MIME = {
473
+ ".html": "text/html; charset=utf-8",
474
+ ".js": "application/javascript",
475
+ ".mjs": "application/javascript",
476
+ ".css": "text/css",
477
+ ".json": "application/json",
478
+ ".png": "image/png",
479
+ ".jpg": "image/jpeg",
480
+ ".jpeg": "image/jpeg",
481
+ ".gif": "image/gif",
482
+ ".svg": "image/svg+xml",
483
+ ".ico": "image/x-icon",
484
+ ".webp": "image/webp",
485
+ ".avif": "image/avif",
486
+ ".woff": "font/woff",
487
+ ".woff2": "font/woff2",
488
+ ".ttf": "font/ttf",
489
+ ".eot": "application/vnd.ms-fontobject",
490
+ ".txt": "text/plain",
491
+ ".xml": "application/xml",
492
+ ".webmanifest": "application/manifest+json",
493
+ ".map": "application/json"
494
+ };
495
+ }
496
+ });
483
497
 
484
498
  // src/cli.ts
485
- start().catch((err) => {
499
+ import { existsSync } from "fs";
500
+ process.env.NODE_ENV = "production";
501
+ var envFiles = [
502
+ ".env.local",
503
+ ".env.production.local",
504
+ ".env.production",
505
+ ".env"
506
+ ];
507
+ for (const file of envFiles) {
508
+ if (existsSync(file)) process.loadEnvFile(file);
509
+ }
510
+ var { start: start2 } = await Promise.resolve().then(() => (init_src(), src_exports));
511
+ start2().catch((err) => {
486
512
  console.error(err);
487
513
  process.exit(1);
488
514
  });
package/dist/index.js CHANGED
@@ -10,22 +10,15 @@ import { exec } from "child_process";
10
10
  import { pathToFileURL } from "url";
11
11
  import { pipeline } from "stream/promises";
12
12
  import { createReadStream } from "fs";
13
- import { loadEnv, detectEnvFiles } from "bini-env";
14
- process.env.NODE_ENV = "production";
15
- (function suppressDotenv() {
16
- const _log = console.log.bind(console);
17
- const _err = console.error.bind(console);
18
- const isDotenv = (...args) => {
19
- const msg = args.join(" ");
20
- return msg.includes("[dotenv@") || msg.includes("[bini-env] Loaded");
21
- };
22
- console.log = (...args) => {
23
- if (!isDotenv(...args)) _log(...args);
24
- };
25
- console.error = (...args) => {
26
- if (!isDotenv(...args)) _err(...args);
27
- };
28
- })();
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
+ }
29
22
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
30
23
  var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
31
24
  var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
@@ -64,7 +57,7 @@ function getNetworkIp() {
64
57
  return null;
65
58
  }
66
59
  function printBanner(port) {
67
- const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
60
+ const envFiles = detectEnvFiles(process.cwd());
68
61
  const networkIp = getNetworkIp();
69
62
  console.log(`
70
63
  ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
@@ -75,7 +68,7 @@ function printBanner(port) {
75
68
  if (networkIp) {
76
69
  console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
77
70
  }
78
- console.log(` ${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h${C.DIM} + ${C.RESET}enter${C.DIM} to show help${C.RESET}`);
71
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
79
72
  console.log("");
80
73
  }
81
74
  async function isPortFree(port) {
@@ -105,8 +98,8 @@ function startKeyboardLoop(port) {
105
98
  case "h":
106
99
  console.log("");
107
100
  console.log(" Shortcuts");
108
- console.log(` ${C.DIM}press ${C.RESET}o${C.DIM} + ${C.RESET}enter${C.DIM} to open in browser${C.RESET}`);
109
- console.log(` ${C.DIM}press ${C.RESET}q${C.DIM} + ${C.RESET}enter${C.DIM} to quit${C.RESET}`);
101
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
102
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
110
103
  console.log("");
111
104
  break;
112
105
  case "o": {
@@ -242,6 +235,9 @@ var CORS_HEADERS = {
242
235
  "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
243
236
  "Vary": "Origin"
244
237
  };
238
+ function invokeHono(honoApp, request) {
239
+ return honoApp.fetch(request, process.env);
240
+ }
245
241
  var routeCache = null;
246
242
  async function handleApiRequest(req, res, next) {
247
243
  if (req.method === "OPTIONS") {
@@ -298,7 +294,7 @@ async function handleApiRequest(req, res, next) {
298
294
  try {
299
295
  if (typeof handler.fetch === "function") {
300
296
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
301
- webRes = await handler.fetch(new Request(honoUrl, {
297
+ webRes = await invokeHono(handler, new Request(honoUrl, {
302
298
  method,
303
299
  headers: normalizedHeaders,
304
300
  body: body ? new Uint8Array(body) : null
@@ -436,7 +432,6 @@ function compose(middlewares) {
436
432
  };
437
433
  }
438
434
  async function start() {
439
- await loadEnv(process.cwd());
440
435
  if (!fs.existsSync(DIST_DIR)) {
441
436
  console.error(`
442
437
  ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.4",
3
+ "version": "1.0.7",
4
4
  "description": "Production server for bini-router apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -31,9 +31,6 @@
31
31
  "lint": "tsc --noEmit",
32
32
  "clean": "rm -rf dist"
33
33
  },
34
- "dependencies": {
35
- "bini-env": "1.0.8"
36
- },
37
34
  "engines": {
38
35
  "node": ">=20.19.0"
39
36
  },
@@ -41,7 +38,6 @@
41
38
  "bini",
42
39
  "bini-js",
43
40
  "bini-router",
44
- "bini-env",
45
41
  "server",
46
42
  "spa",
47
43
  "vite",
@@ -63,8 +59,9 @@
63
59
  "url": "https://github.com/Binidu01/bini-server/issues"
64
60
  },
65
61
  "devDependencies": {
66
- "@types/node": "^25.6.0",
62
+ "@types/node": "^25.7.0",
67
63
  "tsup": "^8.5.1",
68
- "typescript": "^5.9.3"
64
+ "typescript": "^6.0.3",
65
+ "dotenv": "^17.4.2"
69
66
  }
70
67
  }