bini-server 1.0.2 → 1.0.4
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 +53 -107
- package/dist/cli.js +178 -127
- package/dist/index.js +178 -127
- package/package.json +14 -10
package/README.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
<div align="center">
|
|
4
4
|
|
|
5
|
-
[](https://www.npmjs.com/package/bini-server)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
[](https://nodejs.org)
|
|
8
|
+
[](https://www.npmjs.com/package/bini-env)
|
|
9
9
|
|
|
10
|
-
**
|
|
11
|
-
Serves your `dist/` statically and
|
|
10
|
+
**Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
|
|
11
|
+
Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` handlers — just like `vite preview`, but production-grade.
|
|
12
12
|
|
|
13
13
|
</div>
|
|
14
14
|
|
|
@@ -16,17 +16,17 @@ Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handl
|
|
|
16
16
|
|
|
17
17
|
## Features
|
|
18
18
|
|
|
19
|
-
- ⚡ **Zero dependencies** — pure Node.js built-ins only
|
|
20
19
|
- 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
|
|
21
|
-
- 🌐 **API routes** —
|
|
20
|
+
- 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
|
|
22
21
|
- 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
|
|
23
|
-
- 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env)
|
|
22
|
+
- 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env)
|
|
24
23
|
- 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
|
|
25
24
|
- 🛡️ **CORS** — enabled by default on all API responses
|
|
26
|
-
- ⏱️ **Timeouts** —
|
|
27
|
-
- 🔒 **Body limit** —
|
|
28
|
-
- 🔌 **Port auto-increment** — starts at 3000
|
|
29
|
-
- 🪄 **Graceful shutdown** — handles SIGTERM + SIGINT with 10s force-exit fallback
|
|
25
|
+
- ⏱️ **Timeouts** — configurable body read + handler timeouts (default 30s each)
|
|
26
|
+
- 🔒 **Body limit** — configurable request body limit (default 10MB)
|
|
27
|
+
- 🔌 **Port auto-increment** — starts at `3000`, increments if busy
|
|
28
|
+
- 🪄 **Graceful shutdown** — handles `SIGTERM` + `SIGINT` with 10s force-exit fallback
|
|
29
|
+
- ⌨️ **Interactive keyboard shortcuts** — `h` for help, `o` to open in browser, `q` to quit
|
|
30
30
|
- 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
|
|
31
31
|
|
|
32
32
|
---
|
|
@@ -69,114 +69,76 @@ npm start # serve it in production
|
|
|
69
69
|
Terminal output:
|
|
70
70
|
|
|
71
71
|
```
|
|
72
|
-
ß Bini.js
|
|
73
|
-
|
|
72
|
+
ß Bini.js (production)
|
|
74
73
|
➜ Environments: .env
|
|
75
74
|
➜ Local: http://localhost:3000/
|
|
76
75
|
➜ Network: http://192.168.1.5:3000/
|
|
76
|
+
➜ press h + enter to show help
|
|
77
77
|
```
|
|
78
78
|
|
|
79
79
|
---
|
|
80
80
|
|
|
81
|
+
## Keyboard Shortcuts
|
|
82
|
+
|
|
83
|
+
Once the server is running, type a key and press `enter`:
|
|
84
|
+
|
|
85
|
+
| Key | Action |
|
|
86
|
+
|-----|--------|
|
|
87
|
+
| `h` | Show available shortcuts |
|
|
88
|
+
| `o` | Open in browser |
|
|
89
|
+
| `q` | Quit |
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
81
93
|
## Environment Variables
|
|
82
94
|
|
|
83
|
-
|
|
95
|
+
`.env` is loaded automatically at startup — all vars are available in `process.env` in your API handlers with no imports needed.
|
|
84
96
|
|
|
85
97
|
```env
|
|
86
|
-
# .env
|
|
87
98
|
PORT=3000
|
|
88
|
-
|
|
89
|
-
# Server-side vars — used by API routes via getEnv() / requireEnv()
|
|
90
99
|
SMTP_USER=user@smtp.example.com
|
|
91
100
|
SMTP_PASS=your_password
|
|
92
|
-
FROM_EMAIL=App <noreply@example.com>
|
|
93
|
-
|
|
94
|
-
# Client-side vars — already baked into dist/ at build time, ignored by server
|
|
95
|
-
BINI_FIREBASE_API_KEY=your_key
|
|
96
101
|
```
|
|
97
102
|
|
|
98
|
-
|
|
103
|
+
### Server Configuration
|
|
99
104
|
|
|
100
|
-
|
|
105
|
+
These variables tune server behaviour and can be set in `.env` or inline:
|
|
101
106
|
|
|
102
|
-
|
|
107
|
+
| Variable | Default | Description |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| `PORT` | `3000` | HTTP port to listen on |
|
|
110
|
+
| `BINI_API_DIR` | `src/app/api` | Path to API handlers directory |
|
|
111
|
+
| `BINI_DIST_DIR` | `dist` | Path to static files directory |
|
|
112
|
+
| `BINI_BODY_TIMEOUT_SECS` | `30` | Max seconds to read request body |
|
|
113
|
+
| `BINI_HANDLER_TIMEOUT_SECS` | `30` | Max seconds for an API handler to respond |
|
|
114
|
+
| `BINI_BODY_SIZE_LIMIT` | `10485760` | Max request body size in bytes (default 10MB) |
|
|
103
115
|
|
|
104
|
-
|
|
116
|
+
---
|
|
105
117
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
├─ /api/* → src/app/api/ handlers (Hono apps or plain functions)
|
|
110
|
-
│
|
|
111
|
-
├─ /* → stream static file from dist/ (with ETag + cache headers)
|
|
112
|
-
│
|
|
113
|
-
└─ /* → dist/index.html (SPA fallback)
|
|
114
|
-
```
|
|
118
|
+
## Important: ship your `src/` folder
|
|
119
|
+
|
|
120
|
+
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/`.
|
|
115
121
|
|
|
116
|
-
|
|
122
|
+
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.
|
|
117
123
|
|
|
118
124
|
---
|
|
119
125
|
|
|
120
126
|
## Port
|
|
121
127
|
|
|
122
|
-
Default port is `3000`. Override via
|
|
123
|
-
|
|
124
|
-
```bash
|
|
125
|
-
PORT=8080 bini-server
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
Or in `.env`:
|
|
128
|
+
Default port is `3000`. Override via `.env` or inline:
|
|
129
129
|
|
|
130
130
|
```env
|
|
131
131
|
PORT=8080
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
```
|
|
137
|
-
⚠ Port 3000 is in use, using port 3001 instead.
|
|
134
|
+
```bash
|
|
135
|
+
PORT=8080 bini-server
|
|
138
136
|
```
|
|
139
137
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
## Configurable Directories
|
|
143
|
-
|
|
144
|
-
By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars if your project uses a different structure:
|
|
138
|
+
If the port is busy, bini-server automatically increments and warns:
|
|
145
139
|
|
|
146
|
-
```env
|
|
147
|
-
BINI_API_DIR=src/api # default: src/app/api
|
|
148
|
-
BINI_DIST_DIR=build # default: dist
|
|
149
140
|
```
|
|
150
|
-
|
|
151
|
-
---
|
|
152
|
-
|
|
153
|
-
## API Routes
|
|
154
|
-
|
|
155
|
-
bini-server reads `src/app/api/` directly — the same files your dev server uses. Both Hono apps and plain function handlers are supported. `getEnv` and `requireEnv` are auto-imported by bini-router so no imports needed:
|
|
156
|
-
|
|
157
|
-
```ts
|
|
158
|
-
// src/app/api/email.ts
|
|
159
|
-
import { Hono } from 'hono'
|
|
160
|
-
import nodemailer from 'nodemailer'
|
|
161
|
-
|
|
162
|
-
const app = new Hono().basePath('/api')
|
|
163
|
-
|
|
164
|
-
const transporter = nodemailer.createTransport({
|
|
165
|
-
host: 'smtp-relay.brevo.com',
|
|
166
|
-
port: 587,
|
|
167
|
-
auth: {
|
|
168
|
-
user: requireEnv('SMTP_USER'), // auto-imported, throws if missing
|
|
169
|
-
pass: requireEnv('SMTP_PASS'),
|
|
170
|
-
},
|
|
171
|
-
})
|
|
172
|
-
|
|
173
|
-
app.post('/email', async (c) => {
|
|
174
|
-
const { to, subject, html } = await c.req.json()
|
|
175
|
-
await transporter.sendMail({ from: requireEnv('FROM_EMAIL'), to, subject, html })
|
|
176
|
-
return c.json({ ok: true })
|
|
177
|
-
})
|
|
178
|
-
|
|
179
|
-
export default app
|
|
141
|
+
⚠ Port 3000 in use — using 3001 instead.
|
|
180
142
|
```
|
|
181
143
|
|
|
182
144
|
---
|
|
@@ -201,7 +163,7 @@ pm2 startup
|
|
|
201
163
|
|
|
202
164
|
### Railway
|
|
203
165
|
|
|
204
|
-
Set start command to `npm start
|
|
166
|
+
Set start command to `npm start`. Railway injects `PORT` automatically.
|
|
205
167
|
|
|
206
168
|
### Render
|
|
207
169
|
|
|
@@ -217,38 +179,22 @@ Set start command to `npm start`. Render injects `PORT` automatically.
|
|
|
217
179
|
|
|
218
180
|
---
|
|
219
181
|
|
|
220
|
-
## Project structure
|
|
221
|
-
|
|
222
|
-
bini-server expects the standard bini-router project layout:
|
|
223
|
-
|
|
224
|
-
```
|
|
225
|
-
my-app/
|
|
226
|
-
├── src/
|
|
227
|
-
│ └── app/
|
|
228
|
-
│ └── api/ ← API route handlers
|
|
229
|
-
├── dist/ ← built frontend (vite build output)
|
|
230
|
-
├── .env ← environment variables
|
|
231
|
-
└── package.json
|
|
232
|
-
```
|
|
233
|
-
|
|
234
|
-
---
|
|
235
|
-
|
|
236
182
|
## vs `vite preview`
|
|
237
183
|
|
|
238
184
|
| Feature | `vite preview` | `bini-server` |
|
|
239
185
|
|---|---|---|
|
|
240
186
|
| Serves `dist/` | ✅ | ✅ |
|
|
241
|
-
| API routes | ✅
|
|
187
|
+
| API routes | ✅ | ✅ |
|
|
242
188
|
| SPA fallback | ✅ | ✅ |
|
|
243
|
-
| Auto env loading | ✅
|
|
189
|
+
| Auto env loading | ✅ | ✅ |
|
|
244
190
|
| ETag / 304 support | ❌ | ✅ |
|
|
245
|
-
| Production use | ❌
|
|
191
|
+
| Production use | ❌ | ✅ |
|
|
246
192
|
| Body timeout | ❌ | ✅ 30s |
|
|
247
193
|
| Body size limit | ❌ | ✅ 10MB |
|
|
248
194
|
| Handler timeout | ❌ | ✅ 30s |
|
|
249
195
|
| Graceful shutdown | ❌ | ✅ |
|
|
196
|
+
| Keyboard shortcuts | ❌ | ✅ |
|
|
250
197
|
| Configurable dirs | ❌ | ✅ |
|
|
251
|
-
| Zero dependencies | ✅ | ✅ |
|
|
252
198
|
|
|
253
199
|
---
|
|
254
200
|
|
package/dist/cli.js
CHANGED
|
@@ -7,6 +7,8 @@ import path from "path";
|
|
|
7
7
|
import os from "os";
|
|
8
8
|
import net from "net";
|
|
9
9
|
import crypto from "crypto";
|
|
10
|
+
import readline from "readline";
|
|
11
|
+
import { exec } from "child_process";
|
|
10
12
|
import { pathToFileURL } from "url";
|
|
11
13
|
import { pipeline } from "stream/promises";
|
|
12
14
|
import { createReadStream } from "fs";
|
|
@@ -27,49 +29,55 @@ process.env.NODE_ENV = "production";
|
|
|
27
29
|
};
|
|
28
30
|
})();
|
|
29
31
|
var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
|
|
32
|
+
var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
|
|
33
|
+
var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
|
|
34
|
+
var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
|
|
30
35
|
var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
|
|
31
36
|
var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
|
|
32
|
-
var API_EXTS = [".ts", ".js"];
|
|
33
|
-
var BODY_TIMEOUT = 3e4;
|
|
34
|
-
var HANDLER_TIMEOUT = 3e4;
|
|
35
|
-
var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
|
|
37
|
+
var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
|
|
36
38
|
var C = {
|
|
37
39
|
CYAN: "\x1B[36m",
|
|
38
40
|
RESET: "\x1B[0m",
|
|
39
41
|
GREEN: "\x1B[32m",
|
|
40
42
|
RED: "\x1B[31m",
|
|
41
43
|
YELLOW: "\x1B[33m",
|
|
44
|
+
BOLD: "\x1B[1m",
|
|
42
45
|
DIM: "\x1B[2m"
|
|
43
46
|
};
|
|
44
|
-
function
|
|
47
|
+
function getNetworkIp() {
|
|
45
48
|
const ifaces = os.networkInterfaces();
|
|
46
|
-
const
|
|
49
|
+
const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
|
|
47
50
|
for (const name in ifaces) {
|
|
48
|
-
if (
|
|
51
|
+
if (SKIP.test(name)) continue;
|
|
49
52
|
for (const iface of ifaces[name] ?? []) {
|
|
50
53
|
if (iface.internal || iface.family !== "IPv4") continue;
|
|
51
|
-
|
|
54
|
+
const [a, b] = iface.address.split(".").map(Number);
|
|
55
|
+
if (a === 169 && b === 254) continue;
|
|
56
|
+
const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
|
|
57
|
+
if (isPrivate) return iface.address;
|
|
52
58
|
}
|
|
53
59
|
}
|
|
54
|
-
|
|
60
|
+
for (const name in ifaces) {
|
|
61
|
+
if (SKIP.test(name)) continue;
|
|
62
|
+
for (const iface of ifaces[name] ?? []) {
|
|
63
|
+
if (!iface.internal && iface.family === "IPv4") return iface.address;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
55
67
|
}
|
|
56
68
|
function printBanner(port) {
|
|
57
|
-
const networkIps = getAllNetworkIps();
|
|
58
69
|
const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
|
|
70
|
+
const networkIp = getNetworkIp();
|
|
59
71
|
console.log(`
|
|
60
|
-
${C.CYAN}\xDF Bini.js${C.RESET}
|
|
61
|
-
`);
|
|
72
|
+
${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
|
|
62
73
|
if (envFiles.length > 0) {
|
|
63
74
|
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
|
|
64
75
|
}
|
|
65
76
|
console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
|
|
66
|
-
|
|
67
|
-
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${
|
|
68
|
-
}
|
|
69
|
-
if (!fs.existsSync(API_DIR)) {
|
|
70
|
-
console.log(`
|
|
71
|
-
${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
|
|
77
|
+
if (networkIp) {
|
|
78
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
|
|
72
79
|
}
|
|
80
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h${C.DIM} + ${C.RESET}enter${C.DIM} to show help${C.RESET}`);
|
|
73
81
|
console.log("");
|
|
74
82
|
}
|
|
75
83
|
async function isPortFree(port) {
|
|
@@ -85,16 +93,39 @@ async function findFreePort(start2) {
|
|
|
85
93
|
if (await isPortFree(port)) {
|
|
86
94
|
if (port !== start2) {
|
|
87
95
|
console.log(`
|
|
88
|
-
${C.YELLOW}\u26A0${C.RESET} Port ${start2}
|
|
96
|
+
${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
|
|
89
97
|
}
|
|
90
98
|
return port;
|
|
91
99
|
}
|
|
92
100
|
}
|
|
93
|
-
throw new Error(`No free port found
|
|
101
|
+
throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
|
|
102
|
+
}
|
|
103
|
+
function startKeyboardLoop(port) {
|
|
104
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
105
|
+
rl.on("line", (line) => {
|
|
106
|
+
switch (line.trim()) {
|
|
107
|
+
case "h":
|
|
108
|
+
console.log("");
|
|
109
|
+
console.log(" Shortcuts");
|
|
110
|
+
console.log(` ${C.DIM}press ${C.RESET}o${C.DIM} + ${C.RESET}enter${C.DIM} to open in browser${C.RESET}`);
|
|
111
|
+
console.log(` ${C.DIM}press ${C.RESET}q${C.DIM} + ${C.RESET}enter${C.DIM} to quit${C.RESET}`);
|
|
112
|
+
console.log("");
|
|
113
|
+
break;
|
|
114
|
+
case "o": {
|
|
115
|
+
const url = `http://localhost:${port}/`;
|
|
116
|
+
const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
|
|
117
|
+
exec(cmd);
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
case "q":
|
|
121
|
+
process.exit(0);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
rl.on("close", () => process.exit(0));
|
|
94
125
|
}
|
|
95
|
-
function scanApiRoutes(dir, baseRoute = "") {
|
|
126
|
+
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
96
127
|
const routes = [];
|
|
97
|
-
if (!fs.existsSync(dir)) return routes;
|
|
128
|
+
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
98
129
|
let entries;
|
|
99
130
|
try {
|
|
100
131
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
@@ -108,16 +139,20 @@ function scanApiRoutes(dir, baseRoute = "") {
|
|
|
108
139
|
const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
|
|
109
140
|
const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
|
|
110
141
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
111
|
-
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}
|
|
142
|
+
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
|
|
112
143
|
continue;
|
|
113
144
|
}
|
|
114
145
|
const ext = path.extname(entry.name);
|
|
115
146
|
const base = path.basename(entry.name, ext);
|
|
116
|
-
if (!API_EXTS.
|
|
147
|
+
if (!API_EXTS.has(ext)) continue;
|
|
117
148
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
118
149
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
119
|
-
|
|
120
|
-
|
|
150
|
+
let routePath;
|
|
151
|
+
if (isCatchAll) routePath = `${baseRoute}/*`;
|
|
152
|
+
else if (base === "index") routePath = baseRoute || "/";
|
|
153
|
+
else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
|
|
154
|
+
else routePath = `${baseRoute}/${base}`;
|
|
155
|
+
routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
|
|
121
156
|
}
|
|
122
157
|
return routes;
|
|
123
158
|
}
|
|
@@ -129,8 +164,7 @@ function matchRoute(pattern, pathname) {
|
|
|
129
164
|
const prefix = patParts.slice(0, -1);
|
|
130
165
|
if (urlParts.length < prefix.length) return null;
|
|
131
166
|
for (let i = 0; i < prefix.length; i++) {
|
|
132
|
-
if (prefix[i].startsWith(":"))
|
|
133
|
-
if (prefix[i] !== urlParts[i]) return null;
|
|
167
|
+
if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
|
|
134
168
|
}
|
|
135
169
|
return { "*": urlParts.slice(prefix.length).join("/") };
|
|
136
170
|
}
|
|
@@ -138,7 +172,9 @@ function matchRoute(pattern, pathname) {
|
|
|
138
172
|
const params = {};
|
|
139
173
|
for (let i = 0; i < patParts.length; i++) {
|
|
140
174
|
if (patParts[i].startsWith(":")) {
|
|
141
|
-
|
|
175
|
+
const value = decodeURIComponent(urlParts[i]);
|
|
176
|
+
if (value.includes("..") || value.includes("//")) return null;
|
|
177
|
+
params[patParts[i].slice(1)] = value;
|
|
142
178
|
} else if (patParts[i] !== urlParts[i]) {
|
|
143
179
|
return null;
|
|
144
180
|
}
|
|
@@ -151,31 +187,33 @@ async function importHandler(filePath) {
|
|
|
151
187
|
try {
|
|
152
188
|
mtime = fs.statSync(filePath).mtimeMs;
|
|
153
189
|
} catch {
|
|
190
|
+
return null;
|
|
154
191
|
}
|
|
155
192
|
const cached = moduleCache.get(filePath);
|
|
156
|
-
if (cached
|
|
193
|
+
if (cached?.mtime === mtime) return cached.handler;
|
|
157
194
|
try {
|
|
158
195
|
const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
|
|
159
196
|
const handler = mod.default ?? null;
|
|
160
197
|
moduleCache.set(filePath, { mtime, handler });
|
|
161
198
|
return handler;
|
|
162
199
|
} catch (e) {
|
|
200
|
+
console.error(`[bini-api] import error: ${filePath}`, e?.message);
|
|
163
201
|
moduleCache.delete(filePath);
|
|
164
|
-
|
|
202
|
+
return null;
|
|
165
203
|
}
|
|
166
204
|
}
|
|
167
205
|
function readBody(req) {
|
|
168
206
|
return new Promise((resolve, reject) => {
|
|
169
207
|
const chunks = [];
|
|
170
208
|
let size = 0;
|
|
171
|
-
const
|
|
209
|
+
const timer = setTimeout(() => {
|
|
172
210
|
req.destroy();
|
|
173
211
|
reject(new Error("Request body timeout"));
|
|
174
212
|
}, BODY_TIMEOUT);
|
|
175
213
|
req.on("data", (chunk) => {
|
|
176
214
|
size += chunk.byteLength;
|
|
177
215
|
if (size > BODY_SIZE_LIMIT) {
|
|
178
|
-
clearTimeout(
|
|
216
|
+
clearTimeout(timer);
|
|
179
217
|
req.destroy();
|
|
180
218
|
reject(new Error("Request body too large"));
|
|
181
219
|
return;
|
|
@@ -183,11 +221,11 @@ function readBody(req) {
|
|
|
183
221
|
chunks.push(chunk);
|
|
184
222
|
});
|
|
185
223
|
req.on("end", () => {
|
|
186
|
-
clearTimeout(
|
|
224
|
+
clearTimeout(timer);
|
|
187
225
|
resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
|
|
188
226
|
});
|
|
189
227
|
req.on("error", (err) => {
|
|
190
|
-
clearTimeout(
|
|
228
|
+
clearTimeout(timer);
|
|
191
229
|
reject(err);
|
|
192
230
|
});
|
|
193
231
|
});
|
|
@@ -203,97 +241,103 @@ function normalizeHeaders(raw) {
|
|
|
203
241
|
var CORS_HEADERS = {
|
|
204
242
|
"Access-Control-Allow-Origin": "*",
|
|
205
243
|
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
206
|
-
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
244
|
+
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
245
|
+
"Vary": "Origin"
|
|
207
246
|
};
|
|
208
247
|
var routeCache = null;
|
|
209
248
|
async function handleApiRequest(req, res, next) {
|
|
249
|
+
if (req.method === "OPTIONS") {
|
|
250
|
+
res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
|
|
251
|
+
res.end();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
routeCache ??= scanApiRoutes(API_DIR);
|
|
255
|
+
const host = req.headers.host ?? "localhost";
|
|
256
|
+
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
257
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
258
|
+
let parsedUrl;
|
|
210
259
|
try {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
260
|
+
parsedUrl = new URL(rawUrl);
|
|
261
|
+
} catch {
|
|
262
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
263
|
+
res.end(JSON.stringify({ error: "Bad request URL" }));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const { pathname, search } = parsedUrl;
|
|
267
|
+
let matchedRoute = null;
|
|
268
|
+
let params = null;
|
|
269
|
+
for (const route of routeCache) {
|
|
270
|
+
params = matchRoute(route.routePath, pathname);
|
|
271
|
+
if (params !== null) {
|
|
272
|
+
matchedRoute = route;
|
|
273
|
+
break;
|
|
218
274
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
275
|
+
}
|
|
276
|
+
if (!matchedRoute) {
|
|
277
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
278
|
+
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
let body;
|
|
282
|
+
if (!["GET", "HEAD"].includes(method)) {
|
|
224
283
|
try {
|
|
225
|
-
body =
|
|
284
|
+
body = await readBody(req);
|
|
226
285
|
} catch (e) {
|
|
227
|
-
|
|
286
|
+
const status = e.message.includes("too large") ? 413 : 408;
|
|
287
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
228
288
|
res.end(JSON.stringify({ error: e.message }));
|
|
229
289
|
return;
|
|
230
290
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
"x-bini-params": JSON.stringify(params)
|
|
264
|
-
}
|
|
265
|
-
});
|
|
266
|
-
const result = await Promise.race([
|
|
267
|
-
handler(reqWithParams),
|
|
268
|
-
new Promise(
|
|
269
|
-
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
270
|
-
)
|
|
271
|
-
]);
|
|
272
|
-
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
273
|
-
status: 200,
|
|
274
|
-
headers: { "Content-Type": "application/json" }
|
|
275
|
-
});
|
|
276
|
-
} else {
|
|
277
|
-
continue;
|
|
278
|
-
}
|
|
279
|
-
} catch (e) {
|
|
280
|
-
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
281
|
-
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
285
|
-
webRes.headers.forEach((v, k) => {
|
|
286
|
-
finalHeaders[k] = v;
|
|
291
|
+
}
|
|
292
|
+
const handler = await importHandler(matchedRoute.filePath);
|
|
293
|
+
if (!handler) {
|
|
294
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
295
|
+
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const normalizedHeaders = normalizeHeaders(req.headers);
|
|
299
|
+
let webRes;
|
|
300
|
+
try {
|
|
301
|
+
if (typeof handler.fetch === "function") {
|
|
302
|
+
const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
|
|
303
|
+
webRes = await handler.fetch(new Request(honoUrl, {
|
|
304
|
+
method,
|
|
305
|
+
headers: normalizedHeaders,
|
|
306
|
+
body: body ? new Uint8Array(body) : null
|
|
307
|
+
}));
|
|
308
|
+
} else if (typeof handler === "function") {
|
|
309
|
+
const reqWithParams = new Request(rawUrl, {
|
|
310
|
+
method,
|
|
311
|
+
headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
|
|
312
|
+
body: body ? new Uint8Array(body) : null
|
|
313
|
+
});
|
|
314
|
+
const result = await Promise.race([
|
|
315
|
+
handler(reqWithParams),
|
|
316
|
+
new Promise(
|
|
317
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
318
|
+
)
|
|
319
|
+
]);
|
|
320
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
321
|
+
status: 200,
|
|
322
|
+
headers: { "Content-Type": "application/json" }
|
|
287
323
|
});
|
|
288
|
-
|
|
289
|
-
res.
|
|
324
|
+
} else {
|
|
325
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
326
|
+
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
290
327
|
return;
|
|
291
328
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
329
|
+
} catch (e) {
|
|
330
|
+
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
331
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
332
|
+
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
333
|
+
return;
|
|
296
334
|
}
|
|
335
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
336
|
+
webRes.headers.forEach((v, k) => {
|
|
337
|
+
finalHeaders[k] = v;
|
|
338
|
+
});
|
|
339
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
340
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
297
341
|
}
|
|
298
342
|
var MIME = {
|
|
299
343
|
".html": "text/html; charset=utf-8",
|
|
@@ -327,15 +371,14 @@ async function sendFile(filePath, req, res) {
|
|
|
327
371
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
328
372
|
let stat;
|
|
329
373
|
try {
|
|
330
|
-
stat = fs.
|
|
374
|
+
stat = await fs.promises.stat(filePath);
|
|
331
375
|
} catch {
|
|
332
376
|
res.writeHead(404);
|
|
333
377
|
res.end("Not found");
|
|
334
378
|
return;
|
|
335
379
|
}
|
|
336
380
|
const etag = getETag(stat);
|
|
337
|
-
|
|
338
|
-
if (ifNoneMatch === etag) {
|
|
381
|
+
if (req.headers["if-none-match"] === etag) {
|
|
339
382
|
res.writeHead(304);
|
|
340
383
|
res.end();
|
|
341
384
|
return;
|
|
@@ -357,23 +400,29 @@ async function sendFile(filePath, req, res) {
|
|
|
357
400
|
}
|
|
358
401
|
}
|
|
359
402
|
async function serveStatic(req, res, next) {
|
|
360
|
-
const pathname = new URL(req.url ?? "/",
|
|
403
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
404
|
+
if (pathname.startsWith("/api")) return next();
|
|
361
405
|
const filePath = path.join(DIST_DIR, pathname);
|
|
362
|
-
|
|
363
|
-
await
|
|
364
|
-
|
|
406
|
+
try {
|
|
407
|
+
const stat = await fs.promises.stat(filePath);
|
|
408
|
+
if (stat.isFile()) {
|
|
409
|
+
await sendFile(filePath, req, res);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
} catch {
|
|
365
413
|
}
|
|
366
414
|
const indexPath = path.join(DIST_DIR, "index.html");
|
|
367
|
-
|
|
415
|
+
try {
|
|
416
|
+
await fs.promises.access(indexPath);
|
|
368
417
|
await sendFile(indexPath, req, res);
|
|
369
|
-
|
|
418
|
+
} catch {
|
|
419
|
+
next();
|
|
370
420
|
}
|
|
371
|
-
next();
|
|
372
421
|
}
|
|
373
422
|
function compose(middlewares) {
|
|
374
423
|
return async (req, res) => {
|
|
375
424
|
let idx = 0;
|
|
376
|
-
async
|
|
425
|
+
const next = async () => {
|
|
377
426
|
if (idx >= middlewares.length) return;
|
|
378
427
|
const fn = middlewares[idx++];
|
|
379
428
|
try {
|
|
@@ -384,7 +433,7 @@ function compose(middlewares) {
|
|
|
384
433
|
res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
|
|
385
434
|
}
|
|
386
435
|
}
|
|
387
|
-
}
|
|
436
|
+
};
|
|
388
437
|
await next();
|
|
389
438
|
};
|
|
390
439
|
}
|
|
@@ -392,7 +441,8 @@ async function start() {
|
|
|
392
441
|
await loadEnv(process.cwd());
|
|
393
442
|
if (!fs.existsSync(DIST_DIR)) {
|
|
394
443
|
console.error(`
|
|
395
|
-
${C.RED}\u2717${C.RESET} dist/ not found
|
|
444
|
+
${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
|
|
445
|
+
Run ${C.CYAN}npm run build${C.RESET} first.
|
|
396
446
|
`);
|
|
397
447
|
process.exit(1);
|
|
398
448
|
}
|
|
@@ -419,13 +469,14 @@ async function start() {
|
|
|
419
469
|
});
|
|
420
470
|
server.keepAliveTimeout = 65e3;
|
|
421
471
|
server.headersTimeout = 66e3;
|
|
472
|
+
startKeyboardLoop(port);
|
|
422
473
|
server.listen(port, "0.0.0.0", () => {
|
|
423
474
|
printBanner(port);
|
|
424
475
|
});
|
|
425
|
-
|
|
476
|
+
const shutdown = () => {
|
|
426
477
|
server.close(() => process.exit(0));
|
|
427
478
|
setTimeout(() => process.exit(1), 1e4).unref();
|
|
428
|
-
}
|
|
479
|
+
};
|
|
429
480
|
process.on("SIGTERM", shutdown);
|
|
430
481
|
process.on("SIGINT", shutdown);
|
|
431
482
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,8 @@ import path from "path";
|
|
|
5
5
|
import os from "os";
|
|
6
6
|
import net from "net";
|
|
7
7
|
import crypto from "crypto";
|
|
8
|
+
import readline from "readline";
|
|
9
|
+
import { exec } from "child_process";
|
|
8
10
|
import { pathToFileURL } from "url";
|
|
9
11
|
import { pipeline } from "stream/promises";
|
|
10
12
|
import { createReadStream } from "fs";
|
|
@@ -25,49 +27,55 @@ process.env.NODE_ENV = "production";
|
|
|
25
27
|
};
|
|
26
28
|
})();
|
|
27
29
|
var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
|
|
30
|
+
var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
|
|
31
|
+
var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
|
|
32
|
+
var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
|
|
28
33
|
var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
|
|
29
34
|
var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
|
|
30
|
-
var API_EXTS = [".ts", ".js"];
|
|
31
|
-
var BODY_TIMEOUT = 3e4;
|
|
32
|
-
var HANDLER_TIMEOUT = 3e4;
|
|
33
|
-
var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
|
|
35
|
+
var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
|
|
34
36
|
var C = {
|
|
35
37
|
CYAN: "\x1B[36m",
|
|
36
38
|
RESET: "\x1B[0m",
|
|
37
39
|
GREEN: "\x1B[32m",
|
|
38
40
|
RED: "\x1B[31m",
|
|
39
41
|
YELLOW: "\x1B[33m",
|
|
42
|
+
BOLD: "\x1B[1m",
|
|
40
43
|
DIM: "\x1B[2m"
|
|
41
44
|
};
|
|
42
|
-
function
|
|
45
|
+
function getNetworkIp() {
|
|
43
46
|
const ifaces = os.networkInterfaces();
|
|
44
|
-
const
|
|
47
|
+
const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
|
|
45
48
|
for (const name in ifaces) {
|
|
46
|
-
if (
|
|
49
|
+
if (SKIP.test(name)) continue;
|
|
47
50
|
for (const iface of ifaces[name] ?? []) {
|
|
48
51
|
if (iface.internal || iface.family !== "IPv4") continue;
|
|
49
|
-
|
|
52
|
+
const [a, b] = iface.address.split(".").map(Number);
|
|
53
|
+
if (a === 169 && b === 254) continue;
|
|
54
|
+
const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
|
|
55
|
+
if (isPrivate) return iface.address;
|
|
50
56
|
}
|
|
51
57
|
}
|
|
52
|
-
|
|
58
|
+
for (const name in ifaces) {
|
|
59
|
+
if (SKIP.test(name)) continue;
|
|
60
|
+
for (const iface of ifaces[name] ?? []) {
|
|
61
|
+
if (!iface.internal && iface.family === "IPv4") return iface.address;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
53
65
|
}
|
|
54
66
|
function printBanner(port) {
|
|
55
|
-
const networkIps = getAllNetworkIps();
|
|
56
67
|
const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
|
|
68
|
+
const networkIp = getNetworkIp();
|
|
57
69
|
console.log(`
|
|
58
|
-
${C.CYAN}\xDF Bini.js${C.RESET}
|
|
59
|
-
`);
|
|
70
|
+
${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
|
|
60
71
|
if (envFiles.length > 0) {
|
|
61
72
|
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
|
|
62
73
|
}
|
|
63
74
|
console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
|
|
64
|
-
|
|
65
|
-
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${
|
|
66
|
-
}
|
|
67
|
-
if (!fs.existsSync(API_DIR)) {
|
|
68
|
-
console.log(`
|
|
69
|
-
${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
|
|
75
|
+
if (networkIp) {
|
|
76
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
|
|
70
77
|
}
|
|
78
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h${C.DIM} + ${C.RESET}enter${C.DIM} to show help${C.RESET}`);
|
|
71
79
|
console.log("");
|
|
72
80
|
}
|
|
73
81
|
async function isPortFree(port) {
|
|
@@ -83,16 +91,39 @@ async function findFreePort(start2) {
|
|
|
83
91
|
if (await isPortFree(port)) {
|
|
84
92
|
if (port !== start2) {
|
|
85
93
|
console.log(`
|
|
86
|
-
${C.YELLOW}\u26A0${C.RESET} Port ${start2}
|
|
94
|
+
${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
|
|
87
95
|
}
|
|
88
96
|
return port;
|
|
89
97
|
}
|
|
90
98
|
}
|
|
91
|
-
throw new Error(`No free port found
|
|
99
|
+
throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
|
|
100
|
+
}
|
|
101
|
+
function startKeyboardLoop(port) {
|
|
102
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
103
|
+
rl.on("line", (line) => {
|
|
104
|
+
switch (line.trim()) {
|
|
105
|
+
case "h":
|
|
106
|
+
console.log("");
|
|
107
|
+
console.log(" Shortcuts");
|
|
108
|
+
console.log(` ${C.DIM}press ${C.RESET}o${C.DIM} + ${C.RESET}enter${C.DIM} to open in browser${C.RESET}`);
|
|
109
|
+
console.log(` ${C.DIM}press ${C.RESET}q${C.DIM} + ${C.RESET}enter${C.DIM} to quit${C.RESET}`);
|
|
110
|
+
console.log("");
|
|
111
|
+
break;
|
|
112
|
+
case "o": {
|
|
113
|
+
const url = `http://localhost:${port}/`;
|
|
114
|
+
const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
|
|
115
|
+
exec(cmd);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
case "q":
|
|
119
|
+
process.exit(0);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
rl.on("close", () => process.exit(0));
|
|
92
123
|
}
|
|
93
|
-
function scanApiRoutes(dir, baseRoute = "") {
|
|
124
|
+
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
94
125
|
const routes = [];
|
|
95
|
-
if (!fs.existsSync(dir)) return routes;
|
|
126
|
+
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
96
127
|
let entries;
|
|
97
128
|
try {
|
|
98
129
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
@@ -106,16 +137,20 @@ function scanApiRoutes(dir, baseRoute = "") {
|
|
|
106
137
|
const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
|
|
107
138
|
const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
|
|
108
139
|
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
109
|
-
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}
|
|
140
|
+
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
|
|
110
141
|
continue;
|
|
111
142
|
}
|
|
112
143
|
const ext = path.extname(entry.name);
|
|
113
144
|
const base = path.basename(entry.name, ext);
|
|
114
|
-
if (!API_EXTS.
|
|
145
|
+
if (!API_EXTS.has(ext)) continue;
|
|
115
146
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
116
147
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
117
|
-
|
|
118
|
-
|
|
148
|
+
let routePath;
|
|
149
|
+
if (isCatchAll) routePath = `${baseRoute}/*`;
|
|
150
|
+
else if (base === "index") routePath = baseRoute || "/";
|
|
151
|
+
else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
|
|
152
|
+
else routePath = `${baseRoute}/${base}`;
|
|
153
|
+
routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
|
|
119
154
|
}
|
|
120
155
|
return routes;
|
|
121
156
|
}
|
|
@@ -127,8 +162,7 @@ function matchRoute(pattern, pathname) {
|
|
|
127
162
|
const prefix = patParts.slice(0, -1);
|
|
128
163
|
if (urlParts.length < prefix.length) return null;
|
|
129
164
|
for (let i = 0; i < prefix.length; i++) {
|
|
130
|
-
if (prefix[i].startsWith(":"))
|
|
131
|
-
if (prefix[i] !== urlParts[i]) return null;
|
|
165
|
+
if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
|
|
132
166
|
}
|
|
133
167
|
return { "*": urlParts.slice(prefix.length).join("/") };
|
|
134
168
|
}
|
|
@@ -136,7 +170,9 @@ function matchRoute(pattern, pathname) {
|
|
|
136
170
|
const params = {};
|
|
137
171
|
for (let i = 0; i < patParts.length; i++) {
|
|
138
172
|
if (patParts[i].startsWith(":")) {
|
|
139
|
-
|
|
173
|
+
const value = decodeURIComponent(urlParts[i]);
|
|
174
|
+
if (value.includes("..") || value.includes("//")) return null;
|
|
175
|
+
params[patParts[i].slice(1)] = value;
|
|
140
176
|
} else if (patParts[i] !== urlParts[i]) {
|
|
141
177
|
return null;
|
|
142
178
|
}
|
|
@@ -149,31 +185,33 @@ async function importHandler(filePath) {
|
|
|
149
185
|
try {
|
|
150
186
|
mtime = fs.statSync(filePath).mtimeMs;
|
|
151
187
|
} catch {
|
|
188
|
+
return null;
|
|
152
189
|
}
|
|
153
190
|
const cached = moduleCache.get(filePath);
|
|
154
|
-
if (cached
|
|
191
|
+
if (cached?.mtime === mtime) return cached.handler;
|
|
155
192
|
try {
|
|
156
193
|
const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
|
|
157
194
|
const handler = mod.default ?? null;
|
|
158
195
|
moduleCache.set(filePath, { mtime, handler });
|
|
159
196
|
return handler;
|
|
160
197
|
} catch (e) {
|
|
198
|
+
console.error(`[bini-api] import error: ${filePath}`, e?.message);
|
|
161
199
|
moduleCache.delete(filePath);
|
|
162
|
-
|
|
200
|
+
return null;
|
|
163
201
|
}
|
|
164
202
|
}
|
|
165
203
|
function readBody(req) {
|
|
166
204
|
return new Promise((resolve, reject) => {
|
|
167
205
|
const chunks = [];
|
|
168
206
|
let size = 0;
|
|
169
|
-
const
|
|
207
|
+
const timer = setTimeout(() => {
|
|
170
208
|
req.destroy();
|
|
171
209
|
reject(new Error("Request body timeout"));
|
|
172
210
|
}, BODY_TIMEOUT);
|
|
173
211
|
req.on("data", (chunk) => {
|
|
174
212
|
size += chunk.byteLength;
|
|
175
213
|
if (size > BODY_SIZE_LIMIT) {
|
|
176
|
-
clearTimeout(
|
|
214
|
+
clearTimeout(timer);
|
|
177
215
|
req.destroy();
|
|
178
216
|
reject(new Error("Request body too large"));
|
|
179
217
|
return;
|
|
@@ -181,11 +219,11 @@ function readBody(req) {
|
|
|
181
219
|
chunks.push(chunk);
|
|
182
220
|
});
|
|
183
221
|
req.on("end", () => {
|
|
184
|
-
clearTimeout(
|
|
222
|
+
clearTimeout(timer);
|
|
185
223
|
resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
|
|
186
224
|
});
|
|
187
225
|
req.on("error", (err) => {
|
|
188
|
-
clearTimeout(
|
|
226
|
+
clearTimeout(timer);
|
|
189
227
|
reject(err);
|
|
190
228
|
});
|
|
191
229
|
});
|
|
@@ -201,97 +239,103 @@ function normalizeHeaders(raw) {
|
|
|
201
239
|
var CORS_HEADERS = {
|
|
202
240
|
"Access-Control-Allow-Origin": "*",
|
|
203
241
|
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
204
|
-
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
242
|
+
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
243
|
+
"Vary": "Origin"
|
|
205
244
|
};
|
|
206
245
|
var routeCache = null;
|
|
207
246
|
async function handleApiRequest(req, res, next) {
|
|
247
|
+
if (req.method === "OPTIONS") {
|
|
248
|
+
res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
|
|
249
|
+
res.end();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
routeCache ??= scanApiRoutes(API_DIR);
|
|
253
|
+
const host = req.headers.host ?? "localhost";
|
|
254
|
+
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
255
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
256
|
+
let parsedUrl;
|
|
208
257
|
try {
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
258
|
+
parsedUrl = new URL(rawUrl);
|
|
259
|
+
} catch {
|
|
260
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
261
|
+
res.end(JSON.stringify({ error: "Bad request URL" }));
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const { pathname, search } = parsedUrl;
|
|
265
|
+
let matchedRoute = null;
|
|
266
|
+
let params = null;
|
|
267
|
+
for (const route of routeCache) {
|
|
268
|
+
params = matchRoute(route.routePath, pathname);
|
|
269
|
+
if (params !== null) {
|
|
270
|
+
matchedRoute = route;
|
|
271
|
+
break;
|
|
216
272
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
273
|
+
}
|
|
274
|
+
if (!matchedRoute) {
|
|
275
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
276
|
+
res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
let body;
|
|
280
|
+
if (!["GET", "HEAD"].includes(method)) {
|
|
222
281
|
try {
|
|
223
|
-
body =
|
|
282
|
+
body = await readBody(req);
|
|
224
283
|
} catch (e) {
|
|
225
|
-
|
|
284
|
+
const status = e.message.includes("too large") ? 413 : 408;
|
|
285
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
226
286
|
res.end(JSON.stringify({ error: e.message }));
|
|
227
287
|
return;
|
|
228
288
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
"x-bini-params": JSON.stringify(params)
|
|
262
|
-
}
|
|
263
|
-
});
|
|
264
|
-
const result = await Promise.race([
|
|
265
|
-
handler(reqWithParams),
|
|
266
|
-
new Promise(
|
|
267
|
-
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
268
|
-
)
|
|
269
|
-
]);
|
|
270
|
-
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
271
|
-
status: 200,
|
|
272
|
-
headers: { "Content-Type": "application/json" }
|
|
273
|
-
});
|
|
274
|
-
} else {
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
} catch (e) {
|
|
278
|
-
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
279
|
-
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
const finalHeaders = { ...CORS_HEADERS };
|
|
283
|
-
webRes.headers.forEach((v, k) => {
|
|
284
|
-
finalHeaders[k] = v;
|
|
289
|
+
}
|
|
290
|
+
const handler = await importHandler(matchedRoute.filePath);
|
|
291
|
+
if (!handler) {
|
|
292
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
293
|
+
res.end(JSON.stringify({ error: "Failed to load handler" }));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const normalizedHeaders = normalizeHeaders(req.headers);
|
|
297
|
+
let webRes;
|
|
298
|
+
try {
|
|
299
|
+
if (typeof handler.fetch === "function") {
|
|
300
|
+
const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
|
|
301
|
+
webRes = await handler.fetch(new Request(honoUrl, {
|
|
302
|
+
method,
|
|
303
|
+
headers: normalizedHeaders,
|
|
304
|
+
body: body ? new Uint8Array(body) : null
|
|
305
|
+
}));
|
|
306
|
+
} else if (typeof handler === "function") {
|
|
307
|
+
const reqWithParams = new Request(rawUrl, {
|
|
308
|
+
method,
|
|
309
|
+
headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
|
|
310
|
+
body: body ? new Uint8Array(body) : null
|
|
311
|
+
});
|
|
312
|
+
const result = await Promise.race([
|
|
313
|
+
handler(reqWithParams),
|
|
314
|
+
new Promise(
|
|
315
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
316
|
+
)
|
|
317
|
+
]);
|
|
318
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
319
|
+
status: 200,
|
|
320
|
+
headers: { "Content-Type": "application/json" }
|
|
285
321
|
});
|
|
286
|
-
|
|
287
|
-
res.
|
|
322
|
+
} else {
|
|
323
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
324
|
+
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
288
325
|
return;
|
|
289
326
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
327
|
+
} catch (e) {
|
|
328
|
+
console.error("[bini-api] handler error:", e?.message ?? e);
|
|
329
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
330
|
+
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
331
|
+
return;
|
|
294
332
|
}
|
|
333
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
334
|
+
webRes.headers.forEach((v, k) => {
|
|
335
|
+
finalHeaders[k] = v;
|
|
336
|
+
});
|
|
337
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
338
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
295
339
|
}
|
|
296
340
|
var MIME = {
|
|
297
341
|
".html": "text/html; charset=utf-8",
|
|
@@ -325,15 +369,14 @@ async function sendFile(filePath, req, res) {
|
|
|
325
369
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
326
370
|
let stat;
|
|
327
371
|
try {
|
|
328
|
-
stat = fs.
|
|
372
|
+
stat = await fs.promises.stat(filePath);
|
|
329
373
|
} catch {
|
|
330
374
|
res.writeHead(404);
|
|
331
375
|
res.end("Not found");
|
|
332
376
|
return;
|
|
333
377
|
}
|
|
334
378
|
const etag = getETag(stat);
|
|
335
|
-
|
|
336
|
-
if (ifNoneMatch === etag) {
|
|
379
|
+
if (req.headers["if-none-match"] === etag) {
|
|
337
380
|
res.writeHead(304);
|
|
338
381
|
res.end();
|
|
339
382
|
return;
|
|
@@ -355,23 +398,29 @@ async function sendFile(filePath, req, res) {
|
|
|
355
398
|
}
|
|
356
399
|
}
|
|
357
400
|
async function serveStatic(req, res, next) {
|
|
358
|
-
const pathname = new URL(req.url ?? "/",
|
|
401
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
402
|
+
if (pathname.startsWith("/api")) return next();
|
|
359
403
|
const filePath = path.join(DIST_DIR, pathname);
|
|
360
|
-
|
|
361
|
-
await
|
|
362
|
-
|
|
404
|
+
try {
|
|
405
|
+
const stat = await fs.promises.stat(filePath);
|
|
406
|
+
if (stat.isFile()) {
|
|
407
|
+
await sendFile(filePath, req, res);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
} catch {
|
|
363
411
|
}
|
|
364
412
|
const indexPath = path.join(DIST_DIR, "index.html");
|
|
365
|
-
|
|
413
|
+
try {
|
|
414
|
+
await fs.promises.access(indexPath);
|
|
366
415
|
await sendFile(indexPath, req, res);
|
|
367
|
-
|
|
416
|
+
} catch {
|
|
417
|
+
next();
|
|
368
418
|
}
|
|
369
|
-
next();
|
|
370
419
|
}
|
|
371
420
|
function compose(middlewares) {
|
|
372
421
|
return async (req, res) => {
|
|
373
422
|
let idx = 0;
|
|
374
|
-
async
|
|
423
|
+
const next = async () => {
|
|
375
424
|
if (idx >= middlewares.length) return;
|
|
376
425
|
const fn = middlewares[idx++];
|
|
377
426
|
try {
|
|
@@ -382,7 +431,7 @@ function compose(middlewares) {
|
|
|
382
431
|
res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
|
|
383
432
|
}
|
|
384
433
|
}
|
|
385
|
-
}
|
|
434
|
+
};
|
|
386
435
|
await next();
|
|
387
436
|
};
|
|
388
437
|
}
|
|
@@ -390,7 +439,8 @@ async function start() {
|
|
|
390
439
|
await loadEnv(process.cwd());
|
|
391
440
|
if (!fs.existsSync(DIST_DIR)) {
|
|
392
441
|
console.error(`
|
|
393
|
-
${C.RED}\u2717${C.RESET} dist/ not found
|
|
442
|
+
${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
|
|
443
|
+
Run ${C.CYAN}npm run build${C.RESET} first.
|
|
394
444
|
`);
|
|
395
445
|
process.exit(1);
|
|
396
446
|
}
|
|
@@ -417,13 +467,14 @@ async function start() {
|
|
|
417
467
|
});
|
|
418
468
|
server.keepAliveTimeout = 65e3;
|
|
419
469
|
server.headersTimeout = 66e3;
|
|
470
|
+
startKeyboardLoop(port);
|
|
420
471
|
server.listen(port, "0.0.0.0", () => {
|
|
421
472
|
printBanner(port);
|
|
422
473
|
});
|
|
423
|
-
|
|
474
|
+
const shutdown = () => {
|
|
424
475
|
server.close(() => process.exit(0));
|
|
425
476
|
setTimeout(() => process.exit(1), 1e4).unref();
|
|
426
|
-
}
|
|
477
|
+
};
|
|
427
478
|
process.on("SIGTERM", shutdown);
|
|
428
479
|
process.on("SIGINT", shutdown);
|
|
429
480
|
}
|
package/package.json
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bini-server",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.0.4",
|
|
4
|
+
"description": "Production server for bini-router apps.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "./dist/index.
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
7
8
|
"types": "./dist/index.d.ts",
|
|
8
9
|
"exports": {
|
|
9
10
|
".": {
|
|
10
11
|
"import": {
|
|
11
12
|
"types": "./dist/index.d.ts",
|
|
12
13
|
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.cts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
13
18
|
}
|
|
14
19
|
}
|
|
15
20
|
},
|
|
@@ -27,10 +32,10 @@
|
|
|
27
32
|
"clean": "rm -rf dist"
|
|
28
33
|
},
|
|
29
34
|
"dependencies": {
|
|
30
|
-
"bini-env": "
|
|
35
|
+
"bini-env": "1.0.8"
|
|
31
36
|
},
|
|
32
37
|
"engines": {
|
|
33
|
-
"node": ">=
|
|
38
|
+
"node": ">=20.19.0"
|
|
34
39
|
},
|
|
35
40
|
"keywords": [
|
|
36
41
|
"bini",
|
|
@@ -52,15 +57,14 @@
|
|
|
52
57
|
"homepage": "https://bini.js.org",
|
|
53
58
|
"repository": {
|
|
54
59
|
"type": "git",
|
|
55
|
-
"url": "https://github.com/Binidu01/bini-server.git"
|
|
60
|
+
"url": "git+https://github.com/Binidu01/bini-server.git"
|
|
56
61
|
},
|
|
57
62
|
"bugs": {
|
|
58
63
|
"url": "https://github.com/Binidu01/bini-server/issues"
|
|
59
64
|
},
|
|
60
65
|
"devDependencies": {
|
|
61
|
-
"@types/node": "^25",
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"typescript" : "^5"
|
|
66
|
+
"@types/node": "^25.6.0",
|
|
67
|
+
"tsup": "^8.5.1",
|
|
68
|
+
"typescript": "^5.9.3"
|
|
65
69
|
}
|
|
66
70
|
}
|