bini-server 1.0.9 → 2.0.0

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.
Files changed (4) hide show
  1. package/README.md +348 -77
  2. package/dist/cli.js +177 -42
  3. package/dist/index.js +198 -63
  4. package/package.json +4 -4
package/README.md CHANGED
@@ -5,49 +5,66 @@
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
7
  [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
8
+ [![bundle size](https://img.shields.io/bundlephobia/min/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://bundlephobia.com/package/bini-server)
9
+ [![downloads](https://img.shields.io/npm/dt/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
8
10
 
9
11
  **Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
10
- Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` handlers — just like `vite preview`, but production-grade.
12
+ Zero-dependency, secure-by-default, production-grade server for your static sites and API routes.
11
13
 
12
14
  </div>
13
15
 
14
16
  ---
15
17
 
16
- ## Features
17
-
18
- - 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
19
- - 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
20
- - 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
21
- - 🌿 **Auto env loading** — `.env` files detected and listed automatically at startup
22
- - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
23
- - 🛡️ **CORS** — enabled by default on all API responses
24
- - ⏱️ **Timeouts** — configurable body read + handler timeouts (default 30s each)
25
- - 🔒 **Body limit** — configurable request body limit (default 10MB)
26
- - 🔌 **Port auto-increment** — starts at `3000`, increments if busy
27
- - 🪄 **Graceful shutdown** — handles `SIGTERM` + `SIGINT` with 10s force-exit fallback
28
- - ⌨️ **Interactive keyboard shortcuts** — `h` for help, `o` to open in browser, `q` to quit
29
- - 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
18
+ ## ✨ Features
19
+
20
+ ### Core Features
21
+ - 🗂️ **Static file serving** — Streams `dist/` with proper MIME types, ETag, and cache headers
22
+ - 🌐 **API routes** — Serves `/api/*` from `src/app/api/` (Hono apps + plain functions)
23
+ - 🔀 **SPA fallback** — Unknown routes serve `dist/index.html` automatically
24
+ - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged static files
25
+ - ⚡ **Lazy route loading** — API routes scanned only on first request for fast startup
26
+
27
+ ### Security & Performance
28
+ - 🛡️ **CORS** — Enabled by default, configurable via `CORS_ENABLED` (supports `BINI_*`, `VITE_*`, no prefix)
29
+ - 🔒 **Body limits** — Configurable request body size limit (default 10MB)
30
+ - ⏱️ **Timeouts** — Configurable body read + handler timeouts (default 30s each)
31
+ - 🚫 **Path traversal protection** — Guards against `..` and `//` in URLs
32
+ - 💾 **Module cache** — Caches imported handlers with mtime invalidation
33
+ - 🔌 **Port auto-increment** — Starts at `3000`, auto-increments if busy
34
+
35
+ ### Developer Experience
36
+ - 🌿 **Auto env loading** — `.env` files detected and listed at startup
37
+ - ⌨️ **Interactive shortcuts** — `h` for help, `o` to open browser, `q` to quit
38
+ - 🖥️ **Cross-platform** — Works on Windows, macOS, and Linux
39
+ - 🪄 **Graceful shutdown** — Handles `SIGTERM` + `SIGINT` with timeout fallback
40
+ - 📦 **Zero dependencies** — Only uses Node.js built-in modules
41
+ - 🔧 **Flexible config** — Supports `BINI_*`, `VITE_*`, or no prefix env vars
30
42
 
31
43
  ---
32
44
 
33
- ## Requirements
45
+ ## 📋 Requirements
34
46
 
35
- - Node.js **≥ 20**
47
+ - Node.js **≥ 20.19.0**
36
48
  - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
49
+ - API handlers in `src/app/api/` (if using API routes)
37
50
 
38
51
  ---
39
52
 
40
- ## Install
53
+ ## 📦 Install
41
54
 
42
55
  ```bash
43
56
  npm install bini-server
57
+ # or
58
+ pnpm add bini-server
59
+ # or
60
+ yarn add bini-server
44
61
  ```
45
62
 
46
63
  ---
47
64
 
48
- ## Usage
65
+ ## 🚀 Usage
49
66
 
50
- Add to your `package.json`:
67
+ ### 1. Add to `package.json`
51
68
 
52
69
  ```json
53
70
  {
@@ -58,18 +75,18 @@ Add to your `package.json`:
58
75
  }
59
76
  ```
60
77
 
61
- Then:
78
+ ### 2. Build and Start
62
79
 
63
80
  ```bash
64
- npm run build # build your app
65
- npm start # serve it in production
81
+ npm run build # Build your app
82
+ npm start # Serve in production
66
83
  ```
67
84
 
68
- Terminal output:
85
+ ### 3. Terminal Output
69
86
 
70
87
  ```
71
88
  ß Bini.js (production)
72
- ➜ Environments: .env
89
+ ➜ Environments: .env, .env.local
73
90
  ➜ Local: http://localhost:3000/
74
91
  ➜ Network: http://192.168.1.5:3000/
75
92
  ➜ press h + enter to show help
@@ -77,96 +94,222 @@ Terminal output:
77
94
 
78
95
  ---
79
96
 
80
- ## Keyboard Shortcuts
97
+ ## ⌨️ Keyboard Shortcuts
81
98
 
82
- Once the server is running, type a key and press `enter`:
99
+ While the server is running, type a key and press `enter`:
83
100
 
84
101
  | Key | Action |
85
102
  |-----|--------|
86
103
  | `h` | Show available shortcuts |
87
- | `o` | Open in browser |
88
- | `q` | Quit |
104
+ | `o` | Open your app in the default browser |
105
+ | `q` | Quit the server |
106
+
107
+ > Keyboard shortcuts are automatically disabled in non-interactive environments (like Render, CI/CD).
89
108
 
90
109
  ---
91
110
 
92
- ## Environment Variables
111
+ ## 🌿 Environment Variables
93
112
 
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.
113
+ ### Auto-Detected `.env` Files
95
114
 
96
- ```env
97
- PORT=3000
98
- SMTP_USER=user@smtp.example.com
99
- SMTP_PASS=your_password
100
- ```
115
+ At startup, bini-server automatically detects and loads:
116
+
117
+ 1. `.env.local`
118
+ 2. `.env.[NODE_ENV].local` (e.g., `.env.production.local`)
119
+ 3. `.env.[NODE_ENV]` (e.g., `.env.production`)
120
+ 4. `.env`
121
+
122
+ All detected files are listed in the startup banner.
101
123
 
102
124
  ### Server Configuration
103
125
 
104
- These variables tune server behaviour and can be set in `.env` or inline:
126
+ All environment variables support **three naming conventions:**
127
+
128
+ | Convention | Example | Priority |
129
+ |------------|---------|----------|
130
+ | `BINI_*` | `BINI_PORT=3000` | Highest |
131
+ | `VITE_*` | `VITE_PORT=3000` | Medium |
132
+ | No prefix | `PORT=3000` | Lowest |
105
133
 
106
134
  | Variable | Default | Description |
107
- |---|---|---|
135
+ |----------|---------|-------------|
108
136
  | `PORT` | `3000` | HTTP port to listen on |
109
- | `BINI_API_DIR` | `src/app/api` | Path to API handlers directory |
110
- | `BINI_DIST_DIR` | `dist` | Path to static files directory |
111
- | `BINI_BODY_TIMEOUT_SECS` | `30` | Max seconds to read request body |
112
- | `BINI_HANDLER_TIMEOUT_SECS` | `30` | Max seconds for an API handler to respond |
113
- | `BINI_BODY_SIZE_LIMIT` | `10485760` | Max request body size in bytes (default 10MB) |
137
+ | `CORS_ENABLED` | `true` | Enable/disable CORS on API routes |
138
+ | `API_DIR` | `src/app/api` | Path to API handlers directory |
139
+ | `DIST_DIR` | `dist` | Path to static files directory |
140
+ | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read request body |
141
+ | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for handler to respond |
142
+ | `BODY_SIZE_LIMIT` | `10485760` | Max request body size in bytes (10MB) |
114
143
 
115
- ---
144
+ ### Examples
116
145
 
117
- ## Important: ship your `src/` folder
146
+ ```bash
147
+ # .env file
148
+ PORT=8080
149
+ CORS_ENABLED=false
150
+ API_DIR=src/api
151
+ BODY_SIZE_LIMIT=5242880 # 5MB
118
152
 
119
- bini-server runs your API handlers directly from `src/app/api/` — they are **not** compiled into `dist/`. When deploying, make sure your server has access to both `dist/` and `src/app/api/`.
153
+ # Or inline
154
+ PORT=3001 BINI_CORS_ENABLED=false bini-server
120
155
 
121
- For VPS/pm2 this means deploying your full project directory, not just `dist/`. For Railway, Render, and Fly.io this happens automatically since they clone your repository.
156
+ # Or with VITE prefix
157
+ VITE_PORT=3000 VITE_CORS_ENABLED=false bini-server
158
+ ```
122
159
 
123
160
  ---
124
161
 
125
- ## Port
162
+ ## 📁 Project Structure
126
163
 
127
- Default port is `3000`. Override via `.env` or inline:
164
+ ```
165
+ my-app/
166
+ ├── dist/ # Built static files (required)
167
+ │ ├── index.html
168
+ │ ├── assets/
169
+ │ └── ...
170
+ ├── src/
171
+ │ ├── app/
172
+ │ │ ├── api/ # API handlers (optional)
173
+ │ │ │ ├── users.ts
174
+ │ │ │ └── posts/
175
+ │ │ │ ├── index.ts
176
+ │ │ │ └── [id].ts
177
+ │ │ └── layout.tsx
178
+ │ └── main.tsx
179
+ ├── .env # Environment variables
180
+ ├── package.json
181
+ └── vite.config.ts
182
+ ```
128
183
 
129
- ```env
130
- PORT=8080
184
+ ---
185
+
186
+ ## 🌐 API Routes
187
+
188
+ ### Supported Formats
189
+
190
+ ```typescript
191
+ // 1. Hono App (Recommended)
192
+ import { Hono } from 'hono';
193
+ const app = new Hono();
194
+ app.get('/users', (c) => c.json({ users: [] }));
195
+ export default app;
196
+
197
+ // 2. Plain Function
198
+ export default (req: Request) => {
199
+ return Response.json({ message: 'Hello' });
200
+ };
131
201
  ```
132
202
 
133
- ```bash
134
- PORT=8080 bini-server
203
+ ### Supported Extensions
204
+
205
+ Only `.ts` and `.js` files are supported for API routes (Next.js convention).
206
+
207
+ ### Dynamic Routes
208
+
209
+ ```
210
+ src/app/api/
211
+ users/
212
+ [id].ts → /api/users/:id
213
+ posts/
214
+ [...slug].ts → /api/posts/*
215
+ ```
216
+
217
+ ### Route Parameters
218
+
219
+ ```typescript
220
+ // src/app/api/users/[id].ts
221
+ export default (req: Request) => {
222
+ const params = JSON.parse(req.headers.get('x-bini-params') || '{}');
223
+ // params.id → '123'
224
+ return Response.json({ id: params.id });
225
+ };
135
226
  ```
136
227
 
137
- If the port is busy, bini-server automatically increments and warns:
228
+ ### CORS
229
+
230
+ CORS is **enabled by default** with these headers:
138
231
 
139
232
  ```
140
- ⚠ Port 3000 in use — using 3001 instead.
233
+ Access-Control-Allow-Origin: *
234
+ Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD
235
+ Access-Control-Allow-Headers: Content-Type,Authorization,X-Request-ID
141
236
  ```
142
237
 
238
+ Disable with `CORS_ENABLED=false`, `BINI_CORS_ENABLED=false`, or `VITE_CORS_ENABLED=false`.
239
+
143
240
  ---
144
241
 
145
- ## Deployment
242
+ ## 🗂️ Static File Serving
243
+
244
+ ### Supported MIME Types
245
+
246
+ All common file types are served with correct MIME types:
247
+ - HTML, CSS, JavaScript, JSON
248
+ - Images: PNG, JPEG, GIF, SVG, WebP, AVIF, ICO
249
+ - Fonts: WOFF, WOFF2, TTF, EOT
250
+ - Documents: TXT, XML
251
+ - Web manifests
252
+
253
+ ### Cache Headers
254
+
255
+ | File Type | Cache Policy |
256
+ |-----------|--------------|
257
+ | **Assets** (`/assets/*`) | `public, max-age=31536000, immutable` (1 year) |
258
+ | **All other files** | `no-cache` |
259
+
260
+ ### ETag Support
261
+
262
+ Automatically generates ETags from file `size + mtimeMs`:
263
+ - Sends `ETag` header on first request
264
+ - Handles `If-None-Match` for `304 Not Modified` responses
265
+ - Uses MD5 hash (16 chars) for efficient caching
266
+
267
+ ---
268
+
269
+ ## 🚢 Deployment
270
+
271
+ ### Important: Ship Your `src/` Folder
146
272
 
147
- ### VPS (Ubuntu, Debian, etc.)
273
+ bini-server runs API handlers directly from `src/app/api/` — they are **not** compiled into `dist/`. When deploying, ensure your server has access to both `dist/` and `src/app/api/`.
274
+
275
+ - ✅ **VPS/pm2**: Deploy the full project directory
276
+ - ✅ **Railway/Render/Fly.io**: Automatic (clones your repository)
277
+ - ✅ **Docker**: Copy both `dist/` and `src/` directories
278
+
279
+ ### VPS / Dedicated Server
148
280
 
149
281
  ```bash
150
282
  npm run build
151
283
  npm start
152
- ```
153
284
 
154
- Use [pm2](https://pm2.keymetrics.io/) to keep it running:
155
-
156
- ```bash
285
+ # With pm2 (recommended)
157
286
  npm install -g pm2
158
287
  pm2 start "npm start" --name my-app
159
288
  pm2 save
160
289
  pm2 startup
161
290
  ```
162
291
 
163
- ### Railway
164
-
165
- Set start command to `npm start`. Railway injects `PORT` automatically.
166
-
167
- ### Render
168
-
169
- Set start command to `npm start`. Render injects `PORT` automatically.
292
+ ### Platform as a Service
293
+
294
+ | Platform | Start Command | Notes |
295
+ |----------|---------------|-------|
296
+ | **Railway** | `npm start` | PORT injected automatically |
297
+ | **Render** | `npm start` | PORT injected automatically |
298
+ | **Fly.io** | `npm start` | See fly.toml example below |
299
+ | **Heroku** | `npm start` | PORT injected automatically |
300
+
301
+ ### Docker
302
+
303
+ ```dockerfile
304
+ FROM node:20-alpine
305
+ WORKDIR /app
306
+ COPY package*.json ./
307
+ RUN npm install --production
308
+ COPY . .
309
+ RUN npm run build
310
+ EXPOSE 3000
311
+ CMD ["npm", "start"]
312
+ ```
170
313
 
171
314
  ### Fly.io
172
315
 
@@ -178,25 +321,153 @@ Set start command to `npm start`. Render injects `PORT` automatically.
178
321
 
179
322
  ---
180
323
 
181
- ## vs `vite preview`
324
+ ## 🔧 vs `vite preview`
182
325
 
183
326
  | Feature | `vite preview` | `bini-server` |
184
- |---|---|---|
327
+ |---------|---------------|---------------|
185
328
  | Serves `dist/` | ✅ | ✅ |
186
329
  | API routes | ✅ | ✅ |
187
330
  | SPA fallback | ✅ | ✅ |
188
331
  | Auto env loading | ✅ | ✅ |
189
332
  | ETag / 304 support | ❌ | ✅ |
190
- | Production use | ❌ | ✅ |
191
- | Body timeout | ❌ | ✅ 30s |
192
- | Body size limit | ❌ | ✅ 10MB |
193
- | Handler timeout | ❌ | ✅ 30s |
333
+ | Body timeout | ❌ | ✅ (30s) |
334
+ | Body size limit | ❌ | ✅ (10MB) |
335
+ | Handler timeout | ❌ | ✅ (30s) |
194
336
  | Graceful shutdown | ❌ | ✅ |
195
- | Handler module cache | ❌ | ✅ |
337
+ | Module cache | ❌ | ✅ |
196
338
  | Configurable dirs | ❌ | ✅ |
339
+ | CORS control | ❌ | ✅ |
340
+ | Zero dependencies | ❌ | ✅ |
341
+ | Production use | ⚠️ Not recommended | ✅ Production-ready |
342
+
343
+ ---
344
+
345
+ ## 🛡️ Security
346
+
347
+ | Feature | Default | Configurable |
348
+ |---------|---------|--------------|
349
+ | CORS | Enabled | ✅ via `CORS_ENABLED` |
350
+ | Body size limit | 10MB | ✅ via `BODY_SIZE_LIMIT` |
351
+ | Request timeout | 30s | ✅ via `BODY_TIMEOUT_SECS` |
352
+ | Handler timeout | 30s | ✅ via `HANDLER_TIMEOUT_SECS` |
353
+ | Path traversal | Blocked | ✅ (guard in place) |
354
+
355
+ ---
356
+
357
+ ## 🧪 Testing Your Server
358
+
359
+ ```bash
360
+ # Check static files
361
+ curl http://localhost:3000/
362
+
363
+ # Check API routes
364
+ curl http://localhost:3000/api/hello
365
+
366
+ # Check ETag
367
+ curl -I http://localhost:3000/styles.css
368
+
369
+ # Test 304 Not Modified
370
+ curl -I http://localhost:3000/styles.css \
371
+ -H "If-None-Match: [etag_from_previous_request]"
372
+
373
+ # Test CORS
374
+ curl -X OPTIONS http://localhost:3000/api/hello \
375
+ -H "Origin: http://example.com"
376
+ ```
377
+
378
+ ---
379
+
380
+ ## ⚙️ Configuration Examples
381
+
382
+ ### Development (All security disabled)
383
+ ```bash
384
+ CORS_ENABLED=true
385
+ BODY_TIMEOUT_SECS=0
386
+ HANDLER_TIMEOUT_SECS=0
387
+ BODY_SIZE_LIMIT=0
388
+ NODE_ENV=development
389
+ ```
390
+
391
+ ### Production (Secure defaults)
392
+ ```bash
393
+ CORS_ENABLED=true
394
+ BODY_TIMEOUT_SECS=30
395
+ HANDLER_TIMEOUT_SECS=30
396
+ BODY_SIZE_LIMIT=10485760
397
+ NODE_ENV=production
398
+ ```
399
+
400
+ ### Internal API (No CORS)
401
+ ```bash
402
+ CORS_ENABLED=false
403
+ BODY_SIZE_LIMIT=5242880 # 5MB
404
+ ```
405
+
406
+ ### File Upload Service
407
+ ```bash
408
+ CORS_ENABLED=true
409
+ BODY_SIZE_LIMIT=1073741824 # 1GB
410
+ BODY_TIMEOUT_SECS=300 # 5 minutes
411
+ ```
197
412
 
198
413
  ---
199
414
 
200
- ## License
415
+ ## 📚 API Reference
416
+
417
+ ### Environment Variables Priority
418
+
419
+ 1. `BINI_*` (highest)
420
+ 2. `VITE_*` (medium)
421
+ 3. No prefix (lowest)
422
+
423
+ ### Returned HTTP Status Codes
424
+
425
+ | Code | Description |
426
+ |------|-------------|
427
+ | `200` | Success |
428
+ | `204` | OPTIONS preflight success |
429
+ | `304` | Not Modified (ETag match) |
430
+ | `400` | Bad Request URL |
431
+ | `404` | Route not found |
432
+ | `408` | Request timeout |
433
+ | `413` | Payload too large |
434
+ | `500` | Internal server error |
435
+
436
+ ### Supported HTTP Methods
437
+
438
+ - `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
439
+ - `OPTIONS` (CORS preflight)
440
+ - `HEAD` (with ETag support)
441
+
442
+ ---
443
+
444
+ ## 🤝 Contributing
445
+
446
+ 1. Fork the repository
447
+ 2. Create your feature branch
448
+ 3. Commit your changes
449
+ 4. Push to the branch
450
+ 5. Open a Pull Request
451
+
452
+ ---
201
453
 
202
- MIT © [Binidu Ranasinghe](https://bini.js.org)
454
+ ## 📝 License
455
+
456
+ MIT © [Binidu Ranasinghe](https://bini.js.org)
457
+
458
+ ---
459
+
460
+ ## 🔗 Links
461
+
462
+ - [GitHub](https://github.com/Binidu01/bini-server)
463
+ - [npm](https://www.npmjs.com/package/bini-server)
464
+ - [Bini.js](https://bini.js.org)
465
+ - [Issues](https://github.com/Binidu01/bini-server/issues)
466
+
467
+ ---
468
+
469
+ <div align="center">
470
+
471
+ **Built with ❤️ by [Binidu Ranasinghe](https://github.com/Binidu01)**
472
+
473
+ </div>
package/dist/cli.js CHANGED
@@ -34,6 +34,84 @@ function detectEnvFiles(root) {
34
34
  ".env"
35
35
  ].filter((f) => fs.existsSync(path.join(root, f)));
36
36
  }
37
+ 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 !== "";
49
+ }
50
+ 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;
55
+ }
56
+ function scanShellRoutes() {
57
+ const shellRoutes = /* @__PURE__ */ new Set();
58
+ const rootDir = DIST_DIR;
59
+ function walkDir(dir, currentPath) {
60
+ 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
+ }
75
+ } catch {
76
+ }
77
+ }
78
+ try {
79
+ walkDir(rootDir, "");
80
+ } catch {
81
+ }
82
+ return shellRoutes;
83
+ }
84
+ function getShellRoutes() {
85
+ if (!shellRouteCache) {
86
+ shellRouteCache = scanShellRoutes();
87
+ }
88
+ return shellRouteCache;
89
+ }
90
+ 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;
111
+ }
112
+ }
113
+ return null;
114
+ }
37
115
  function getNetworkIp() {
38
116
  const ifaces = os.networkInterfaces();
39
117
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
@@ -91,17 +169,15 @@ async function findFreePort(start3) {
91
169
  throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
92
170
  }
93
171
  function startKeyboardLoop(port) {
94
- if (!process.stdin.isTTY) {
95
- return;
96
- }
172
+ if (!process.stdin.isTTY) return;
97
173
  const rl = readline.createInterface({ input: process.stdin });
98
174
  rl.on("line", (line) => {
99
175
  switch (line.trim()) {
100
176
  case "h":
101
177
  console.log("");
102
178
  console.log(" Shortcuts");
103
- console.log(` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
104
- console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
179
+ console.log(` ${C.DIM}press ${C.RESET}o + enter${C.RESET} to open in browser${C.RESET}`);
180
+ console.log(` ${C.DIM}press ${C.RESET}q + enter${C.RESET} to quit${C.RESET}`);
105
181
  console.log("");
106
182
  break;
107
183
  case "o": {
@@ -116,6 +192,20 @@ function startKeyboardLoop(port) {
116
192
  });
117
193
  rl.on("close", () => process.exit(0));
118
194
  }
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
+ }
119
209
  function scanApiRoutes(dir, baseRoute = "", depth = 0) {
120
210
  const routes = [];
121
211
  if (depth > 100 || !fs.existsSync(dir)) return routes;
@@ -125,19 +215,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
125
215
  } catch {
126
216
  return routes;
127
217
  }
128
- for (const entry of entries) {
129
- if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
218
+ for (let i = 0; i < entries.length; i++) {
219
+ const entry = entries[i];
220
+ if (SKIP_PATTERN.test(entry.name)) continue;
130
221
  const fullPath = path.join(dir, entry.name);
131
222
  if (entry.isDirectory()) {
132
- const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
133
- const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
223
+ const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
224
+ const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
134
225
  const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
135
- routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
226
+ const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
227
+ for (let j = 0; j < childRoutes.length; j++) {
228
+ routes.push(childRoutes[j]);
229
+ }
136
230
  continue;
137
231
  }
138
232
  const ext = path.extname(entry.name);
139
- const base = path.basename(entry.name, ext);
140
233
  if (!API_EXTS.has(ext)) continue;
234
+ const base = path.basename(entry.name, ext);
141
235
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
142
236
  const isDynamic = base.startsWith("[") && base.endsWith("]");
143
237
  let routePath;
@@ -230,16 +324,14 @@ function normalizeHeaders(raw) {
230
324
  }
231
325
  return out;
232
326
  }
233
- function invokeHono(honoApp, request) {
234
- return honoApp.fetch(request, process.env);
235
- }
236
327
  async function handleApiRequest(req, res, next) {
237
328
  if (req.method === "OPTIONS") {
238
- res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
329
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
330
+ res.writeHead(204, headers);
239
331
  res.end();
240
332
  return;
241
333
  }
242
- routeCache ??= scanApiRoutes(API_DIR);
334
+ const routes = getRouteCache();
243
335
  const host = req.headers.host ?? "localhost";
244
336
  const rawUrl = `http://${host}${req.url ?? "/"}`;
245
337
  const method = (req.method ?? "GET").toUpperCase();
@@ -254,15 +346,22 @@ async function handleApiRequest(req, res, next) {
254
346
  const { pathname, search } = parsedUrl;
255
347
  let matchedRoute = null;
256
348
  let params = null;
257
- for (const route of routeCache) {
258
- params = matchRoute(route.routePath, pathname);
259
- if (params !== null) {
260
- matchedRoute = route;
261
- break;
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
+ }
262
360
  }
263
361
  }
264
362
  if (!matchedRoute) {
265
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
363
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
364
+ res.writeHead(404, { "Content-Type": "application/json", ...headers });
266
365
  res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
267
366
  return;
268
367
  }
@@ -279,7 +378,8 @@ async function handleApiRequest(req, res, next) {
279
378
  }
280
379
  const handler = await importHandler(matchedRoute.filePath);
281
380
  if (!handler) {
282
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
381
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
382
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
283
383
  res.end(JSON.stringify({ error: "Failed to load handler" }));
284
384
  return;
285
385
  }
@@ -288,7 +388,7 @@ async function handleApiRequest(req, res, next) {
288
388
  try {
289
389
  if (typeof handler.fetch === "function") {
290
390
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
291
- webRes = await invokeHono(handler, new Request(honoUrl, {
391
+ webRes = await handler.fetch(new Request(honoUrl, {
292
392
  method,
293
393
  headers: normalizedHeaders,
294
394
  body: body ? new Uint8Array(body) : null
@@ -310,17 +410,19 @@ async function handleApiRequest(req, res, next) {
310
410
  headers: { "Content-Type": "application/json" }
311
411
  });
312
412
  } else {
313
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
413
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
414
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
314
415
  res.end(JSON.stringify({ error: "Handler has no valid default export" }));
315
416
  return;
316
417
  }
317
418
  } catch (e) {
318
419
  console.error("[bini-api] handler error:", e?.message ?? e);
319
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
420
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
421
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
320
422
  res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
321
423
  return;
322
424
  }
323
- const finalHeaders = { ...CORS_HEADERS };
425
+ const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
324
426
  webRes.headers.forEach((v, k) => {
325
427
  finalHeaders[k] = v;
326
428
  });
@@ -332,7 +434,7 @@ function getETag(stat) {
332
434
  }
333
435
  async function sendFile(filePath, req, res) {
334
436
  const ext = path.extname(filePath).toLowerCase();
335
- const mimeType = MIME[ext] ?? "application/octet-stream";
437
+ const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
336
438
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
337
439
  let stat;
338
440
  try {
@@ -367,15 +469,40 @@ async function sendFile(filePath, req, res) {
367
469
  async function serveStatic(req, res, next) {
368
470
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
369
471
  if (pathname.startsWith("/api")) return next();
370
- const filePath = path.join(DIST_DIR, pathname);
472
+ const hasExtension = path.extname(pathname).length > 0;
473
+ 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
+ }
483
+ return next();
484
+ }
485
+ const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
371
486
  try {
372
- const stat = await fs.promises.stat(filePath);
487
+ const stat = await fs.promises.stat(staticFilePath);
373
488
  if (stat.isFile()) {
374
- await sendFile(filePath, req, res);
489
+ await sendFile(staticFilePath, req, res);
375
490
  return;
376
491
  }
377
492
  } catch {
378
493
  }
494
+ const matchingShell = findMatchingShellRoute(pathname);
495
+ 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
+ }
379
506
  const indexPath = path.join(DIST_DIR, "index.html");
380
507
  try {
381
508
  await fs.promises.access(indexPath);
@@ -410,6 +537,7 @@ async function start() {
410
537
  `);
411
538
  process.exit(1);
412
539
  }
540
+ getShellRoutes();
413
541
  const port = await findFreePort(DEFAULT_PORT);
414
542
  const handler = compose([
415
543
  async (req, res, next) => {
@@ -433,6 +561,7 @@ async function start() {
433
561
  });
434
562
  server.keepAliveTimeout = 65e3;
435
563
  server.headersTimeout = 66e3;
564
+ server.maxHeadersCount = 2e3;
436
565
  startKeyboardLoop(port);
437
566
  server.listen(port, "0.0.0.0", () => {
438
567
  printBanner(port);
@@ -444,17 +573,17 @@ async function start() {
444
573
  process.on("SIGTERM", shutdown);
445
574
  process.on("SIGINT", shutdown);
446
575
  }
447
- var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, API_EXTS, C, moduleCache, CORS_HEADERS, routeCache, MIME;
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;
448
577
  var init_src = __esm({
449
578
  "src/index.ts"() {
450
579
  "use strict";
451
- DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
452
- BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
453
- HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
454
- BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
455
- API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
456
- DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
457
- API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
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);
458
587
  C = {
459
588
  CYAN: "\x1B[36m",
460
589
  RESET: "\x1B[0m",
@@ -464,15 +593,21 @@ var init_src = __esm({
464
593
  BOLD: "\x1B[1m",
465
594
  DIM: "\x1B[2m"
466
595
  };
596
+ 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 = /^[_.]/;
467
603
  moduleCache = /* @__PURE__ */ new Map();
468
604
  CORS_HEADERS = {
469
605
  "Access-Control-Allow-Origin": "*",
470
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
606
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
471
607
  "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
472
608
  "Vary": "Origin"
473
609
  };
474
- routeCache = null;
475
- MIME = {
610
+ MIME_TYPES = {
476
611
  ".html": "text/html; charset=utf-8",
477
612
  ".js": "application/javascript",
478
613
  ".mjs": "application/javascript",
package/dist/index.js CHANGED
@@ -19,13 +19,32 @@ function detectEnvFiles(root) {
19
19
  ".env"
20
20
  ].filter((f) => fs.existsSync(path.join(root, f)));
21
21
  }
22
- var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
23
- var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
24
- var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
25
- var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
26
- var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
27
- var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
28
- var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
22
+ function getEnvVar(key, defaultValue) {
23
+ const biniKey = `BINI_${key}`;
24
+ if (process.env[biniKey] !== void 0) return process.env[biniKey];
25
+ const viteKey = `VITE_${key}`;
26
+ if (process.env[viteKey] !== void 0) return process.env[viteKey];
27
+ if (process.env[key] !== void 0) return process.env[key];
28
+ return defaultValue;
29
+ }
30
+ function getEnvVarBoolean(key, defaultValue) {
31
+ const value = getEnvVar(key);
32
+ if (value === void 0) return defaultValue;
33
+ return value !== "false" && value !== "0" && value !== "";
34
+ }
35
+ function getEnvVarNumber(key, defaultValue) {
36
+ const value = getEnvVar(key);
37
+ if (value === void 0) return defaultValue;
38
+ const parsed = parseInt(value, 10);
39
+ return isNaN(parsed) ? defaultValue : parsed;
40
+ }
41
+ var DEFAULT_PORT = getEnvVarNumber("PORT", 3e3);
42
+ var BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
43
+ var HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
44
+ var BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
45
+ var API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
46
+ var DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
47
+ var CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
29
48
  var C = {
30
49
  CYAN: "\x1B[36m",
31
50
  RESET: "\x1B[0m",
@@ -35,6 +54,66 @@ var C = {
35
54
  BOLD: "\x1B[1m",
36
55
  DIM: "\x1B[2m"
37
56
  };
57
+ function scanShellRoutes() {
58
+ const shellRoutes = /* @__PURE__ */ new Set();
59
+ const rootDir = DIST_DIR;
60
+ function walkDir(dir, currentPath) {
61
+ try {
62
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
63
+ for (const entry of entries) {
64
+ if (!entry.isDirectory()) continue;
65
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
66
+ const fullPath = path.join(dir, entry.name);
67
+ const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
68
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
69
+ const indexPath = path.join(fullPath, "index.html");
70
+ if (fs.existsSync(indexPath)) {
71
+ shellRoutes.add(`/${routePath}`);
72
+ }
73
+ }
74
+ walkDir(fullPath, routePath);
75
+ }
76
+ } catch {
77
+ }
78
+ }
79
+ try {
80
+ walkDir(rootDir, "");
81
+ } catch {
82
+ }
83
+ return shellRoutes;
84
+ }
85
+ var shellRouteCache = null;
86
+ function getShellRoutes() {
87
+ if (!shellRouteCache) {
88
+ shellRouteCache = scanShellRoutes();
89
+ }
90
+ return shellRouteCache;
91
+ }
92
+ function findMatchingShellRoute(pathname) {
93
+ const shellRoutes = getShellRoutes();
94
+ const cleanPath = pathname.replace(/^\/|\/$/g, "");
95
+ const pathSegments = cleanPath.split("/").filter(Boolean);
96
+ for (const shellRoute of shellRoutes) {
97
+ const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
98
+ const shellSegments = cleanShell.split("/").filter(Boolean);
99
+ if (shellSegments.length !== pathSegments.length) continue;
100
+ let matches = true;
101
+ for (let i = 0; i < shellSegments.length; i++) {
102
+ const segment = shellSegments[i];
103
+ if (segment.startsWith("[") && segment.endsWith("]")) {
104
+ continue;
105
+ }
106
+ if (segment !== pathSegments[i]) {
107
+ matches = false;
108
+ break;
109
+ }
110
+ }
111
+ if (matches) {
112
+ return shellRoute;
113
+ }
114
+ }
115
+ return null;
116
+ }
38
117
  function getNetworkIp() {
39
118
  const ifaces = os.networkInterfaces();
40
119
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
@@ -92,17 +171,15 @@ async function findFreePort(start2) {
92
171
  throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
93
172
  }
94
173
  function startKeyboardLoop(port) {
95
- if (!process.stdin.isTTY) {
96
- return;
97
- }
174
+ if (!process.stdin.isTTY) return;
98
175
  const rl = readline.createInterface({ input: process.stdin });
99
176
  rl.on("line", (line) => {
100
177
  switch (line.trim()) {
101
178
  case "h":
102
179
  console.log("");
103
180
  console.log(" Shortcuts");
104
- console.log(` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
105
- console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
181
+ console.log(` ${C.DIM}press ${C.RESET}o + enter${C.RESET} to open in browser${C.RESET}`);
182
+ console.log(` ${C.DIM}press ${C.RESET}q + enter${C.RESET} to quit${C.RESET}`);
106
183
  console.log("");
107
184
  break;
108
185
  case "o": {
@@ -117,6 +194,26 @@ function startKeyboardLoop(port) {
117
194
  });
118
195
  rl.on("close", () => process.exit(0));
119
196
  }
197
+ var routeCache = null;
198
+ var routeIndex = /* @__PURE__ */ new Map();
199
+ var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
200
+ var CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
201
+ var DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
202
+ var SKIP_PATTERN = /^[_.]/;
203
+ function getRouteCache() {
204
+ if (!routeCache) {
205
+ const start2 = Date.now();
206
+ routeCache = scanApiRoutes(API_DIR);
207
+ routeIndex.clear();
208
+ for (let i = 0; i < routeCache.length; i++) {
209
+ routeIndex.set(routeCache[i].routePath, routeCache[i]);
210
+ }
211
+ if (process.env.NODE_ENV === "development") {
212
+ console.log(`[bini-server] API routes scanned in ${Date.now() - start2}ms`);
213
+ }
214
+ }
215
+ return routeCache;
216
+ }
120
217
  function scanApiRoutes(dir, baseRoute = "", depth = 0) {
121
218
  const routes = [];
122
219
  if (depth > 100 || !fs.existsSync(dir)) return routes;
@@ -126,19 +223,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
126
223
  } catch {
127
224
  return routes;
128
225
  }
129
- for (const entry of entries) {
130
- if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
226
+ for (let i = 0; i < entries.length; i++) {
227
+ const entry = entries[i];
228
+ if (SKIP_PATTERN.test(entry.name)) continue;
131
229
  const fullPath = path.join(dir, entry.name);
132
230
  if (entry.isDirectory()) {
133
- const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
134
- const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
231
+ const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
232
+ const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
135
233
  const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
136
- routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
234
+ const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
235
+ for (let j = 0; j < childRoutes.length; j++) {
236
+ routes.push(childRoutes[j]);
237
+ }
137
238
  continue;
138
239
  }
139
240
  const ext = path.extname(entry.name);
140
- const base = path.basename(entry.name, ext);
141
241
  if (!API_EXTS.has(ext)) continue;
242
+ const base = path.basename(entry.name, ext);
142
243
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
143
244
  const isDynamic = base.startsWith("[") && base.endsWith("]");
144
245
  let routePath;
@@ -234,21 +335,18 @@ function normalizeHeaders(raw) {
234
335
  }
235
336
  var CORS_HEADERS = {
236
337
  "Access-Control-Allow-Origin": "*",
237
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
338
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
238
339
  "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
239
340
  "Vary": "Origin"
240
341
  };
241
- function invokeHono(honoApp, request) {
242
- return honoApp.fetch(request, process.env);
243
- }
244
- var routeCache = null;
245
342
  async function handleApiRequest(req, res, next) {
246
343
  if (req.method === "OPTIONS") {
247
- res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
344
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
345
+ res.writeHead(204, headers);
248
346
  res.end();
249
347
  return;
250
348
  }
251
- routeCache ??= scanApiRoutes(API_DIR);
349
+ const routes = getRouteCache();
252
350
  const host = req.headers.host ?? "localhost";
253
351
  const rawUrl = `http://${host}${req.url ?? "/"}`;
254
352
  const method = (req.method ?? "GET").toUpperCase();
@@ -263,15 +361,22 @@ async function handleApiRequest(req, res, next) {
263
361
  const { pathname, search } = parsedUrl;
264
362
  let matchedRoute = null;
265
363
  let params = null;
266
- for (const route of routeCache) {
267
- params = matchRoute(route.routePath, pathname);
268
- if (params !== null) {
269
- matchedRoute = route;
270
- break;
364
+ if (routeIndex.has(pathname)) {
365
+ matchedRoute = routeIndex.get(pathname);
366
+ params = {};
367
+ } else {
368
+ for (let i = 0; i < routes.length; i++) {
369
+ const route = routes[i];
370
+ params = matchRoute(route.routePath, pathname);
371
+ if (params !== null) {
372
+ matchedRoute = route;
373
+ break;
374
+ }
271
375
  }
272
376
  }
273
377
  if (!matchedRoute) {
274
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
378
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
379
+ res.writeHead(404, { "Content-Type": "application/json", ...headers });
275
380
  res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
276
381
  return;
277
382
  }
@@ -288,7 +393,8 @@ async function handleApiRequest(req, res, next) {
288
393
  }
289
394
  const handler = await importHandler(matchedRoute.filePath);
290
395
  if (!handler) {
291
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
396
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
397
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
292
398
  res.end(JSON.stringify({ error: "Failed to load handler" }));
293
399
  return;
294
400
  }
@@ -297,7 +403,7 @@ async function handleApiRequest(req, res, next) {
297
403
  try {
298
404
  if (typeof handler.fetch === "function") {
299
405
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
300
- webRes = await invokeHono(handler, new Request(honoUrl, {
406
+ webRes = await handler.fetch(new Request(honoUrl, {
301
407
  method,
302
408
  headers: normalizedHeaders,
303
409
  body: body ? new Uint8Array(body) : null
@@ -319,52 +425,31 @@ async function handleApiRequest(req, res, next) {
319
425
  headers: { "Content-Type": "application/json" }
320
426
  });
321
427
  } else {
322
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
428
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
429
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
323
430
  res.end(JSON.stringify({ error: "Handler has no valid default export" }));
324
431
  return;
325
432
  }
326
433
  } catch (e) {
327
434
  console.error("[bini-api] handler error:", e?.message ?? e);
328
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
435
+ const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
436
+ res.writeHead(500, { "Content-Type": "application/json", ...headers });
329
437
  res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
330
438
  return;
331
439
  }
332
- const finalHeaders = { ...CORS_HEADERS };
440
+ const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
333
441
  webRes.headers.forEach((v, k) => {
334
442
  finalHeaders[k] = v;
335
443
  });
336
444
  res.writeHead(webRes.status, finalHeaders);
337
445
  res.end(Buffer.from(await webRes.arrayBuffer()));
338
446
  }
339
- var MIME = {
340
- ".html": "text/html; charset=utf-8",
341
- ".js": "application/javascript",
342
- ".mjs": "application/javascript",
343
- ".css": "text/css",
344
- ".json": "application/json",
345
- ".png": "image/png",
346
- ".jpg": "image/jpeg",
347
- ".jpeg": "image/jpeg",
348
- ".gif": "image/gif",
349
- ".svg": "image/svg+xml",
350
- ".ico": "image/x-icon",
351
- ".webp": "image/webp",
352
- ".avif": "image/avif",
353
- ".woff": "font/woff",
354
- ".woff2": "font/woff2",
355
- ".ttf": "font/ttf",
356
- ".eot": "application/vnd.ms-fontobject",
357
- ".txt": "text/plain",
358
- ".xml": "application/xml",
359
- ".webmanifest": "application/manifest+json",
360
- ".map": "application/json"
361
- };
362
447
  function getETag(stat) {
363
448
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
364
449
  }
365
450
  async function sendFile(filePath, req, res) {
366
451
  const ext = path.extname(filePath).toLowerCase();
367
- const mimeType = MIME[ext] ?? "application/octet-stream";
452
+ const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
368
453
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
369
454
  let stat;
370
455
  try {
@@ -396,18 +481,66 @@ async function sendFile(filePath, req, res) {
396
481
  } catch {
397
482
  }
398
483
  }
484
+ var MIME_TYPES = {
485
+ ".html": "text/html; charset=utf-8",
486
+ ".js": "application/javascript",
487
+ ".mjs": "application/javascript",
488
+ ".css": "text/css",
489
+ ".json": "application/json",
490
+ ".png": "image/png",
491
+ ".jpg": "image/jpeg",
492
+ ".jpeg": "image/jpeg",
493
+ ".gif": "image/gif",
494
+ ".svg": "image/svg+xml",
495
+ ".ico": "image/x-icon",
496
+ ".webp": "image/webp",
497
+ ".avif": "image/avif",
498
+ ".woff": "font/woff",
499
+ ".woff2": "font/woff2",
500
+ ".ttf": "font/ttf",
501
+ ".eot": "application/vnd.ms-fontobject",
502
+ ".txt": "text/plain",
503
+ ".xml": "application/xml",
504
+ ".webmanifest": "application/manifest+json",
505
+ ".map": "application/json"
506
+ };
399
507
  async function serveStatic(req, res, next) {
400
508
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
401
509
  if (pathname.startsWith("/api")) return next();
402
- const filePath = path.join(DIST_DIR, pathname);
510
+ const hasExtension = path.extname(pathname).length > 0;
511
+ if (hasExtension) {
512
+ const filePath = path.join(DIST_DIR, pathname);
513
+ try {
514
+ const stat = await fs.promises.stat(filePath);
515
+ if (stat.isFile()) {
516
+ await sendFile(filePath, req, res);
517
+ return;
518
+ }
519
+ } catch {
520
+ }
521
+ return next();
522
+ }
523
+ const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
403
524
  try {
404
- const stat = await fs.promises.stat(filePath);
525
+ const stat = await fs.promises.stat(staticFilePath);
405
526
  if (stat.isFile()) {
406
- await sendFile(filePath, req, res);
527
+ await sendFile(staticFilePath, req, res);
407
528
  return;
408
529
  }
409
530
  } catch {
410
531
  }
532
+ const matchingShell = findMatchingShellRoute(pathname);
533
+ if (matchingShell) {
534
+ const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
535
+ try {
536
+ const stat = await fs.promises.stat(shellPath);
537
+ if (stat.isFile()) {
538
+ await sendFile(shellPath, req, res);
539
+ return;
540
+ }
541
+ } catch {
542
+ }
543
+ }
411
544
  const indexPath = path.join(DIST_DIR, "index.html");
412
545
  try {
413
546
  await fs.promises.access(indexPath);
@@ -442,6 +575,7 @@ async function start() {
442
575
  `);
443
576
  process.exit(1);
444
577
  }
578
+ getShellRoutes();
445
579
  const port = await findFreePort(DEFAULT_PORT);
446
580
  const handler = compose([
447
581
  async (req, res, next) => {
@@ -465,6 +599,7 @@ async function start() {
465
599
  });
466
600
  server.keepAliveTimeout = 65e3;
467
601
  server.headersTimeout = 66e3;
602
+ server.maxHeadersCount = 2e3;
468
603
  startKeyboardLoop(port);
469
604
  server.listen(port, "0.0.0.0", () => {
470
605
  printBanner(port);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.9",
3
+ "version": "2.0.0",
4
4
  "description": "Production server for bini-router apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -40,6 +40,7 @@
40
40
  "bini-router",
41
41
  "server",
42
42
  "spa",
43
+ "ssg",
43
44
  "vite",
44
45
  "hono",
45
46
  "production",
@@ -59,9 +60,8 @@
59
60
  "url": "https://github.com/Binidu01/bini-server/issues"
60
61
  },
61
62
  "devDependencies": {
62
- "@types/node": "^25.7.0",
63
+ "@types/node": "^26.1.2",
63
64
  "tsup": "^8.5.1",
64
- "typescript": "^6.0.3",
65
- "dotenv": "^17.4.2"
65
+ "typescript": "^6.0.3"
66
66
  }
67
67
  }