bini-server 1.0.9 → 1.0.10
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 +348 -77
- package/dist/cli.js +90 -30
- package/dist/index.js +111 -51
- package/package.json +3 -4
package/README.md
CHANGED
|
@@ -5,49 +5,66 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/bini-server)
|
|
6
6
|
[](./LICENSE)
|
|
7
7
|
[](https://nodejs.org)
|
|
8
|
+
[](https://bundlephobia.com/package/bini-server)
|
|
9
|
+
[](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
|
-
|
|
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
|
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
- 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
|
|
23
|
-
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
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
|
|
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
|
-
|
|
78
|
+
### 2. Build and Start
|
|
62
79
|
|
|
63
80
|
```bash
|
|
64
|
-
npm run build #
|
|
65
|
-
npm start #
|
|
81
|
+
npm run build # Build your app
|
|
82
|
+
npm start # Serve in production
|
|
66
83
|
```
|
|
67
84
|
|
|
68
|
-
Terminal
|
|
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
|
-
|
|
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
|
-
|
|
113
|
+
### Auto-Detected `.env` Files
|
|
95
114
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
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
|
-
| `
|
|
110
|
-
| `
|
|
111
|
-
| `
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
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
|
-
|
|
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
|
-
|
|
153
|
+
# Or inline
|
|
154
|
+
PORT=3001 BINI_CORS_ENABLED=false bini-server
|
|
120
155
|
|
|
121
|
-
|
|
156
|
+
# Or with VITE prefix
|
|
157
|
+
VITE_PORT=3000 VITE_CORS_ENABLED=false bini-server
|
|
158
|
+
```
|
|
122
159
|
|
|
123
160
|
---
|
|
124
161
|
|
|
125
|
-
##
|
|
162
|
+
## 📁 Project Structure
|
|
126
163
|
|
|
127
|
-
|
|
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
|
-
|
|
130
|
-
|
|
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
|
-
|
|
134
|
-
|
|
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
|
-
|
|
228
|
+
### CORS
|
|
229
|
+
|
|
230
|
+
CORS is **enabled by default** with these headers:
|
|
138
231
|
|
|
139
232
|
```
|
|
140
|
-
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
###
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
-
|
|
|
191
|
-
| Body
|
|
192
|
-
|
|
|
193
|
-
| Handler timeout | ❌ | ✅ 30s |
|
|
333
|
+
| Body timeout | ❌ | ✅ (30s) |
|
|
334
|
+
| Body size limit | ❌ | ✅ (10MB) |
|
|
335
|
+
| Handler timeout | ❌ | ✅ (30s) |
|
|
194
336
|
| Graceful shutdown | ❌ | ✅ |
|
|
195
|
-
|
|
|
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
|
-
##
|
|
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
|
-
|
|
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,31 @@ 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) {
|
|
40
|
+
return process.env[biniKey];
|
|
41
|
+
}
|
|
42
|
+
const viteKey = `VITE_${key}`;
|
|
43
|
+
if (process.env[viteKey] !== void 0) {
|
|
44
|
+
return process.env[viteKey];
|
|
45
|
+
}
|
|
46
|
+
if (process.env[key] !== void 0) {
|
|
47
|
+
return process.env[key];
|
|
48
|
+
}
|
|
49
|
+
return defaultValue;
|
|
50
|
+
}
|
|
51
|
+
function getEnvVarBoolean(key, defaultValue) {
|
|
52
|
+
const value = getEnvVar(key);
|
|
53
|
+
if (value === void 0) return defaultValue;
|
|
54
|
+
return value !== "false" && value !== "0" && value !== "";
|
|
55
|
+
}
|
|
56
|
+
function getEnvVarNumber(key, defaultValue) {
|
|
57
|
+
const value = getEnvVar(key);
|
|
58
|
+
if (value === void 0) return defaultValue;
|
|
59
|
+
const parsed = parseInt(value, 10);
|
|
60
|
+
return isNaN(parsed) ? defaultValue : parsed;
|
|
61
|
+
}
|
|
37
62
|
function getNetworkIp() {
|
|
38
63
|
const ifaces = os.networkInterfaces();
|
|
39
64
|
const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
|
|
@@ -116,6 +141,20 @@ function startKeyboardLoop(port) {
|
|
|
116
141
|
});
|
|
117
142
|
rl.on("close", () => process.exit(0));
|
|
118
143
|
}
|
|
144
|
+
function getRouteCache() {
|
|
145
|
+
if (!routeCache) {
|
|
146
|
+
const start3 = Date.now();
|
|
147
|
+
routeCache = scanApiRoutes(API_DIR);
|
|
148
|
+
routeIndex.clear();
|
|
149
|
+
for (let i = 0; i < routeCache.length; i++) {
|
|
150
|
+
routeIndex.set(routeCache[i].routePath, routeCache[i]);
|
|
151
|
+
}
|
|
152
|
+
if (process.env.NODE_ENV === "development") {
|
|
153
|
+
console.log(`[bini-server] Routes scanned in ${Date.now() - start3}ms`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return routeCache;
|
|
157
|
+
}
|
|
119
158
|
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
120
159
|
const routes = [];
|
|
121
160
|
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
@@ -125,19 +164,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
|
125
164
|
} catch {
|
|
126
165
|
return routes;
|
|
127
166
|
}
|
|
128
|
-
for (
|
|
129
|
-
|
|
167
|
+
for (let i = 0; i < entries.length; i++) {
|
|
168
|
+
const entry = entries[i];
|
|
169
|
+
if (SKIP_PATTERN.test(entry.name)) continue;
|
|
130
170
|
const fullPath = path.join(dir, entry.name);
|
|
131
171
|
if (entry.isDirectory()) {
|
|
132
|
-
const isCatchAll2 =
|
|
133
|
-
const isDynamic2 =
|
|
172
|
+
const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
|
|
173
|
+
const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
|
|
134
174
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
135
|
-
|
|
175
|
+
const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
|
|
176
|
+
for (let j = 0; j < childRoutes.length; j++) {
|
|
177
|
+
routes.push(childRoutes[j]);
|
|
178
|
+
}
|
|
136
179
|
continue;
|
|
137
180
|
}
|
|
138
181
|
const ext = path.extname(entry.name);
|
|
139
|
-
const base = path.basename(entry.name, ext);
|
|
140
182
|
if (!API_EXTS.has(ext)) continue;
|
|
183
|
+
const base = path.basename(entry.name, ext);
|
|
141
184
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
142
185
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
143
186
|
let routePath;
|
|
@@ -235,11 +278,12 @@ function invokeHono(honoApp, request) {
|
|
|
235
278
|
}
|
|
236
279
|
async function handleApiRequest(req, res, next) {
|
|
237
280
|
if (req.method === "OPTIONS") {
|
|
238
|
-
|
|
281
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
|
|
282
|
+
res.writeHead(204, headers);
|
|
239
283
|
res.end();
|
|
240
284
|
return;
|
|
241
285
|
}
|
|
242
|
-
|
|
286
|
+
const routes = getRouteCache();
|
|
243
287
|
const host = req.headers.host ?? "localhost";
|
|
244
288
|
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
245
289
|
const method = (req.method ?? "GET").toUpperCase();
|
|
@@ -254,15 +298,22 @@ async function handleApiRequest(req, res, next) {
|
|
|
254
298
|
const { pathname, search } = parsedUrl;
|
|
255
299
|
let matchedRoute = null;
|
|
256
300
|
let params = null;
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
301
|
+
if (routeIndex.has(pathname)) {
|
|
302
|
+
matchedRoute = routeIndex.get(pathname);
|
|
303
|
+
params = {};
|
|
304
|
+
} else {
|
|
305
|
+
for (let i = 0; i < routes.length; i++) {
|
|
306
|
+
const route = routes[i];
|
|
307
|
+
params = matchRoute(route.routePath, pathname);
|
|
308
|
+
if (params !== null) {
|
|
309
|
+
matchedRoute = route;
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
262
312
|
}
|
|
263
313
|
}
|
|
264
314
|
if (!matchedRoute) {
|
|
265
|
-
|
|
315
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
316
|
+
res.writeHead(404, { "Content-Type": "application/json", ...headers });
|
|
266
317
|
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
267
318
|
return;
|
|
268
319
|
}
|
|
@@ -279,7 +330,8 @@ async function handleApiRequest(req, res, next) {
|
|
|
279
330
|
}
|
|
280
331
|
const handler = await importHandler(matchedRoute.filePath);
|
|
281
332
|
if (!handler) {
|
|
282
|
-
|
|
333
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
334
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
283
335
|
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
284
336
|
return;
|
|
285
337
|
}
|
|
@@ -310,17 +362,19 @@ async function handleApiRequest(req, res, next) {
|
|
|
310
362
|
headers: { "Content-Type": "application/json" }
|
|
311
363
|
});
|
|
312
364
|
} else {
|
|
313
|
-
|
|
365
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
366
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
314
367
|
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
315
368
|
return;
|
|
316
369
|
}
|
|
317
370
|
} catch (e) {
|
|
318
371
|
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
319
|
-
|
|
372
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
373
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
320
374
|
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
321
375
|
return;
|
|
322
376
|
}
|
|
323
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
377
|
+
const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
324
378
|
webRes.headers.forEach((v, k) => {
|
|
325
379
|
finalHeaders[k] = v;
|
|
326
380
|
});
|
|
@@ -332,7 +386,7 @@ function getETag(stat) {
|
|
|
332
386
|
}
|
|
333
387
|
async function sendFile(filePath, req, res) {
|
|
334
388
|
const ext = path.extname(filePath).toLowerCase();
|
|
335
|
-
const mimeType =
|
|
389
|
+
const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
336
390
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
337
391
|
let stat;
|
|
338
392
|
try {
|
|
@@ -433,6 +487,7 @@ async function start() {
|
|
|
433
487
|
});
|
|
434
488
|
server.keepAliveTimeout = 65e3;
|
|
435
489
|
server.headersTimeout = 66e3;
|
|
490
|
+
server.maxHeadersCount = 2e3;
|
|
436
491
|
startKeyboardLoop(port);
|
|
437
492
|
server.listen(port, "0.0.0.0", () => {
|
|
438
493
|
printBanner(port);
|
|
@@ -444,17 +499,17 @@ async function start() {
|
|
|
444
499
|
process.on("SIGTERM", shutdown);
|
|
445
500
|
process.on("SIGINT", shutdown);
|
|
446
501
|
}
|
|
447
|
-
var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR,
|
|
502
|
+
var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, CORS_ENABLED, C, API_EXTS, CATCH_ALL_PATTERN, DYNAMIC_PATTERN, SKIP_PATTERN, routeCache, routeIndex, moduleCache, CORS_HEADERS, MIME_TYPES;
|
|
448
503
|
var init_src = __esm({
|
|
449
504
|
"src/index.ts"() {
|
|
450
505
|
"use strict";
|
|
451
|
-
DEFAULT_PORT =
|
|
452
|
-
BODY_TIMEOUT =
|
|
453
|
-
HANDLER_TIMEOUT =
|
|
454
|
-
BODY_SIZE_LIMIT =
|
|
455
|
-
API_DIR = path.join(process.cwd(),
|
|
456
|
-
DIST_DIR = path.join(process.cwd(),
|
|
457
|
-
|
|
506
|
+
DEFAULT_PORT = getEnvVarNumber("PORT", 3e3);
|
|
507
|
+
BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
|
|
508
|
+
HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
|
|
509
|
+
BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
|
|
510
|
+
API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
|
|
511
|
+
DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
|
|
512
|
+
CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
|
|
458
513
|
C = {
|
|
459
514
|
CYAN: "\x1B[36m",
|
|
460
515
|
RESET: "\x1B[0m",
|
|
@@ -464,15 +519,20 @@ var init_src = __esm({
|
|
|
464
519
|
BOLD: "\x1B[1m",
|
|
465
520
|
DIM: "\x1B[2m"
|
|
466
521
|
};
|
|
522
|
+
API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
|
|
523
|
+
CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
|
|
524
|
+
DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
|
|
525
|
+
SKIP_PATTERN = /^[_.]/;
|
|
526
|
+
routeCache = null;
|
|
527
|
+
routeIndex = /* @__PURE__ */ new Map();
|
|
467
528
|
moduleCache = /* @__PURE__ */ new Map();
|
|
468
529
|
CORS_HEADERS = {
|
|
469
530
|
"Access-Control-Allow-Origin": "*",
|
|
470
|
-
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
531
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
|
|
471
532
|
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
472
533
|
"Vary": "Origin"
|
|
473
534
|
};
|
|
474
|
-
|
|
475
|
-
MIME = {
|
|
535
|
+
MIME_TYPES = {
|
|
476
536
|
".html": "text/html; charset=utf-8",
|
|
477
537
|
".js": "application/javascript",
|
|
478
538
|
".mjs": "application/javascript",
|
package/dist/index.js
CHANGED
|
@@ -19,13 +19,38 @@ function detectEnvFiles(root) {
|
|
|
19
19
|
".env"
|
|
20
20
|
].filter((f) => fs.existsSync(path.join(root, f)));
|
|
21
21
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
22
|
+
function getEnvVar(key, defaultValue) {
|
|
23
|
+
const biniKey = `BINI_${key}`;
|
|
24
|
+
if (process.env[biniKey] !== void 0) {
|
|
25
|
+
return process.env[biniKey];
|
|
26
|
+
}
|
|
27
|
+
const viteKey = `VITE_${key}`;
|
|
28
|
+
if (process.env[viteKey] !== void 0) {
|
|
29
|
+
return process.env[viteKey];
|
|
30
|
+
}
|
|
31
|
+
if (process.env[key] !== void 0) {
|
|
32
|
+
return process.env[key];
|
|
33
|
+
}
|
|
34
|
+
return defaultValue;
|
|
35
|
+
}
|
|
36
|
+
function getEnvVarBoolean(key, defaultValue) {
|
|
37
|
+
const value = getEnvVar(key);
|
|
38
|
+
if (value === void 0) return defaultValue;
|
|
39
|
+
return value !== "false" && value !== "0" && value !== "";
|
|
40
|
+
}
|
|
41
|
+
function getEnvVarNumber(key, defaultValue) {
|
|
42
|
+
const value = getEnvVar(key);
|
|
43
|
+
if (value === void 0) return defaultValue;
|
|
44
|
+
const parsed = parseInt(value, 10);
|
|
45
|
+
return isNaN(parsed) ? defaultValue : parsed;
|
|
46
|
+
}
|
|
47
|
+
var DEFAULT_PORT = getEnvVarNumber("PORT", 3e3);
|
|
48
|
+
var BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
|
|
49
|
+
var HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
|
|
50
|
+
var BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
|
|
51
|
+
var API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
|
|
52
|
+
var DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
|
|
53
|
+
var CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
|
|
29
54
|
var C = {
|
|
30
55
|
CYAN: "\x1B[36m",
|
|
31
56
|
RESET: "\x1B[0m",
|
|
@@ -117,6 +142,26 @@ function startKeyboardLoop(port) {
|
|
|
117
142
|
});
|
|
118
143
|
rl.on("close", () => process.exit(0));
|
|
119
144
|
}
|
|
145
|
+
var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
|
|
146
|
+
var CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
|
|
147
|
+
var DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
|
|
148
|
+
var SKIP_PATTERN = /^[_.]/;
|
|
149
|
+
var routeCache = null;
|
|
150
|
+
var routeIndex = /* @__PURE__ */ new Map();
|
|
151
|
+
function getRouteCache() {
|
|
152
|
+
if (!routeCache) {
|
|
153
|
+
const start2 = Date.now();
|
|
154
|
+
routeCache = scanApiRoutes(API_DIR);
|
|
155
|
+
routeIndex.clear();
|
|
156
|
+
for (let i = 0; i < routeCache.length; i++) {
|
|
157
|
+
routeIndex.set(routeCache[i].routePath, routeCache[i]);
|
|
158
|
+
}
|
|
159
|
+
if (process.env.NODE_ENV === "development") {
|
|
160
|
+
console.log(`[bini-server] Routes scanned in ${Date.now() - start2}ms`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return routeCache;
|
|
164
|
+
}
|
|
120
165
|
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
121
166
|
const routes = [];
|
|
122
167
|
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
@@ -126,19 +171,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
|
126
171
|
} catch {
|
|
127
172
|
return routes;
|
|
128
173
|
}
|
|
129
|
-
for (
|
|
130
|
-
|
|
174
|
+
for (let i = 0; i < entries.length; i++) {
|
|
175
|
+
const entry = entries[i];
|
|
176
|
+
if (SKIP_PATTERN.test(entry.name)) continue;
|
|
131
177
|
const fullPath = path.join(dir, entry.name);
|
|
132
178
|
if (entry.isDirectory()) {
|
|
133
|
-
const isCatchAll2 =
|
|
134
|
-
const isDynamic2 =
|
|
179
|
+
const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
|
|
180
|
+
const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
|
|
135
181
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
136
|
-
|
|
182
|
+
const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
|
|
183
|
+
for (let j = 0; j < childRoutes.length; j++) {
|
|
184
|
+
routes.push(childRoutes[j]);
|
|
185
|
+
}
|
|
137
186
|
continue;
|
|
138
187
|
}
|
|
139
188
|
const ext = path.extname(entry.name);
|
|
140
|
-
const base = path.basename(entry.name, ext);
|
|
141
189
|
if (!API_EXTS.has(ext)) continue;
|
|
190
|
+
const base = path.basename(entry.name, ext);
|
|
142
191
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
143
192
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
144
193
|
let routePath;
|
|
@@ -234,21 +283,21 @@ function normalizeHeaders(raw) {
|
|
|
234
283
|
}
|
|
235
284
|
var CORS_HEADERS = {
|
|
236
285
|
"Access-Control-Allow-Origin": "*",
|
|
237
|
-
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
286
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
|
|
238
287
|
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
239
288
|
"Vary": "Origin"
|
|
240
289
|
};
|
|
241
290
|
function invokeHono(honoApp, request) {
|
|
242
291
|
return honoApp.fetch(request, process.env);
|
|
243
292
|
}
|
|
244
|
-
var routeCache = null;
|
|
245
293
|
async function handleApiRequest(req, res, next) {
|
|
246
294
|
if (req.method === "OPTIONS") {
|
|
247
|
-
|
|
295
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
|
|
296
|
+
res.writeHead(204, headers);
|
|
248
297
|
res.end();
|
|
249
298
|
return;
|
|
250
299
|
}
|
|
251
|
-
|
|
300
|
+
const routes = getRouteCache();
|
|
252
301
|
const host = req.headers.host ?? "localhost";
|
|
253
302
|
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
254
303
|
const method = (req.method ?? "GET").toUpperCase();
|
|
@@ -263,15 +312,22 @@ async function handleApiRequest(req, res, next) {
|
|
|
263
312
|
const { pathname, search } = parsedUrl;
|
|
264
313
|
let matchedRoute = null;
|
|
265
314
|
let params = null;
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
315
|
+
if (routeIndex.has(pathname)) {
|
|
316
|
+
matchedRoute = routeIndex.get(pathname);
|
|
317
|
+
params = {};
|
|
318
|
+
} else {
|
|
319
|
+
for (let i = 0; i < routes.length; i++) {
|
|
320
|
+
const route = routes[i];
|
|
321
|
+
params = matchRoute(route.routePath, pathname);
|
|
322
|
+
if (params !== null) {
|
|
323
|
+
matchedRoute = route;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
271
326
|
}
|
|
272
327
|
}
|
|
273
328
|
if (!matchedRoute) {
|
|
274
|
-
|
|
329
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
330
|
+
res.writeHead(404, { "Content-Type": "application/json", ...headers });
|
|
275
331
|
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
276
332
|
return;
|
|
277
333
|
}
|
|
@@ -288,7 +344,8 @@ async function handleApiRequest(req, res, next) {
|
|
|
288
344
|
}
|
|
289
345
|
const handler = await importHandler(matchedRoute.filePath);
|
|
290
346
|
if (!handler) {
|
|
291
|
-
|
|
347
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
348
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
292
349
|
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
293
350
|
return;
|
|
294
351
|
}
|
|
@@ -319,52 +376,31 @@ async function handleApiRequest(req, res, next) {
|
|
|
319
376
|
headers: { "Content-Type": "application/json" }
|
|
320
377
|
});
|
|
321
378
|
} else {
|
|
322
|
-
|
|
379
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
380
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
323
381
|
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
324
382
|
return;
|
|
325
383
|
}
|
|
326
384
|
} catch (e) {
|
|
327
385
|
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
328
|
-
|
|
386
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
387
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
329
388
|
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
330
389
|
return;
|
|
331
390
|
}
|
|
332
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
391
|
+
const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
333
392
|
webRes.headers.forEach((v, k) => {
|
|
334
393
|
finalHeaders[k] = v;
|
|
335
394
|
});
|
|
336
395
|
res.writeHead(webRes.status, finalHeaders);
|
|
337
396
|
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
338
397
|
}
|
|
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
398
|
function getETag(stat) {
|
|
363
399
|
return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
|
|
364
400
|
}
|
|
365
401
|
async function sendFile(filePath, req, res) {
|
|
366
402
|
const ext = path.extname(filePath).toLowerCase();
|
|
367
|
-
const mimeType =
|
|
403
|
+
const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
368
404
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
369
405
|
let stat;
|
|
370
406
|
try {
|
|
@@ -396,6 +432,29 @@ async function sendFile(filePath, req, res) {
|
|
|
396
432
|
} catch {
|
|
397
433
|
}
|
|
398
434
|
}
|
|
435
|
+
var MIME_TYPES = {
|
|
436
|
+
".html": "text/html; charset=utf-8",
|
|
437
|
+
".js": "application/javascript",
|
|
438
|
+
".mjs": "application/javascript",
|
|
439
|
+
".css": "text/css",
|
|
440
|
+
".json": "application/json",
|
|
441
|
+
".png": "image/png",
|
|
442
|
+
".jpg": "image/jpeg",
|
|
443
|
+
".jpeg": "image/jpeg",
|
|
444
|
+
".gif": "image/gif",
|
|
445
|
+
".svg": "image/svg+xml",
|
|
446
|
+
".ico": "image/x-icon",
|
|
447
|
+
".webp": "image/webp",
|
|
448
|
+
".avif": "image/avif",
|
|
449
|
+
".woff": "font/woff",
|
|
450
|
+
".woff2": "font/woff2",
|
|
451
|
+
".ttf": "font/ttf",
|
|
452
|
+
".eot": "application/vnd.ms-fontobject",
|
|
453
|
+
".txt": "text/plain",
|
|
454
|
+
".xml": "application/xml",
|
|
455
|
+
".webmanifest": "application/manifest+json",
|
|
456
|
+
".map": "application/json"
|
|
457
|
+
};
|
|
399
458
|
async function serveStatic(req, res, next) {
|
|
400
459
|
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
401
460
|
if (pathname.startsWith("/api")) return next();
|
|
@@ -465,6 +524,7 @@ async function start() {
|
|
|
465
524
|
});
|
|
466
525
|
server.keepAliveTimeout = 65e3;
|
|
467
526
|
server.headersTimeout = 66e3;
|
|
527
|
+
server.maxHeadersCount = 2e3;
|
|
468
528
|
startKeyboardLoop(port);
|
|
469
529
|
server.listen(port, "0.0.0.0", () => {
|
|
470
530
|
printBanner(port);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bini-server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.10",
|
|
4
4
|
"description": "Production server for bini-router apps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -59,9 +59,8 @@
|
|
|
59
59
|
"url": "https://github.com/Binidu01/bini-server/issues"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
-
"@types/node": "^
|
|
62
|
+
"@types/node": "^26.1.2",
|
|
63
63
|
"tsup": "^8.5.1",
|
|
64
|
-
"typescript": "^6.0.3"
|
|
65
|
-
"dotenv": "^17.4.2"
|
|
64
|
+
"typescript": "^6.0.3"
|
|
66
65
|
}
|
|
67
66
|
}
|