bini-server 1.0.2 → 1.0.3
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 +20 -88
- package/dist/cli.js +99 -78
- package/dist/index.js +99 -78
- package/package.json +13 -9
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
[](https://www.npmjs.com/package/bini-env)
|
|
9
9
|
|
|
10
10
|
**Zero-dependency production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
|
|
11
|
-
Serves your `dist/` statically and
|
|
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
|
|
|
@@ -18,15 +18,15 @@ Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handl
|
|
|
18
18
|
|
|
19
19
|
- ⚡ **Zero dependencies** — pure Node.js built-ins only
|
|
20
20
|
- 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
|
|
21
|
-
- 🌐 **API routes** —
|
|
21
|
+
- 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
|
|
22
22
|
- 🔀 **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)
|
|
23
|
+
- 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env)
|
|
24
24
|
- 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
|
|
25
25
|
- 🛡️ **CORS** — enabled by default on all API responses
|
|
26
|
-
- ⏱️ **Timeouts** — 30s body read + 30s handler timeout
|
|
26
|
+
- ⏱️ **Timeouts** — 30s body read timeout + 30s handler timeout
|
|
27
27
|
- 🔒 **Body limit** — 10MB request body limit
|
|
28
|
-
- 🔌 **Port auto-increment** — starts at 3000
|
|
29
|
-
- 🪄 **Graceful shutdown** — handles SIGTERM + SIGINT with 10s force-exit fallback
|
|
28
|
+
- 🔌 **Port auto-increment** — starts at `3000`, increments if busy
|
|
29
|
+
- 🪄 **Graceful shutdown** — handles `SIGTERM` + `SIGINT` with 10s force-exit fallback
|
|
30
30
|
- 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
|
|
31
31
|
|
|
32
32
|
---
|
|
@@ -80,57 +80,36 @@ Terminal output:
|
|
|
80
80
|
|
|
81
81
|
## Environment Variables
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
`.env` is loaded automatically at startup — all vars are available in `process.env` in your API handlers with no imports needed.
|
|
84
84
|
|
|
85
85
|
```env
|
|
86
|
-
# .env
|
|
87
86
|
PORT=3000
|
|
88
|
-
|
|
89
|
-
# Server-side vars — used by API routes via getEnv() / requireEnv()
|
|
90
87
|
SMTP_USER=user@smtp.example.com
|
|
91
88
|
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
89
|
```
|
|
97
90
|
|
|
98
|
-
> Client-side `BINI_*` vars are baked into `dist/` at build time by Vite — bini-server loads them into `process.env` but never uses them. They don't cause any errors.
|
|
99
|
-
|
|
100
91
|
---
|
|
101
92
|
|
|
102
|
-
##
|
|
103
|
-
|
|
104
|
-
bini-server runs a plain Node.js `http` server with a three-layer middleware stack:
|
|
93
|
+
## Important: ship your `src/` folder
|
|
105
94
|
|
|
106
|
-
|
|
107
|
-
Request
|
|
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
|
-
```
|
|
95
|
+
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
96
|
|
|
116
|
-
|
|
97
|
+
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
98
|
|
|
118
99
|
---
|
|
119
100
|
|
|
120
101
|
## Port
|
|
121
102
|
|
|
122
|
-
Default port is `3000`. Override via
|
|
123
|
-
|
|
124
|
-
```bash
|
|
125
|
-
PORT=8080 bini-server
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
Or in `.env`:
|
|
103
|
+
Default port is `3000`. Override via `.env` or inline:
|
|
129
104
|
|
|
130
105
|
```env
|
|
131
106
|
PORT=8080
|
|
132
107
|
```
|
|
133
108
|
|
|
109
|
+
```bash
|
|
110
|
+
PORT=8080 bini-server
|
|
111
|
+
```
|
|
112
|
+
|
|
134
113
|
If the port is busy, bini-server automatically increments and warns:
|
|
135
114
|
|
|
136
115
|
```
|
|
@@ -141,7 +120,7 @@ If the port is busy, bini-server automatically increments and warns:
|
|
|
141
120
|
|
|
142
121
|
## Configurable Directories
|
|
143
122
|
|
|
144
|
-
By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars
|
|
123
|
+
By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars:
|
|
145
124
|
|
|
146
125
|
```env
|
|
147
126
|
BINI_API_DIR=src/api # default: src/app/api
|
|
@@ -150,37 +129,6 @@ BINI_DIST_DIR=build # default: dist
|
|
|
150
129
|
|
|
151
130
|
---
|
|
152
131
|
|
|
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
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
---
|
|
183
|
-
|
|
184
132
|
## Deployment
|
|
185
133
|
|
|
186
134
|
### VPS (Ubuntu, Debian, etc.)
|
|
@@ -201,7 +149,7 @@ pm2 startup
|
|
|
201
149
|
|
|
202
150
|
### Railway
|
|
203
151
|
|
|
204
|
-
Set start command to `npm start
|
|
152
|
+
Set start command to `npm start`. Railway injects `PORT` automatically.
|
|
205
153
|
|
|
206
154
|
### Render
|
|
207
155
|
|
|
@@ -217,32 +165,16 @@ Set start command to `npm start`. Render injects `PORT` automatically.
|
|
|
217
165
|
|
|
218
166
|
---
|
|
219
167
|
|
|
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
168
|
## vs `vite preview`
|
|
237
169
|
|
|
238
170
|
| Feature | `vite preview` | `bini-server` |
|
|
239
171
|
|---|---|---|
|
|
240
172
|
| Serves `dist/` | ✅ | ✅ |
|
|
241
|
-
| API routes | ✅
|
|
173
|
+
| API routes | ✅ | ✅ |
|
|
242
174
|
| SPA fallback | ✅ | ✅ |
|
|
243
|
-
| Auto env loading | ✅
|
|
175
|
+
| Auto env loading | ✅ | ✅ |
|
|
244
176
|
| ETag / 304 support | ❌ | ✅ |
|
|
245
|
-
| Production use | ❌
|
|
177
|
+
| Production use | ❌ | ✅ |
|
|
246
178
|
| Body timeout | ❌ | ✅ 30s |
|
|
247
179
|
| Body size limit | ❌ | ✅ 10MB |
|
|
248
180
|
| Handler timeout | ❌ | ✅ 30s |
|
package/dist/cli.js
CHANGED
|
@@ -116,8 +116,18 @@ function scanApiRoutes(dir, baseRoute = "") {
|
|
|
116
116
|
if (!API_EXTS.includes(ext)) continue;
|
|
117
117
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
118
118
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
119
|
-
|
|
120
|
-
|
|
119
|
+
let routePath;
|
|
120
|
+
if (isCatchAll) {
|
|
121
|
+
routePath = `${baseRoute}/*`;
|
|
122
|
+
} else if (base === "index") {
|
|
123
|
+
routePath = baseRoute || "/";
|
|
124
|
+
} else if (isDynamic) {
|
|
125
|
+
routePath = `${baseRoute}/:${base.slice(1, -1)}`;
|
|
126
|
+
} else {
|
|
127
|
+
routePath = `${baseRoute}/${base}`;
|
|
128
|
+
}
|
|
129
|
+
const normalizedPath = `/api${routePath}`;
|
|
130
|
+
routes.push({ routePath: normalizedPath, filePath: fullPath });
|
|
121
131
|
}
|
|
122
132
|
return routes;
|
|
123
133
|
}
|
|
@@ -151,6 +161,7 @@ async function importHandler(filePath) {
|
|
|
151
161
|
try {
|
|
152
162
|
mtime = fs.statSync(filePath).mtimeMs;
|
|
153
163
|
} catch {
|
|
164
|
+
return null;
|
|
154
165
|
}
|
|
155
166
|
const cached = moduleCache.get(filePath);
|
|
156
167
|
if (cached && cached.mtime === mtime) return cached.handler;
|
|
@@ -159,9 +170,9 @@ async function importHandler(filePath) {
|
|
|
159
170
|
const handler = mod.default ?? null;
|
|
160
171
|
moduleCache.set(filePath, { mtime, handler });
|
|
161
172
|
return handler;
|
|
162
|
-
} catch
|
|
173
|
+
} catch {
|
|
163
174
|
moduleCache.delete(filePath);
|
|
164
|
-
|
|
175
|
+
return null;
|
|
165
176
|
}
|
|
166
177
|
}
|
|
167
178
|
function readBody(req) {
|
|
@@ -205,6 +216,9 @@ var CORS_HEADERS = {
|
|
|
205
216
|
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
206
217
|
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
207
218
|
};
|
|
219
|
+
function isHonoApp(handler) {
|
|
220
|
+
return handler && typeof handler.fetch === "function";
|
|
221
|
+
}
|
|
208
222
|
var routeCache = null;
|
|
209
223
|
async function handleApiRequest(req, res, next) {
|
|
210
224
|
try {
|
|
@@ -214,12 +228,24 @@ async function handleApiRequest(req, res, next) {
|
|
|
214
228
|
return;
|
|
215
229
|
}
|
|
216
230
|
if (!routeCache) {
|
|
217
|
-
routeCache =
|
|
231
|
+
routeCache = scanApiRoutes(API_DIR);
|
|
218
232
|
}
|
|
219
233
|
const host = req.headers.host ?? "localhost";
|
|
220
|
-
const url = `http://${host}${req.url}`;
|
|
234
|
+
const url = `http://${host}${req.url ?? ""}`;
|
|
221
235
|
const pathname = new URL(url).pathname;
|
|
222
236
|
const method = (req.method ?? "GET").toUpperCase();
|
|
237
|
+
let matchedRoute;
|
|
238
|
+
for (const route of routeCache) {
|
|
239
|
+
if (matchRoute(route.routePath, pathname) !== null) {
|
|
240
|
+
matchedRoute = route;
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (!matchedRoute) {
|
|
245
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
246
|
+
res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
223
249
|
let body;
|
|
224
250
|
try {
|
|
225
251
|
body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
|
|
@@ -228,70 +254,55 @@ async function handleApiRequest(req, res, next) {
|
|
|
228
254
|
res.end(JSON.stringify({ error: e.message }));
|
|
229
255
|
return;
|
|
230
256
|
}
|
|
231
|
-
const
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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;
|
|
257
|
+
const handler = await importHandler(matchedRoute.filePath);
|
|
258
|
+
if (!handler) {
|
|
259
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
260
|
+
res.end(JSON.stringify({ error: `Failed to load handler for ${matchedRoute.routePath}` }));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
let webRes;
|
|
264
|
+
try {
|
|
265
|
+
if (isHonoApp(handler)) {
|
|
266
|
+
const newUrl = url.replace(/^https?:\/\/[^\/]+\/api/, `http://${host}`);
|
|
267
|
+
const modifiedReq = new Request(newUrl, {
|
|
268
|
+
method,
|
|
269
|
+
headers: normalizeHeaders(req.headers),
|
|
270
|
+
body: body ?? null
|
|
271
|
+
});
|
|
272
|
+
webRes = await handler.fetch(modifiedReq);
|
|
273
|
+
} else if (typeof handler === "function") {
|
|
274
|
+
const params = matchRoute(matchedRoute.routePath, pathname);
|
|
275
|
+
const reqWithParams = new Request(url, {
|
|
276
|
+
method,
|
|
277
|
+
headers: {
|
|
278
|
+
...normalizeHeaders(req.headers),
|
|
279
|
+
"x-bini-params": JSON.stringify(params ?? {})
|
|
280
|
+
},
|
|
281
|
+
body: body ?? null
|
|
282
|
+
});
|
|
283
|
+
const result = await Promise.race([
|
|
284
|
+
handler(reqWithParams),
|
|
285
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT))
|
|
286
|
+
]);
|
|
287
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
288
|
+
status: 200,
|
|
289
|
+
headers: { "Content-Type": "application/json" }
|
|
290
|
+
});
|
|
291
|
+
} else {
|
|
292
|
+
throw new Error("Invalid handler type");
|
|
283
293
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
});
|
|
288
|
-
res.writeHead(webRes.status, finalHeaders);
|
|
289
|
-
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
294
|
+
} catch (e) {
|
|
295
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
296
|
+
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
290
297
|
return;
|
|
291
298
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
299
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
300
|
+
webRes.headers.forEach((v, k) => {
|
|
301
|
+
finalHeaders[k] = v;
|
|
302
|
+
});
|
|
303
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
304
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
305
|
+
} catch (e) {
|
|
295
306
|
next();
|
|
296
307
|
}
|
|
297
308
|
}
|
|
@@ -327,7 +338,7 @@ async function sendFile(filePath, req, res) {
|
|
|
327
338
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
328
339
|
let stat;
|
|
329
340
|
try {
|
|
330
|
-
stat = fs.
|
|
341
|
+
stat = await fs.promises.stat(filePath);
|
|
331
342
|
} catch {
|
|
332
343
|
res.writeHead(404);
|
|
333
344
|
res.end("Not found");
|
|
@@ -357,23 +368,33 @@ async function sendFile(filePath, req, res) {
|
|
|
357
368
|
}
|
|
358
369
|
}
|
|
359
370
|
async function serveStatic(req, res, next) {
|
|
360
|
-
const pathname = new URL(req.url ?? "/",
|
|
371
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
372
|
+
if (pathname.startsWith("/api")) {
|
|
373
|
+
return next();
|
|
374
|
+
}
|
|
361
375
|
const filePath = path.join(DIST_DIR, pathname);
|
|
362
|
-
|
|
363
|
-
await
|
|
364
|
-
|
|
376
|
+
try {
|
|
377
|
+
await fs.promises.access(filePath);
|
|
378
|
+
const stat = await fs.promises.stat(filePath);
|
|
379
|
+
if (stat.isFile()) {
|
|
380
|
+
await sendFile(filePath, req, res);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
} catch {
|
|
365
384
|
}
|
|
366
385
|
const indexPath = path.join(DIST_DIR, "index.html");
|
|
367
|
-
|
|
386
|
+
try {
|
|
387
|
+
await fs.promises.access(indexPath);
|
|
368
388
|
await sendFile(indexPath, req, res);
|
|
369
389
|
return;
|
|
390
|
+
} catch {
|
|
391
|
+
next();
|
|
370
392
|
}
|
|
371
|
-
next();
|
|
372
393
|
}
|
|
373
394
|
function compose(middlewares) {
|
|
374
395
|
return async (req, res) => {
|
|
375
396
|
let idx = 0;
|
|
376
|
-
async
|
|
397
|
+
const next = async () => {
|
|
377
398
|
if (idx >= middlewares.length) return;
|
|
378
399
|
const fn = middlewares[idx++];
|
|
379
400
|
try {
|
|
@@ -384,7 +405,7 @@ function compose(middlewares) {
|
|
|
384
405
|
res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
|
|
385
406
|
}
|
|
386
407
|
}
|
|
387
|
-
}
|
|
408
|
+
};
|
|
388
409
|
await next();
|
|
389
410
|
};
|
|
390
411
|
}
|
|
@@ -422,10 +443,10 @@ async function start() {
|
|
|
422
443
|
server.listen(port, "0.0.0.0", () => {
|
|
423
444
|
printBanner(port);
|
|
424
445
|
});
|
|
425
|
-
|
|
446
|
+
const shutdown = () => {
|
|
426
447
|
server.close(() => process.exit(0));
|
|
427
448
|
setTimeout(() => process.exit(1), 1e4).unref();
|
|
428
|
-
}
|
|
449
|
+
};
|
|
429
450
|
process.on("SIGTERM", shutdown);
|
|
430
451
|
process.on("SIGINT", shutdown);
|
|
431
452
|
}
|
package/dist/index.js
CHANGED
|
@@ -114,8 +114,18 @@ function scanApiRoutes(dir, baseRoute = "") {
|
|
|
114
114
|
if (!API_EXTS.includes(ext)) continue;
|
|
115
115
|
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
116
116
|
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
let routePath;
|
|
118
|
+
if (isCatchAll) {
|
|
119
|
+
routePath = `${baseRoute}/*`;
|
|
120
|
+
} else if (base === "index") {
|
|
121
|
+
routePath = baseRoute || "/";
|
|
122
|
+
} else if (isDynamic) {
|
|
123
|
+
routePath = `${baseRoute}/:${base.slice(1, -1)}`;
|
|
124
|
+
} else {
|
|
125
|
+
routePath = `${baseRoute}/${base}`;
|
|
126
|
+
}
|
|
127
|
+
const normalizedPath = `/api${routePath}`;
|
|
128
|
+
routes.push({ routePath: normalizedPath, filePath: fullPath });
|
|
119
129
|
}
|
|
120
130
|
return routes;
|
|
121
131
|
}
|
|
@@ -149,6 +159,7 @@ async function importHandler(filePath) {
|
|
|
149
159
|
try {
|
|
150
160
|
mtime = fs.statSync(filePath).mtimeMs;
|
|
151
161
|
} catch {
|
|
162
|
+
return null;
|
|
152
163
|
}
|
|
153
164
|
const cached = moduleCache.get(filePath);
|
|
154
165
|
if (cached && cached.mtime === mtime) return cached.handler;
|
|
@@ -157,9 +168,9 @@ async function importHandler(filePath) {
|
|
|
157
168
|
const handler = mod.default ?? null;
|
|
158
169
|
moduleCache.set(filePath, { mtime, handler });
|
|
159
170
|
return handler;
|
|
160
|
-
} catch
|
|
171
|
+
} catch {
|
|
161
172
|
moduleCache.delete(filePath);
|
|
162
|
-
|
|
173
|
+
return null;
|
|
163
174
|
}
|
|
164
175
|
}
|
|
165
176
|
function readBody(req) {
|
|
@@ -203,6 +214,9 @@ var CORS_HEADERS = {
|
|
|
203
214
|
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
204
215
|
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
205
216
|
};
|
|
217
|
+
function isHonoApp(handler) {
|
|
218
|
+
return handler && typeof handler.fetch === "function";
|
|
219
|
+
}
|
|
206
220
|
var routeCache = null;
|
|
207
221
|
async function handleApiRequest(req, res, next) {
|
|
208
222
|
try {
|
|
@@ -212,12 +226,24 @@ async function handleApiRequest(req, res, next) {
|
|
|
212
226
|
return;
|
|
213
227
|
}
|
|
214
228
|
if (!routeCache) {
|
|
215
|
-
routeCache =
|
|
229
|
+
routeCache = scanApiRoutes(API_DIR);
|
|
216
230
|
}
|
|
217
231
|
const host = req.headers.host ?? "localhost";
|
|
218
|
-
const url = `http://${host}${req.url}`;
|
|
232
|
+
const url = `http://${host}${req.url ?? ""}`;
|
|
219
233
|
const pathname = new URL(url).pathname;
|
|
220
234
|
const method = (req.method ?? "GET").toUpperCase();
|
|
235
|
+
let matchedRoute;
|
|
236
|
+
for (const route of routeCache) {
|
|
237
|
+
if (matchRoute(route.routePath, pathname) !== null) {
|
|
238
|
+
matchedRoute = route;
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (!matchedRoute) {
|
|
243
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
244
|
+
res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
221
247
|
let body;
|
|
222
248
|
try {
|
|
223
249
|
body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
|
|
@@ -226,70 +252,55 @@ async function handleApiRequest(req, res, next) {
|
|
|
226
252
|
res.end(JSON.stringify({ error: e.message }));
|
|
227
253
|
return;
|
|
228
254
|
}
|
|
229
|
-
const
|
|
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
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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;
|
|
255
|
+
const handler = await importHandler(matchedRoute.filePath);
|
|
256
|
+
if (!handler) {
|
|
257
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
258
|
+
res.end(JSON.stringify({ error: `Failed to load handler for ${matchedRoute.routePath}` }));
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
let webRes;
|
|
262
|
+
try {
|
|
263
|
+
if (isHonoApp(handler)) {
|
|
264
|
+
const newUrl = url.replace(/^https?:\/\/[^\/]+\/api/, `http://${host}`);
|
|
265
|
+
const modifiedReq = new Request(newUrl, {
|
|
266
|
+
method,
|
|
267
|
+
headers: normalizeHeaders(req.headers),
|
|
268
|
+
body: body ?? null
|
|
269
|
+
});
|
|
270
|
+
webRes = await handler.fetch(modifiedReq);
|
|
271
|
+
} else if (typeof handler === "function") {
|
|
272
|
+
const params = matchRoute(matchedRoute.routePath, pathname);
|
|
273
|
+
const reqWithParams = new Request(url, {
|
|
274
|
+
method,
|
|
275
|
+
headers: {
|
|
276
|
+
...normalizeHeaders(req.headers),
|
|
277
|
+
"x-bini-params": JSON.stringify(params ?? {})
|
|
278
|
+
},
|
|
279
|
+
body: body ?? null
|
|
280
|
+
});
|
|
281
|
+
const result = await Promise.race([
|
|
282
|
+
handler(reqWithParams),
|
|
283
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT))
|
|
284
|
+
]);
|
|
285
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
286
|
+
status: 200,
|
|
287
|
+
headers: { "Content-Type": "application/json" }
|
|
288
|
+
});
|
|
289
|
+
} else {
|
|
290
|
+
throw new Error("Invalid handler type");
|
|
281
291
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
});
|
|
286
|
-
res.writeHead(webRes.status, finalHeaders);
|
|
287
|
-
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
292
|
+
} catch (e) {
|
|
293
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
294
|
+
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
288
295
|
return;
|
|
289
296
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
297
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
298
|
+
webRes.headers.forEach((v, k) => {
|
|
299
|
+
finalHeaders[k] = v;
|
|
300
|
+
});
|
|
301
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
302
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
303
|
+
} catch (e) {
|
|
293
304
|
next();
|
|
294
305
|
}
|
|
295
306
|
}
|
|
@@ -325,7 +336,7 @@ async function sendFile(filePath, req, res) {
|
|
|
325
336
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
326
337
|
let stat;
|
|
327
338
|
try {
|
|
328
|
-
stat = fs.
|
|
339
|
+
stat = await fs.promises.stat(filePath);
|
|
329
340
|
} catch {
|
|
330
341
|
res.writeHead(404);
|
|
331
342
|
res.end("Not found");
|
|
@@ -355,23 +366,33 @@ async function sendFile(filePath, req, res) {
|
|
|
355
366
|
}
|
|
356
367
|
}
|
|
357
368
|
async function serveStatic(req, res, next) {
|
|
358
|
-
const pathname = new URL(req.url ?? "/",
|
|
369
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
370
|
+
if (pathname.startsWith("/api")) {
|
|
371
|
+
return next();
|
|
372
|
+
}
|
|
359
373
|
const filePath = path.join(DIST_DIR, pathname);
|
|
360
|
-
|
|
361
|
-
await
|
|
362
|
-
|
|
374
|
+
try {
|
|
375
|
+
await fs.promises.access(filePath);
|
|
376
|
+
const stat = await fs.promises.stat(filePath);
|
|
377
|
+
if (stat.isFile()) {
|
|
378
|
+
await sendFile(filePath, req, res);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
} catch {
|
|
363
382
|
}
|
|
364
383
|
const indexPath = path.join(DIST_DIR, "index.html");
|
|
365
|
-
|
|
384
|
+
try {
|
|
385
|
+
await fs.promises.access(indexPath);
|
|
366
386
|
await sendFile(indexPath, req, res);
|
|
367
387
|
return;
|
|
388
|
+
} catch {
|
|
389
|
+
next();
|
|
368
390
|
}
|
|
369
|
-
next();
|
|
370
391
|
}
|
|
371
392
|
function compose(middlewares) {
|
|
372
393
|
return async (req, res) => {
|
|
373
394
|
let idx = 0;
|
|
374
|
-
async
|
|
395
|
+
const next = async () => {
|
|
375
396
|
if (idx >= middlewares.length) return;
|
|
376
397
|
const fn = middlewares[idx++];
|
|
377
398
|
try {
|
|
@@ -382,7 +403,7 @@ function compose(middlewares) {
|
|
|
382
403
|
res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
|
|
383
404
|
}
|
|
384
405
|
}
|
|
385
|
-
}
|
|
406
|
+
};
|
|
386
407
|
await next();
|
|
387
408
|
};
|
|
388
409
|
}
|
|
@@ -420,10 +441,10 @@ async function start() {
|
|
|
420
441
|
server.listen(port, "0.0.0.0", () => {
|
|
421
442
|
printBanner(port);
|
|
422
443
|
});
|
|
423
|
-
|
|
444
|
+
const shutdown = () => {
|
|
424
445
|
server.close(() => process.exit(0));
|
|
425
446
|
setTimeout(() => process.exit(1), 1e4).unref();
|
|
426
|
-
}
|
|
447
|
+
};
|
|
427
448
|
process.on("SIGTERM", shutdown);
|
|
428
449
|
process.on("SIGINT", shutdown);
|
|
429
450
|
}
|
package/package.json
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bini-server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "Zero-dependency production server for bini-router apps — static files, API routes, SPA fallback",
|
|
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.3.5",
|
|
67
|
+
"tsup": "^8.5.1",
|
|
68
|
+
"typescript": "^5.9.3"
|
|
65
69
|
}
|
|
66
70
|
}
|