bini-server 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/Readme.md +203 -0
- package/dist/cli.js +381 -0
- package/dist/index.js +379 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Binidu Ranasinghe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/Readme.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# bini-server
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/bini-server)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
[](https://nodejs.org)
|
|
8
|
+
[](./package.json)
|
|
9
|
+
|
|
10
|
+
**Zero-dependency production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
|
|
11
|
+
Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handlers — just like Vite's preview server, but for production.
|
|
12
|
+
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Features
|
|
18
|
+
|
|
19
|
+
- ⚡ **Zero dependencies** — pure Node.js built-ins only
|
|
20
|
+
- 🗂️ **Static file serving** — streams `dist/` with correct MIME types and cache headers
|
|
21
|
+
- 🌐 **API routes** — proxies `/api/*` to your `src/app/api/` handlers (Hono apps + plain functions)
|
|
22
|
+
- 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
|
|
23
|
+
- 🛡️ **CORS** — enabled by default on all API responses
|
|
24
|
+
- ⏱️ **Timeouts** — 30s body read + 30s handler timeout with proper error responses
|
|
25
|
+
- 🔒 **Body limit** — 10MB request body limit
|
|
26
|
+
- 🔌 **Port auto-increment** — starts at 3000, increments if busy
|
|
27
|
+
- 🪄 **Graceful shutdown** — handles SIGTERM + SIGINT with 10s force-exit fallback
|
|
28
|
+
- 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Requirements
|
|
33
|
+
|
|
34
|
+
- Node.js **≥ 22**
|
|
35
|
+
- A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install bini-server
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
Add to your `package.json`:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "vite build",
|
|
55
|
+
"start": "bini-server"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Then:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npm run build # build your app
|
|
64
|
+
npm start # serve it in production
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Terminal output:
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
ß Bini.js (production)
|
|
71
|
+
|
|
72
|
+
➜ Environments: .env, .env.production
|
|
73
|
+
➜ Local: http://localhost:3000/
|
|
74
|
+
➜ Network: http://192.168.1.5:3000/
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## How it works
|
|
80
|
+
|
|
81
|
+
`bini-server` runs a plain Node.js `http` server with a three-layer middleware stack:
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
Request
|
|
85
|
+
│
|
|
86
|
+
├─ /api/* → src/app/api/ handlers (Hono apps or plain functions)
|
|
87
|
+
│
|
|
88
|
+
├─ /* → stream static file from dist/
|
|
89
|
+
│
|
|
90
|
+
└─ /* → dist/index.html (SPA fallback)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
No Vite, no Express, no Fastify — just Node's built-in `http` module.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## Port
|
|
98
|
+
|
|
99
|
+
Default port is `3000`. Override via environment variable:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
PORT=8080 bini-server
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
If the port is busy, `bini-server` automatically increments and warns:
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
⚠ Port 3000 is in use, using port 3001 instead.
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## API Routes
|
|
114
|
+
|
|
115
|
+
`bini-server` reads `src/app/api/` directly — the same files your dev server uses. Both Hono apps and plain function handlers are supported:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
// src/app/api/hello.ts
|
|
119
|
+
|
|
120
|
+
// ✅ Hono app
|
|
121
|
+
import { Hono } from 'hono'
|
|
122
|
+
const app = new Hono().basePath('/api')
|
|
123
|
+
app.get('/hello', (c) => c.json({ message: 'hello' }))
|
|
124
|
+
export default app
|
|
125
|
+
|
|
126
|
+
// ✅ Plain function
|
|
127
|
+
export default function handler(req: Request) {
|
|
128
|
+
return Response.json({ message: 'hello' })
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Deployment
|
|
135
|
+
|
|
136
|
+
### VPS (Ubuntu, Debian, etc.)
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
npm run build
|
|
140
|
+
npm start
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Use [pm2](https://pm2.keymetrics.io/) to keep it running:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
npm install -g pm2
|
|
147
|
+
pm2 start "npm start" --name my-app
|
|
148
|
+
pm2 save
|
|
149
|
+
pm2 startup
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Railway
|
|
153
|
+
|
|
154
|
+
Set start command to `npm start` in your Railway project settings. Railway injects `PORT` automatically.
|
|
155
|
+
|
|
156
|
+
### Render
|
|
157
|
+
|
|
158
|
+
Set start command to `npm start`. Render injects `PORT` automatically.
|
|
159
|
+
|
|
160
|
+
### Fly.io
|
|
161
|
+
|
|
162
|
+
```toml
|
|
163
|
+
# fly.toml
|
|
164
|
+
[processes]
|
|
165
|
+
app = "npm start"
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## Project structure
|
|
171
|
+
|
|
172
|
+
`bini-server` expects the standard bini-router project layout:
|
|
173
|
+
|
|
174
|
+
```
|
|
175
|
+
my-app/
|
|
176
|
+
├── src/
|
|
177
|
+
│ └── app/
|
|
178
|
+
│ └── api/ ← API route handlers
|
|
179
|
+
├── dist/ ← built frontend (vite build output)
|
|
180
|
+
└── package.json
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## vs `vite preview`
|
|
186
|
+
|
|
187
|
+
| Feature | `vite preview` | `bini-server` |
|
|
188
|
+
|---|---|---|
|
|
189
|
+
| Serves `dist/` | ✅ | ✅ |
|
|
190
|
+
| API routes | ✅ via bini-router | ✅ via bini-router |
|
|
191
|
+
| SPA fallback | ✅ | ✅ |
|
|
192
|
+
| Production use | ❌ not recommended | ✅ |
|
|
193
|
+
| Body timeout | ❌ | ✅ 30s |
|
|
194
|
+
| Body size limit | ❌ | ✅ 10MB |
|
|
195
|
+
| Handler timeout | ❌ | ✅ 30s |
|
|
196
|
+
| Graceful shutdown | ❌ | ✅ |
|
|
197
|
+
| Zero dependencies | ✅ | ✅ |
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT © [Binidu Ranasinghe](https://bini.js.org)
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import http from "http";
|
|
5
|
+
import fs from "fs";
|
|
6
|
+
import path from "path";
|
|
7
|
+
import os from "os";
|
|
8
|
+
import net from "net";
|
|
9
|
+
import { pathToFileURL } from "url";
|
|
10
|
+
import { pipeline } from "stream/promises";
|
|
11
|
+
import { createReadStream } from "fs";
|
|
12
|
+
var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
|
|
13
|
+
var API_DIR = path.join(process.cwd(), "src/app/api");
|
|
14
|
+
var DIST_DIR = path.join(process.cwd(), "dist");
|
|
15
|
+
var API_EXTS = [".ts", ".js"];
|
|
16
|
+
var BODY_TIMEOUT = 3e4;
|
|
17
|
+
var HANDLER_TIMEOUT = 3e4;
|
|
18
|
+
var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
|
|
19
|
+
var C = {
|
|
20
|
+
CYAN: "\x1B[36m",
|
|
21
|
+
RESET: "\x1B[0m",
|
|
22
|
+
GREEN: "\x1B[32m",
|
|
23
|
+
RED: "\x1B[31m",
|
|
24
|
+
YELLOW: "\x1B[33m",
|
|
25
|
+
DIM: "\x1B[2m"
|
|
26
|
+
};
|
|
27
|
+
function getAllNetworkIps() {
|
|
28
|
+
const ifaces = os.networkInterfaces();
|
|
29
|
+
const ips = [];
|
|
30
|
+
for (const name in ifaces) {
|
|
31
|
+
if (/docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i.test(name)) continue;
|
|
32
|
+
for (const iface of ifaces[name] ?? []) {
|
|
33
|
+
if (iface.internal || iface.family !== "IPv4") continue;
|
|
34
|
+
ips.push(iface.address);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return [...new Set(ips)];
|
|
38
|
+
}
|
|
39
|
+
function detectEnvFiles() {
|
|
40
|
+
const nodeEnv = process.env.NODE_ENV ?? "production";
|
|
41
|
+
const candidates = [
|
|
42
|
+
".env.local",
|
|
43
|
+
`.env.${nodeEnv}.local`,
|
|
44
|
+
`.env.${nodeEnv}`,
|
|
45
|
+
".env"
|
|
46
|
+
];
|
|
47
|
+
return candidates.filter((f) => fs.existsSync(path.join(process.cwd(), f)));
|
|
48
|
+
}
|
|
49
|
+
function printBanner(port) {
|
|
50
|
+
const networkIps = getAllNetworkIps();
|
|
51
|
+
const envFiles = detectEnvFiles();
|
|
52
|
+
console.log(`
|
|
53
|
+
${C.CYAN}\xDF Bini.js${C.RESET} (production)
|
|
54
|
+
`);
|
|
55
|
+
if (envFiles.length > 0) {
|
|
56
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
|
|
57
|
+
}
|
|
58
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
|
|
59
|
+
for (const ip of networkIps) {
|
|
60
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${ip}:${port}/${C.RESET}`);
|
|
61
|
+
}
|
|
62
|
+
if (!fs.existsSync(API_DIR)) {
|
|
63
|
+
console.log(`
|
|
64
|
+
${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
|
|
65
|
+
}
|
|
66
|
+
console.log("");
|
|
67
|
+
}
|
|
68
|
+
async function isPortFree(port) {
|
|
69
|
+
return new Promise((resolve) => {
|
|
70
|
+
const server = net.createServer();
|
|
71
|
+
server.once("error", () => resolve(false));
|
|
72
|
+
server.once("listening", () => server.close(() => resolve(true)));
|
|
73
|
+
server.listen(port, "0.0.0.0");
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async function findFreePort(start2) {
|
|
77
|
+
for (let port = start2; port < start2 + 100; port++) {
|
|
78
|
+
if (await isPortFree(port)) {
|
|
79
|
+
if (port !== start2) {
|
|
80
|
+
console.log(`
|
|
81
|
+
${C.YELLOW}\u26A0${C.RESET} Port ${start2} is in use, using port ${C.CYAN}${port}${C.RESET} instead.`);
|
|
82
|
+
}
|
|
83
|
+
return port;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`No free port found between ${start2} and ${start2 + 100}`);
|
|
87
|
+
}
|
|
88
|
+
function scanApiRoutes(dir, baseRoute = "") {
|
|
89
|
+
const routes = [];
|
|
90
|
+
if (!fs.existsSync(dir)) return routes;
|
|
91
|
+
let entries;
|
|
92
|
+
try {
|
|
93
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
94
|
+
} catch {
|
|
95
|
+
return routes;
|
|
96
|
+
}
|
|
97
|
+
for (const entry of entries) {
|
|
98
|
+
if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
|
|
99
|
+
const fullPath = path.join(dir, entry.name);
|
|
100
|
+
if (entry.isDirectory()) {
|
|
101
|
+
const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
|
|
102
|
+
const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
|
|
103
|
+
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
104
|
+
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`));
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const ext = path.extname(entry.name);
|
|
108
|
+
const base = path.basename(entry.name, ext);
|
|
109
|
+
if (!API_EXTS.includes(ext)) continue;
|
|
110
|
+
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
111
|
+
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
112
|
+
const routePath = isCatchAll ? `${baseRoute}/*` : base === "index" ? baseRoute || "/" : isDynamic ? `${baseRoute}/:${base.slice(1, -1)}` : `${baseRoute}/${base}`;
|
|
113
|
+
routes.push({ routePath, filePath: fullPath });
|
|
114
|
+
}
|
|
115
|
+
return routes;
|
|
116
|
+
}
|
|
117
|
+
function matchRoute(pattern, pathname) {
|
|
118
|
+
const patParts = pattern.split("/").filter(Boolean);
|
|
119
|
+
const urlParts = pathname.split("/").filter(Boolean);
|
|
120
|
+
const isCatchAll = patParts[patParts.length - 1] === "*";
|
|
121
|
+
if (isCatchAll) {
|
|
122
|
+
const prefix = patParts.slice(0, -1);
|
|
123
|
+
if (urlParts.length < prefix.length) return null;
|
|
124
|
+
for (let i = 0; i < prefix.length; i++) {
|
|
125
|
+
if (prefix[i].startsWith(":")) continue;
|
|
126
|
+
if (prefix[i] !== urlParts[i]) return null;
|
|
127
|
+
}
|
|
128
|
+
return { "*": urlParts.slice(prefix.length).join("/") };
|
|
129
|
+
}
|
|
130
|
+
if (patParts.length !== urlParts.length) return null;
|
|
131
|
+
const params = {};
|
|
132
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
133
|
+
if (patParts[i].startsWith(":")) {
|
|
134
|
+
params[patParts[i].slice(1)] = decodeURIComponent(urlParts[i]);
|
|
135
|
+
} else if (patParts[i] !== urlParts[i]) {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return params;
|
|
140
|
+
}
|
|
141
|
+
var moduleCache = /* @__PURE__ */ new Map();
|
|
142
|
+
async function importHandler(filePath) {
|
|
143
|
+
let mtime = 0;
|
|
144
|
+
try {
|
|
145
|
+
mtime = fs.statSync(filePath).mtimeMs;
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
const cached = moduleCache.get(filePath);
|
|
149
|
+
if (cached && cached.mtime === mtime) return cached.handler;
|
|
150
|
+
const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
|
|
151
|
+
const handler = mod.default ?? null;
|
|
152
|
+
moduleCache.set(filePath, { mtime, handler });
|
|
153
|
+
return handler;
|
|
154
|
+
}
|
|
155
|
+
function readBody(req) {
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
const chunks = [];
|
|
158
|
+
let size = 0;
|
|
159
|
+
const timeout = setTimeout(() => {
|
|
160
|
+
req.destroy();
|
|
161
|
+
reject(new Error("Request body timeout"));
|
|
162
|
+
}, BODY_TIMEOUT);
|
|
163
|
+
req.on("data", (chunk) => {
|
|
164
|
+
size += chunk.byteLength;
|
|
165
|
+
if (size > BODY_SIZE_LIMIT) {
|
|
166
|
+
clearTimeout(timeout);
|
|
167
|
+
req.destroy();
|
|
168
|
+
reject(new Error("Request body too large"));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
chunks.push(chunk);
|
|
172
|
+
});
|
|
173
|
+
req.on("end", () => {
|
|
174
|
+
clearTimeout(timeout);
|
|
175
|
+
resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
|
|
176
|
+
});
|
|
177
|
+
req.on("error", (err) => {
|
|
178
|
+
clearTimeout(timeout);
|
|
179
|
+
reject(err);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
function normalizeHeaders(raw) {
|
|
184
|
+
return Object.fromEntries(
|
|
185
|
+
Object.entries(raw).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v])
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
var routeCache = null;
|
|
189
|
+
var CORS_HEADERS = {
|
|
190
|
+
"Access-Control-Allow-Origin": "*",
|
|
191
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
192
|
+
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
193
|
+
};
|
|
194
|
+
async function handleApiRequest(req, res, next) {
|
|
195
|
+
try {
|
|
196
|
+
if (req.method === "OPTIONS") {
|
|
197
|
+
res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
|
|
198
|
+
res.end();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (!routeCache) {
|
|
202
|
+
routeCache = { routes: scanApiRoutes(API_DIR, "/api") };
|
|
203
|
+
}
|
|
204
|
+
const host = req.headers.host ?? "localhost";
|
|
205
|
+
const url = `http://${host}${req.url}`;
|
|
206
|
+
const pathname = new URL(url).pathname;
|
|
207
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
208
|
+
let body;
|
|
209
|
+
try {
|
|
210
|
+
body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
|
|
211
|
+
} catch (e) {
|
|
212
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
213
|
+
res.end(JSON.stringify({ error: e.message }));
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const webReq = new Request(url, {
|
|
217
|
+
method,
|
|
218
|
+
headers: normalizeHeaders(req.headers),
|
|
219
|
+
body: body ?? null
|
|
220
|
+
});
|
|
221
|
+
for (const route of routeCache.routes) {
|
|
222
|
+
const handler = await importHandler(route.filePath);
|
|
223
|
+
if (!handler) continue;
|
|
224
|
+
let webRes;
|
|
225
|
+
try {
|
|
226
|
+
if (typeof handler.fetch === "function") {
|
|
227
|
+
const result = await Promise.race([
|
|
228
|
+
handler.fetch(webReq.clone()),
|
|
229
|
+
new Promise(
|
|
230
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
231
|
+
)
|
|
232
|
+
]);
|
|
233
|
+
webRes = result;
|
|
234
|
+
if (webRes.status === 404) continue;
|
|
235
|
+
} else if (typeof handler === "function") {
|
|
236
|
+
const params = matchRoute(route.routePath, pathname);
|
|
237
|
+
if (params === null) continue;
|
|
238
|
+
const reqWithParams = new Request(webReq.clone(), {
|
|
239
|
+
headers: {
|
|
240
|
+
...normalizeHeaders(req.headers),
|
|
241
|
+
"x-bini-params": JSON.stringify(params)
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
const result = await Promise.race([
|
|
245
|
+
handler(reqWithParams),
|
|
246
|
+
new Promise(
|
|
247
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
248
|
+
)
|
|
249
|
+
]);
|
|
250
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
251
|
+
status: 200,
|
|
252
|
+
headers: { "Content-Type": "application/json" }
|
|
253
|
+
});
|
|
254
|
+
} else {
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
} catch (e) {
|
|
258
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
259
|
+
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
263
|
+
webRes.headers.forEach((v, k) => {
|
|
264
|
+
finalHeaders[k] = v;
|
|
265
|
+
});
|
|
266
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
267
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
271
|
+
res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
|
|
272
|
+
} catch {
|
|
273
|
+
next();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
var MIME = {
|
|
277
|
+
".html": "text/html; charset=utf-8",
|
|
278
|
+
".js": "application/javascript",
|
|
279
|
+
".css": "text/css",
|
|
280
|
+
".json": "application/json",
|
|
281
|
+
".png": "image/png",
|
|
282
|
+
".jpg": "image/jpeg",
|
|
283
|
+
".jpeg": "image/jpeg",
|
|
284
|
+
".svg": "image/svg+xml",
|
|
285
|
+
".ico": "image/x-icon",
|
|
286
|
+
".webp": "image/webp",
|
|
287
|
+
".woff": "font/woff",
|
|
288
|
+
".woff2": "font/woff2",
|
|
289
|
+
".ttf": "font/ttf",
|
|
290
|
+
".eot": "application/vnd.ms-fontobject",
|
|
291
|
+
".txt": "text/plain",
|
|
292
|
+
".webmanifest": "application/manifest+json"
|
|
293
|
+
};
|
|
294
|
+
async function sendFile(filePath, res) {
|
|
295
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
296
|
+
const mimeType = MIME[ext] ?? "application/octet-stream";
|
|
297
|
+
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
298
|
+
let stat;
|
|
299
|
+
try {
|
|
300
|
+
stat = fs.statSync(filePath);
|
|
301
|
+
} catch {
|
|
302
|
+
res.writeHead(404);
|
|
303
|
+
res.end("Not found");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
res.writeHead(200, {
|
|
307
|
+
"Content-Type": mimeType,
|
|
308
|
+
"Content-Length": stat.size,
|
|
309
|
+
"Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
|
|
310
|
+
"X-Powered-By": "Bini.js"
|
|
311
|
+
});
|
|
312
|
+
try {
|
|
313
|
+
await pipeline(createReadStream(filePath), res);
|
|
314
|
+
} catch {
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async function serveStatic(req, res, next) {
|
|
318
|
+
const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
|
|
319
|
+
const filePath = path.join(DIST_DIR, pathname);
|
|
320
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
321
|
+
await sendFile(filePath, res);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const indexPath = path.join(DIST_DIR, "index.html");
|
|
325
|
+
if (fs.existsSync(indexPath)) {
|
|
326
|
+
await sendFile(indexPath, res);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
next();
|
|
330
|
+
}
|
|
331
|
+
function compose(middlewares) {
|
|
332
|
+
return async (req, res) => {
|
|
333
|
+
let idx = 0;
|
|
334
|
+
async function next() {
|
|
335
|
+
if (idx >= middlewares.length) return;
|
|
336
|
+
const fn = middlewares[idx++];
|
|
337
|
+
await fn(req, res, next);
|
|
338
|
+
}
|
|
339
|
+
await next();
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
async function start() {
|
|
343
|
+
if (!fs.existsSync(DIST_DIR)) {
|
|
344
|
+
console.error(`
|
|
345
|
+
${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
|
|
346
|
+
`);
|
|
347
|
+
process.exit(1);
|
|
348
|
+
}
|
|
349
|
+
const port = await findFreePort(DEFAULT_PORT);
|
|
350
|
+
const handler = compose([
|
|
351
|
+
async (req, res, next) => {
|
|
352
|
+
if (!req.url?.startsWith("/api")) return next();
|
|
353
|
+
await handleApiRequest(req, res, next);
|
|
354
|
+
},
|
|
355
|
+
serveStatic,
|
|
356
|
+
(_req, res) => {
|
|
357
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
358
|
+
res.end("Not found");
|
|
359
|
+
}
|
|
360
|
+
]);
|
|
361
|
+
const server = http.createServer((req, res) => {
|
|
362
|
+
handler(req, res).catch(() => {
|
|
363
|
+
if (!res.headersSent) {
|
|
364
|
+
res.writeHead(500);
|
|
365
|
+
res.end("Internal Server Error");
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
server.listen(port, "0.0.0.0", () => {
|
|
370
|
+
printBanner(port);
|
|
371
|
+
});
|
|
372
|
+
function shutdown() {
|
|
373
|
+
server.close(() => process.exit(0));
|
|
374
|
+
setTimeout(() => process.exit(1), 1e4).unref();
|
|
375
|
+
}
|
|
376
|
+
process.on("SIGTERM", shutdown);
|
|
377
|
+
process.on("SIGINT", shutdown);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/cli.ts
|
|
381
|
+
start();
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import http from "http";
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import os from "os";
|
|
6
|
+
import net from "net";
|
|
7
|
+
import { pathToFileURL } from "url";
|
|
8
|
+
import { pipeline } from "stream/promises";
|
|
9
|
+
import { createReadStream } from "fs";
|
|
10
|
+
var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
|
|
11
|
+
var API_DIR = path.join(process.cwd(), "src/app/api");
|
|
12
|
+
var DIST_DIR = path.join(process.cwd(), "dist");
|
|
13
|
+
var API_EXTS = [".ts", ".js"];
|
|
14
|
+
var BODY_TIMEOUT = 3e4;
|
|
15
|
+
var HANDLER_TIMEOUT = 3e4;
|
|
16
|
+
var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
|
|
17
|
+
var C = {
|
|
18
|
+
CYAN: "\x1B[36m",
|
|
19
|
+
RESET: "\x1B[0m",
|
|
20
|
+
GREEN: "\x1B[32m",
|
|
21
|
+
RED: "\x1B[31m",
|
|
22
|
+
YELLOW: "\x1B[33m",
|
|
23
|
+
DIM: "\x1B[2m"
|
|
24
|
+
};
|
|
25
|
+
function getAllNetworkIps() {
|
|
26
|
+
const ifaces = os.networkInterfaces();
|
|
27
|
+
const ips = [];
|
|
28
|
+
for (const name in ifaces) {
|
|
29
|
+
if (/docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i.test(name)) continue;
|
|
30
|
+
for (const iface of ifaces[name] ?? []) {
|
|
31
|
+
if (iface.internal || iface.family !== "IPv4") continue;
|
|
32
|
+
ips.push(iface.address);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return [...new Set(ips)];
|
|
36
|
+
}
|
|
37
|
+
function detectEnvFiles() {
|
|
38
|
+
const nodeEnv = process.env.NODE_ENV ?? "production";
|
|
39
|
+
const candidates = [
|
|
40
|
+
".env.local",
|
|
41
|
+
`.env.${nodeEnv}.local`,
|
|
42
|
+
`.env.${nodeEnv}`,
|
|
43
|
+
".env"
|
|
44
|
+
];
|
|
45
|
+
return candidates.filter((f) => fs.existsSync(path.join(process.cwd(), f)));
|
|
46
|
+
}
|
|
47
|
+
function printBanner(port) {
|
|
48
|
+
const networkIps = getAllNetworkIps();
|
|
49
|
+
const envFiles = detectEnvFiles();
|
|
50
|
+
console.log(`
|
|
51
|
+
${C.CYAN}\xDF Bini.js${C.RESET} (production)
|
|
52
|
+
`);
|
|
53
|
+
if (envFiles.length > 0) {
|
|
54
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
|
|
55
|
+
}
|
|
56
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
|
|
57
|
+
for (const ip of networkIps) {
|
|
58
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${ip}:${port}/${C.RESET}`);
|
|
59
|
+
}
|
|
60
|
+
if (!fs.existsSync(API_DIR)) {
|
|
61
|
+
console.log(`
|
|
62
|
+
${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
|
|
63
|
+
}
|
|
64
|
+
console.log("");
|
|
65
|
+
}
|
|
66
|
+
async function isPortFree(port) {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
const server = net.createServer();
|
|
69
|
+
server.once("error", () => resolve(false));
|
|
70
|
+
server.once("listening", () => server.close(() => resolve(true)));
|
|
71
|
+
server.listen(port, "0.0.0.0");
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
async function findFreePort(start2) {
|
|
75
|
+
for (let port = start2; port < start2 + 100; port++) {
|
|
76
|
+
if (await isPortFree(port)) {
|
|
77
|
+
if (port !== start2) {
|
|
78
|
+
console.log(`
|
|
79
|
+
${C.YELLOW}\u26A0${C.RESET} Port ${start2} is in use, using port ${C.CYAN}${port}${C.RESET} instead.`);
|
|
80
|
+
}
|
|
81
|
+
return port;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`No free port found between ${start2} and ${start2 + 100}`);
|
|
85
|
+
}
|
|
86
|
+
function scanApiRoutes(dir, baseRoute = "") {
|
|
87
|
+
const routes = [];
|
|
88
|
+
if (!fs.existsSync(dir)) return routes;
|
|
89
|
+
let entries;
|
|
90
|
+
try {
|
|
91
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
92
|
+
} catch {
|
|
93
|
+
return routes;
|
|
94
|
+
}
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
|
|
97
|
+
const fullPath = path.join(dir, entry.name);
|
|
98
|
+
if (entry.isDirectory()) {
|
|
99
|
+
const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
|
|
100
|
+
const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
|
|
101
|
+
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
102
|
+
routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`));
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const ext = path.extname(entry.name);
|
|
106
|
+
const base = path.basename(entry.name, ext);
|
|
107
|
+
if (!API_EXTS.includes(ext)) continue;
|
|
108
|
+
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
109
|
+
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
110
|
+
const routePath = isCatchAll ? `${baseRoute}/*` : base === "index" ? baseRoute || "/" : isDynamic ? `${baseRoute}/:${base.slice(1, -1)}` : `${baseRoute}/${base}`;
|
|
111
|
+
routes.push({ routePath, filePath: fullPath });
|
|
112
|
+
}
|
|
113
|
+
return routes;
|
|
114
|
+
}
|
|
115
|
+
function matchRoute(pattern, pathname) {
|
|
116
|
+
const patParts = pattern.split("/").filter(Boolean);
|
|
117
|
+
const urlParts = pathname.split("/").filter(Boolean);
|
|
118
|
+
const isCatchAll = patParts[patParts.length - 1] === "*";
|
|
119
|
+
if (isCatchAll) {
|
|
120
|
+
const prefix = patParts.slice(0, -1);
|
|
121
|
+
if (urlParts.length < prefix.length) return null;
|
|
122
|
+
for (let i = 0; i < prefix.length; i++) {
|
|
123
|
+
if (prefix[i].startsWith(":")) continue;
|
|
124
|
+
if (prefix[i] !== urlParts[i]) return null;
|
|
125
|
+
}
|
|
126
|
+
return { "*": urlParts.slice(prefix.length).join("/") };
|
|
127
|
+
}
|
|
128
|
+
if (patParts.length !== urlParts.length) return null;
|
|
129
|
+
const params = {};
|
|
130
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
131
|
+
if (patParts[i].startsWith(":")) {
|
|
132
|
+
params[patParts[i].slice(1)] = decodeURIComponent(urlParts[i]);
|
|
133
|
+
} else if (patParts[i] !== urlParts[i]) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return params;
|
|
138
|
+
}
|
|
139
|
+
var moduleCache = /* @__PURE__ */ new Map();
|
|
140
|
+
async function importHandler(filePath) {
|
|
141
|
+
let mtime = 0;
|
|
142
|
+
try {
|
|
143
|
+
mtime = fs.statSync(filePath).mtimeMs;
|
|
144
|
+
} catch {
|
|
145
|
+
}
|
|
146
|
+
const cached = moduleCache.get(filePath);
|
|
147
|
+
if (cached && cached.mtime === mtime) return cached.handler;
|
|
148
|
+
const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
|
|
149
|
+
const handler = mod.default ?? null;
|
|
150
|
+
moduleCache.set(filePath, { mtime, handler });
|
|
151
|
+
return handler;
|
|
152
|
+
}
|
|
153
|
+
function readBody(req) {
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
const chunks = [];
|
|
156
|
+
let size = 0;
|
|
157
|
+
const timeout = setTimeout(() => {
|
|
158
|
+
req.destroy();
|
|
159
|
+
reject(new Error("Request body timeout"));
|
|
160
|
+
}, BODY_TIMEOUT);
|
|
161
|
+
req.on("data", (chunk) => {
|
|
162
|
+
size += chunk.byteLength;
|
|
163
|
+
if (size > BODY_SIZE_LIMIT) {
|
|
164
|
+
clearTimeout(timeout);
|
|
165
|
+
req.destroy();
|
|
166
|
+
reject(new Error("Request body too large"));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
chunks.push(chunk);
|
|
170
|
+
});
|
|
171
|
+
req.on("end", () => {
|
|
172
|
+
clearTimeout(timeout);
|
|
173
|
+
resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
|
|
174
|
+
});
|
|
175
|
+
req.on("error", (err) => {
|
|
176
|
+
clearTimeout(timeout);
|
|
177
|
+
reject(err);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
function normalizeHeaders(raw) {
|
|
182
|
+
return Object.fromEntries(
|
|
183
|
+
Object.entries(raw).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v])
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
var routeCache = null;
|
|
187
|
+
var CORS_HEADERS = {
|
|
188
|
+
"Access-Control-Allow-Origin": "*",
|
|
189
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
190
|
+
"Access-Control-Allow-Headers": "Content-Type,Authorization"
|
|
191
|
+
};
|
|
192
|
+
async function handleApiRequest(req, res, next) {
|
|
193
|
+
try {
|
|
194
|
+
if (req.method === "OPTIONS") {
|
|
195
|
+
res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
|
|
196
|
+
res.end();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!routeCache) {
|
|
200
|
+
routeCache = { routes: scanApiRoutes(API_DIR, "/api") };
|
|
201
|
+
}
|
|
202
|
+
const host = req.headers.host ?? "localhost";
|
|
203
|
+
const url = `http://${host}${req.url}`;
|
|
204
|
+
const pathname = new URL(url).pathname;
|
|
205
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
206
|
+
let body;
|
|
207
|
+
try {
|
|
208
|
+
body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
|
|
209
|
+
} catch (e) {
|
|
210
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
211
|
+
res.end(JSON.stringify({ error: e.message }));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const webReq = new Request(url, {
|
|
215
|
+
method,
|
|
216
|
+
headers: normalizeHeaders(req.headers),
|
|
217
|
+
body: body ?? null
|
|
218
|
+
});
|
|
219
|
+
for (const route of routeCache.routes) {
|
|
220
|
+
const handler = await importHandler(route.filePath);
|
|
221
|
+
if (!handler) continue;
|
|
222
|
+
let webRes;
|
|
223
|
+
try {
|
|
224
|
+
if (typeof handler.fetch === "function") {
|
|
225
|
+
const result = await Promise.race([
|
|
226
|
+
handler.fetch(webReq.clone()),
|
|
227
|
+
new Promise(
|
|
228
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
229
|
+
)
|
|
230
|
+
]);
|
|
231
|
+
webRes = result;
|
|
232
|
+
if (webRes.status === 404) continue;
|
|
233
|
+
} else if (typeof handler === "function") {
|
|
234
|
+
const params = matchRoute(route.routePath, pathname);
|
|
235
|
+
if (params === null) continue;
|
|
236
|
+
const reqWithParams = new Request(webReq.clone(), {
|
|
237
|
+
headers: {
|
|
238
|
+
...normalizeHeaders(req.headers),
|
|
239
|
+
"x-bini-params": JSON.stringify(params)
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
const result = await Promise.race([
|
|
243
|
+
handler(reqWithParams),
|
|
244
|
+
new Promise(
|
|
245
|
+
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
246
|
+
)
|
|
247
|
+
]);
|
|
248
|
+
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
249
|
+
status: 200,
|
|
250
|
+
headers: { "Content-Type": "application/json" }
|
|
251
|
+
});
|
|
252
|
+
} else {
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
} catch (e) {
|
|
256
|
+
res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
257
|
+
res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const finalHeaders = { ...CORS_HEADERS };
|
|
261
|
+
webRes.headers.forEach((v, k) => {
|
|
262
|
+
finalHeaders[k] = v;
|
|
263
|
+
});
|
|
264
|
+
res.writeHead(webRes.status, finalHeaders);
|
|
265
|
+
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
|
|
269
|
+
res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
|
|
270
|
+
} catch {
|
|
271
|
+
next();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
var MIME = {
|
|
275
|
+
".html": "text/html; charset=utf-8",
|
|
276
|
+
".js": "application/javascript",
|
|
277
|
+
".css": "text/css",
|
|
278
|
+
".json": "application/json",
|
|
279
|
+
".png": "image/png",
|
|
280
|
+
".jpg": "image/jpeg",
|
|
281
|
+
".jpeg": "image/jpeg",
|
|
282
|
+
".svg": "image/svg+xml",
|
|
283
|
+
".ico": "image/x-icon",
|
|
284
|
+
".webp": "image/webp",
|
|
285
|
+
".woff": "font/woff",
|
|
286
|
+
".woff2": "font/woff2",
|
|
287
|
+
".ttf": "font/ttf",
|
|
288
|
+
".eot": "application/vnd.ms-fontobject",
|
|
289
|
+
".txt": "text/plain",
|
|
290
|
+
".webmanifest": "application/manifest+json"
|
|
291
|
+
};
|
|
292
|
+
async function sendFile(filePath, res) {
|
|
293
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
294
|
+
const mimeType = MIME[ext] ?? "application/octet-stream";
|
|
295
|
+
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
296
|
+
let stat;
|
|
297
|
+
try {
|
|
298
|
+
stat = fs.statSync(filePath);
|
|
299
|
+
} catch {
|
|
300
|
+
res.writeHead(404);
|
|
301
|
+
res.end("Not found");
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
res.writeHead(200, {
|
|
305
|
+
"Content-Type": mimeType,
|
|
306
|
+
"Content-Length": stat.size,
|
|
307
|
+
"Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
|
|
308
|
+
"X-Powered-By": "Bini.js"
|
|
309
|
+
});
|
|
310
|
+
try {
|
|
311
|
+
await pipeline(createReadStream(filePath), res);
|
|
312
|
+
} catch {
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
async function serveStatic(req, res, next) {
|
|
316
|
+
const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
|
|
317
|
+
const filePath = path.join(DIST_DIR, pathname);
|
|
318
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
319
|
+
await sendFile(filePath, res);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
const indexPath = path.join(DIST_DIR, "index.html");
|
|
323
|
+
if (fs.existsSync(indexPath)) {
|
|
324
|
+
await sendFile(indexPath, res);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
next();
|
|
328
|
+
}
|
|
329
|
+
function compose(middlewares) {
|
|
330
|
+
return async (req, res) => {
|
|
331
|
+
let idx = 0;
|
|
332
|
+
async function next() {
|
|
333
|
+
if (idx >= middlewares.length) return;
|
|
334
|
+
const fn = middlewares[idx++];
|
|
335
|
+
await fn(req, res, next);
|
|
336
|
+
}
|
|
337
|
+
await next();
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
async function start() {
|
|
341
|
+
if (!fs.existsSync(DIST_DIR)) {
|
|
342
|
+
console.error(`
|
|
343
|
+
${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
|
|
344
|
+
`);
|
|
345
|
+
process.exit(1);
|
|
346
|
+
}
|
|
347
|
+
const port = await findFreePort(DEFAULT_PORT);
|
|
348
|
+
const handler = compose([
|
|
349
|
+
async (req, res, next) => {
|
|
350
|
+
if (!req.url?.startsWith("/api")) return next();
|
|
351
|
+
await handleApiRequest(req, res, next);
|
|
352
|
+
},
|
|
353
|
+
serveStatic,
|
|
354
|
+
(_req, res) => {
|
|
355
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
356
|
+
res.end("Not found");
|
|
357
|
+
}
|
|
358
|
+
]);
|
|
359
|
+
const server = http.createServer((req, res) => {
|
|
360
|
+
handler(req, res).catch(() => {
|
|
361
|
+
if (!res.headersSent) {
|
|
362
|
+
res.writeHead(500);
|
|
363
|
+
res.end("Internal Server Error");
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
});
|
|
367
|
+
server.listen(port, "0.0.0.0", () => {
|
|
368
|
+
printBanner(port);
|
|
369
|
+
});
|
|
370
|
+
function shutdown() {
|
|
371
|
+
server.close(() => process.exit(0));
|
|
372
|
+
setTimeout(() => process.exit(1), 1e4).unref();
|
|
373
|
+
}
|
|
374
|
+
process.on("SIGTERM", shutdown);
|
|
375
|
+
process.on("SIGINT", shutdown);
|
|
376
|
+
}
|
|
377
|
+
export {
|
|
378
|
+
start
|
|
379
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "bini-server",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency production server for bini-router apps",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"bini-server": "./dist/cli.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"bini",
|
|
23
|
+
"bini-router",
|
|
24
|
+
"server",
|
|
25
|
+
"spa",
|
|
26
|
+
"vite",
|
|
27
|
+
"hono",
|
|
28
|
+
"production",
|
|
29
|
+
"node"
|
|
30
|
+
],
|
|
31
|
+
"author": "Binidu Ranasinghe",
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"homepage": "https://bini.js.org",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/binidu/bini-server"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^25",
|
|
40
|
+
"tsup": "^8",
|
|
41
|
+
"typescript": "^5"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsup"
|
|
45
|
+
}
|
|
46
|
+
}
|