bini-server 1.0.8 → 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 +93 -30
- package/dist/index.js +114 -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;
|
|
@@ -91,6 +116,9 @@ async function findFreePort(start3) {
|
|
|
91
116
|
throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
|
|
92
117
|
}
|
|
93
118
|
function startKeyboardLoop(port) {
|
|
119
|
+
if (!process.stdin.isTTY) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
94
122
|
const rl = readline.createInterface({ input: process.stdin });
|
|
95
123
|
rl.on("line", (line) => {
|
|
96
124
|
switch (line.trim()) {
|
|
@@ -113,6 +141,20 @@ function startKeyboardLoop(port) {
|
|
|
113
141
|
});
|
|
114
142
|
rl.on("close", () => process.exit(0));
|
|
115
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
|
+
}
|
|
116
158
|
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
117
159
|
const routes = [];
|
|
118
160
|
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
@@ -122,19 +164,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
|
122
164
|
} catch {
|
|
123
165
|
return routes;
|
|
124
166
|
}
|
|
125
|
-
for (
|
|
126
|
-
|
|
167
|
+
for (let i = 0; i < entries.length; i++) {
|
|
168
|
+
const entry = entries[i];
|
|
169
|
+
if (SKIP_PATTERN.test(entry.name)) continue;
|
|
127
170
|
const fullPath = path.join(dir, entry.name);
|
|
128
171
|
if (entry.isDirectory()) {
|
|
129
|
-
const isCatchAll2 =
|
|
130
|
-
const isDynamic2 =
|
|
172
|
+
const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
|
|
173
|
+
const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
|
|
131
174
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
132
|
-
|
|
175
|
+
const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
|
|
176
|
+
for (let j = 0; j < childRoutes.length; j++) {
|
|
177
|
+
routes.push(childRoutes[j]);
|
|
178
|
+
}
|
|
133
179
|
continue;
|
|
134
180
|
}
|
|
135
181
|
const ext = path.extname(entry.name);
|
|
136
|
-
const base = path.basename(entry.name, ext);
|
|
137
182
|
if (!API_EXTS.has(ext)) continue;
|
|
183
|
+
const base = path.basename(entry.name, ext);
|
|
138
184
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
139
185
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
140
186
|
let routePath;
|
|
@@ -232,11 +278,12 @@ function invokeHono(honoApp, request) {
|
|
|
232
278
|
}
|
|
233
279
|
async function handleApiRequest(req, res, next) {
|
|
234
280
|
if (req.method === "OPTIONS") {
|
|
235
|
-
|
|
281
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
|
|
282
|
+
res.writeHead(204, headers);
|
|
236
283
|
res.end();
|
|
237
284
|
return;
|
|
238
285
|
}
|
|
239
|
-
|
|
286
|
+
const routes = getRouteCache();
|
|
240
287
|
const host = req.headers.host ?? "localhost";
|
|
241
288
|
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
242
289
|
const method = (req.method ?? "GET").toUpperCase();
|
|
@@ -251,15 +298,22 @@ async function handleApiRequest(req, res, next) {
|
|
|
251
298
|
const { pathname, search } = parsedUrl;
|
|
252
299
|
let matchedRoute = null;
|
|
253
300
|
let params = null;
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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
|
+
}
|
|
259
312
|
}
|
|
260
313
|
}
|
|
261
314
|
if (!matchedRoute) {
|
|
262
|
-
|
|
315
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
316
|
+
res.writeHead(404, { "Content-Type": "application/json", ...headers });
|
|
263
317
|
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
264
318
|
return;
|
|
265
319
|
}
|
|
@@ -276,7 +330,8 @@ async function handleApiRequest(req, res, next) {
|
|
|
276
330
|
}
|
|
277
331
|
const handler = await importHandler(matchedRoute.filePath);
|
|
278
332
|
if (!handler) {
|
|
279
|
-
|
|
333
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
334
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
280
335
|
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
281
336
|
return;
|
|
282
337
|
}
|
|
@@ -307,17 +362,19 @@ async function handleApiRequest(req, res, next) {
|
|
|
307
362
|
headers: { "Content-Type": "application/json" }
|
|
308
363
|
});
|
|
309
364
|
} else {
|
|
310
|
-
|
|
365
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
366
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
311
367
|
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
312
368
|
return;
|
|
313
369
|
}
|
|
314
370
|
} catch (e) {
|
|
315
371
|
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
316
|
-
|
|
372
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
373
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
317
374
|
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
318
375
|
return;
|
|
319
376
|
}
|
|
320
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
377
|
+
const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
321
378
|
webRes.headers.forEach((v, k) => {
|
|
322
379
|
finalHeaders[k] = v;
|
|
323
380
|
});
|
|
@@ -329,7 +386,7 @@ function getETag(stat) {
|
|
|
329
386
|
}
|
|
330
387
|
async function sendFile(filePath, req, res) {
|
|
331
388
|
const ext = path.extname(filePath).toLowerCase();
|
|
332
|
-
const mimeType =
|
|
389
|
+
const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
333
390
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
334
391
|
let stat;
|
|
335
392
|
try {
|
|
@@ -430,6 +487,7 @@ async function start() {
|
|
|
430
487
|
});
|
|
431
488
|
server.keepAliveTimeout = 65e3;
|
|
432
489
|
server.headersTimeout = 66e3;
|
|
490
|
+
server.maxHeadersCount = 2e3;
|
|
433
491
|
startKeyboardLoop(port);
|
|
434
492
|
server.listen(port, "0.0.0.0", () => {
|
|
435
493
|
printBanner(port);
|
|
@@ -441,17 +499,17 @@ async function start() {
|
|
|
441
499
|
process.on("SIGTERM", shutdown);
|
|
442
500
|
process.on("SIGINT", shutdown);
|
|
443
501
|
}
|
|
444
|
-
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;
|
|
445
503
|
var init_src = __esm({
|
|
446
504
|
"src/index.ts"() {
|
|
447
505
|
"use strict";
|
|
448
|
-
DEFAULT_PORT =
|
|
449
|
-
BODY_TIMEOUT =
|
|
450
|
-
HANDLER_TIMEOUT =
|
|
451
|
-
BODY_SIZE_LIMIT =
|
|
452
|
-
API_DIR = path.join(process.cwd(),
|
|
453
|
-
DIST_DIR = path.join(process.cwd(),
|
|
454
|
-
|
|
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);
|
|
455
513
|
C = {
|
|
456
514
|
CYAN: "\x1B[36m",
|
|
457
515
|
RESET: "\x1B[0m",
|
|
@@ -461,15 +519,20 @@ var init_src = __esm({
|
|
|
461
519
|
BOLD: "\x1B[1m",
|
|
462
520
|
DIM: "\x1B[2m"
|
|
463
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();
|
|
464
528
|
moduleCache = /* @__PURE__ */ new Map();
|
|
465
529
|
CORS_HEADERS = {
|
|
466
530
|
"Access-Control-Allow-Origin": "*",
|
|
467
|
-
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
531
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
|
|
468
532
|
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
469
533
|
"Vary": "Origin"
|
|
470
534
|
};
|
|
471
|
-
|
|
472
|
-
MIME = {
|
|
535
|
+
MIME_TYPES = {
|
|
473
536
|
".html": "text/html; charset=utf-8",
|
|
474
537
|
".js": "application/javascript",
|
|
475
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",
|
|
@@ -92,6 +117,9 @@ async function findFreePort(start2) {
|
|
|
92
117
|
throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
|
|
93
118
|
}
|
|
94
119
|
function startKeyboardLoop(port) {
|
|
120
|
+
if (!process.stdin.isTTY) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
95
123
|
const rl = readline.createInterface({ input: process.stdin });
|
|
96
124
|
rl.on("line", (line) => {
|
|
97
125
|
switch (line.trim()) {
|
|
@@ -114,6 +142,26 @@ function startKeyboardLoop(port) {
|
|
|
114
142
|
});
|
|
115
143
|
rl.on("close", () => process.exit(0));
|
|
116
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
|
+
}
|
|
117
165
|
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
118
166
|
const routes = [];
|
|
119
167
|
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
@@ -123,19 +171,23 @@ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
|
123
171
|
} catch {
|
|
124
172
|
return routes;
|
|
125
173
|
}
|
|
126
|
-
for (
|
|
127
|
-
|
|
174
|
+
for (let i = 0; i < entries.length; i++) {
|
|
175
|
+
const entry = entries[i];
|
|
176
|
+
if (SKIP_PATTERN.test(entry.name)) continue;
|
|
128
177
|
const fullPath = path.join(dir, entry.name);
|
|
129
178
|
if (entry.isDirectory()) {
|
|
130
|
-
const isCatchAll2 =
|
|
131
|
-
const isDynamic2 =
|
|
179
|
+
const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
|
|
180
|
+
const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
|
|
132
181
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
133
|
-
|
|
182
|
+
const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
|
|
183
|
+
for (let j = 0; j < childRoutes.length; j++) {
|
|
184
|
+
routes.push(childRoutes[j]);
|
|
185
|
+
}
|
|
134
186
|
continue;
|
|
135
187
|
}
|
|
136
188
|
const ext = path.extname(entry.name);
|
|
137
|
-
const base = path.basename(entry.name, ext);
|
|
138
189
|
if (!API_EXTS.has(ext)) continue;
|
|
190
|
+
const base = path.basename(entry.name, ext);
|
|
139
191
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
140
192
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
141
193
|
let routePath;
|
|
@@ -231,21 +283,21 @@ function normalizeHeaders(raw) {
|
|
|
231
283
|
}
|
|
232
284
|
var CORS_HEADERS = {
|
|
233
285
|
"Access-Control-Allow-Origin": "*",
|
|
234
|
-
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
286
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
|
|
235
287
|
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
236
288
|
"Vary": "Origin"
|
|
237
289
|
};
|
|
238
290
|
function invokeHono(honoApp, request) {
|
|
239
291
|
return honoApp.fetch(request, process.env);
|
|
240
292
|
}
|
|
241
|
-
var routeCache = null;
|
|
242
293
|
async function handleApiRequest(req, res, next) {
|
|
243
294
|
if (req.method === "OPTIONS") {
|
|
244
|
-
|
|
295
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
|
|
296
|
+
res.writeHead(204, headers);
|
|
245
297
|
res.end();
|
|
246
298
|
return;
|
|
247
299
|
}
|
|
248
|
-
|
|
300
|
+
const routes = getRouteCache();
|
|
249
301
|
const host = req.headers.host ?? "localhost";
|
|
250
302
|
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
251
303
|
const method = (req.method ?? "GET").toUpperCase();
|
|
@@ -260,15 +312,22 @@ async function handleApiRequest(req, res, next) {
|
|
|
260
312
|
const { pathname, search } = parsedUrl;
|
|
261
313
|
let matchedRoute = null;
|
|
262
314
|
let params = null;
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
+
}
|
|
268
326
|
}
|
|
269
327
|
}
|
|
270
328
|
if (!matchedRoute) {
|
|
271
|
-
|
|
329
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
330
|
+
res.writeHead(404, { "Content-Type": "application/json", ...headers });
|
|
272
331
|
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
273
332
|
return;
|
|
274
333
|
}
|
|
@@ -285,7 +344,8 @@ async function handleApiRequest(req, res, next) {
|
|
|
285
344
|
}
|
|
286
345
|
const handler = await importHandler(matchedRoute.filePath);
|
|
287
346
|
if (!handler) {
|
|
288
|
-
|
|
347
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
348
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
289
349
|
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
290
350
|
return;
|
|
291
351
|
}
|
|
@@ -316,52 +376,31 @@ async function handleApiRequest(req, res, next) {
|
|
|
316
376
|
headers: { "Content-Type": "application/json" }
|
|
317
377
|
});
|
|
318
378
|
} else {
|
|
319
|
-
|
|
379
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
380
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
320
381
|
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
321
382
|
return;
|
|
322
383
|
}
|
|
323
384
|
} catch (e) {
|
|
324
385
|
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
325
|
-
|
|
386
|
+
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
387
|
+
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
326
388
|
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
327
389
|
return;
|
|
328
390
|
}
|
|
329
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
391
|
+
const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
330
392
|
webRes.headers.forEach((v, k) => {
|
|
331
393
|
finalHeaders[k] = v;
|
|
332
394
|
});
|
|
333
395
|
res.writeHead(webRes.status, finalHeaders);
|
|
334
396
|
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
335
397
|
}
|
|
336
|
-
var MIME = {
|
|
337
|
-
".html": "text/html; charset=utf-8",
|
|
338
|
-
".js": "application/javascript",
|
|
339
|
-
".mjs": "application/javascript",
|
|
340
|
-
".css": "text/css",
|
|
341
|
-
".json": "application/json",
|
|
342
|
-
".png": "image/png",
|
|
343
|
-
".jpg": "image/jpeg",
|
|
344
|
-
".jpeg": "image/jpeg",
|
|
345
|
-
".gif": "image/gif",
|
|
346
|
-
".svg": "image/svg+xml",
|
|
347
|
-
".ico": "image/x-icon",
|
|
348
|
-
".webp": "image/webp",
|
|
349
|
-
".avif": "image/avif",
|
|
350
|
-
".woff": "font/woff",
|
|
351
|
-
".woff2": "font/woff2",
|
|
352
|
-
".ttf": "font/ttf",
|
|
353
|
-
".eot": "application/vnd.ms-fontobject",
|
|
354
|
-
".txt": "text/plain",
|
|
355
|
-
".xml": "application/xml",
|
|
356
|
-
".webmanifest": "application/manifest+json",
|
|
357
|
-
".map": "application/json"
|
|
358
|
-
};
|
|
359
398
|
function getETag(stat) {
|
|
360
399
|
return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
|
|
361
400
|
}
|
|
362
401
|
async function sendFile(filePath, req, res) {
|
|
363
402
|
const ext = path.extname(filePath).toLowerCase();
|
|
364
|
-
const mimeType =
|
|
403
|
+
const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
365
404
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
366
405
|
let stat;
|
|
367
406
|
try {
|
|
@@ -393,6 +432,29 @@ async function sendFile(filePath, req, res) {
|
|
|
393
432
|
} catch {
|
|
394
433
|
}
|
|
395
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
|
+
};
|
|
396
458
|
async function serveStatic(req, res, next) {
|
|
397
459
|
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
398
460
|
if (pathname.startsWith("/api")) return next();
|
|
@@ -462,6 +524,7 @@ async function start() {
|
|
|
462
524
|
});
|
|
463
525
|
server.keepAliveTimeout = 65e3;
|
|
464
526
|
server.headersTimeout = 66e3;
|
|
527
|
+
server.maxHeadersCount = 2e3;
|
|
465
528
|
startKeyboardLoop(port);
|
|
466
529
|
server.listen(port, "0.0.0.0", () => {
|
|
467
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
|
}
|