barejs 0.1.58 → 0.1.60
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 +85 -346
- package/dist/index.js +171 -161
- package/dist/node.js +362 -0
- package/dist/types/core/bare.d.ts +3 -7
- package/dist/types/core/ws-match.d.ts +15 -0
- package/dist/types/node.d.ts +1 -0
- package/dist/types/runtime/bun.d.ts +2 -0
- package/dist/types/runtime/index.d.ts +10 -0
- package/dist/types/runtime/node.d.ts +2 -0
- package/dist/types/runtime/types.d.ts +44 -0
- package/llms.txt +4 -4
- package/package.json +43 -7
- package/src/core/bare.ts +107 -76
- package/src/core/context.ts +3 -1
- package/src/core/loader.ts +5 -3
- package/src/core/ws-match.ts +60 -0
- package/src/node.ts +6 -0
- package/src/runtime/bun.ts +87 -0
- package/src/runtime/index.ts +24 -0
- package/src/runtime/node.ts +374 -0
- package/src/runtime/types.ts +49 -0
- package/src/security/hash.ts +3 -6
- package/src/utils/compress.ts +4 -3
- package/src/utils/static.ts +3 -2
package/README.md
CHANGED
|
@@ -1,415 +1,154 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<br />
|
|
3
3
|
<h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
|
|
4
|
-
<p><strong>The
|
|
5
|
-
<p><i>
|
|
4
|
+
<p><strong>The batteries-included web framework for Bun, Node.js, and Deno, engineered for minimal overhead.</strong></p>
|
|
5
|
+
<p><i>Built-in TypeBox & Zod validation, end-to-end RPC client inference, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and zero-trust security — powered by a JIT-compiled O(1) radix router and LIFO context pooling.</i></p>
|
|
6
6
|
|
|
7
7
|
<p>
|
|
8
|
-
<a href="https://www.npmjs.com/package/barejs">
|
|
9
|
-
<img src="https://img.shields.io/
|
|
10
|
-
|
|
11
|
-
<a href="https://
|
|
12
|
-
<img src="https://img.shields.io/
|
|
13
|
-
|
|
14
|
-
<a href="https://bun.sh">
|
|
15
|
-
<img src="https://img.shields.io/badge/Bun-%3E%3D1.1.0-black?style=for-the-badge&logo=bun" alt="Bun Version">
|
|
16
|
-
</a>
|
|
17
|
-
<a href="https://github.com/xarhang/barejs/blob/main/LICENSE">
|
|
18
|
-
<img src="https://img.shields.io/github/license/xarhang/barejs?style=for-the-badge&color=blue" alt="License">
|
|
19
|
-
</a>
|
|
8
|
+
<a href="https://www.npmjs.com/package/barejs"><img src="https://img.shields.io/npm/v/barejs?style=for-the-badge&logo=npm&color=CB3837" alt="NPM Version"></a>
|
|
9
|
+
<a href="https://github.com/xarhang/bareJS/actions/workflows/bench.yml"><img src="https://img.shields.io/github/actions/workflow/status/xarhang/bareJS/bench.yml?branch=main&label=CI%20%26%20Bench&style=for-the-badge&logo=github" alt="CI & Benchmarks"></a>
|
|
10
|
+
<a href="https://bun.sh"><img src="https://img.shields.io/badge/Bun-%3E%3D1.1.0-black?style=for-the-badge&logo=bun" alt="Bun"></a>
|
|
11
|
+
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node.js-%3E%3D20.0.0-339933?style=for-the-badge&logo=nodedotjs" alt="Node.js"></a>
|
|
12
|
+
<a href="https://deno.com"><img src="https://img.shields.io/badge/Deno-%3E%3D2.0-000000?style=for-the-badge&logo=deno" alt="Deno"></a>
|
|
13
|
+
<a href="https://github.com/xarhang/bareJS/blob/main/LICENSE"><img src="https://img.shields.io/github/license/xarhang/bareJS?style=for-the-badge&color=blue" alt="License"></a>
|
|
20
14
|
</p>
|
|
21
15
|
</div>
|
|
22
16
|
|
|
23
17
|
---
|
|
24
18
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
All benchmark numbers below are **automatically generated on every push to `main`** by GitHub Actions running `benchmarks/fair-suite.ts`, `benchmarks/production-bench.ts`, and `benchmarks/head-to-head.ts` on real `mitata` runs.
|
|
28
|
-
|
|
29
|
-
<!-- MARKER: MULTI_BENCH_START -->
|
|
30
|
-
|
|
31
|
-
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
32
|
-
| :--- | :---: | :---: | :---: |
|
|
33
|
-
| **1. 100 Routes + Dynamic Params** | **`1.34 µs`**<br><sub>`p99: 8.14 µs`</sub> | `1.81 µs`<br><sub>`p99: 8.57 µs`</sub> | `3.63 µs`<br><sub>`p99: 13.85 µs`</sub> |
|
|
34
|
-
| **2. 10 Middlewares + Deep Path** | **`1.34 µs`**<br><sub>`p99: 7.45 µs`</sub> | `1.88 µs`<br><sub>`p99: 8.95 µs`</sub> | `3.91 µs`<br><sub>`p99: 14.28 µs`</sub> |
|
|
35
|
-
| **3. POST JSON + Schema Validation** | `3.94 µs`<br><sub>`p99: 14.14 µs`</sub> | `4.87 µs`<br><sub>`p99: 16.20 µs`</sub> | **`3.17 µs`**<br><sub>`p99: 3.54 µs`</sub> |
|
|
36
|
-
| **4. Async Handler + Query Parsing** | `2.02 µs`<br><sub>`p99: 9.35 µs`</sub> | `2.26 µs`<br><sub>`p99: 9.39 µs`</sub> | **`1.99 µs`**<br><sub>`p99: 2.48 µs`</sub> |
|
|
37
|
-
| **5. Response Schema Secret Stripping** | **`1.08 µs`**<br><sub>`p99: 6.49 µs`</sub> | `1.57 µs`<br><sub>`p99: 7.03 µs`</sub> | — |
|
|
38
|
-
| **6. SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | `22.36 µs`<br><sub>`p99: 45.38 µs`</sub> | **`22.00 µs`**<br><sub>`p99: 41.81 µs`</sub> | `27.79 µs`<br><sub>`p99: 52.80 µs`</sub> |
|
|
39
|
-
| **7. SQLite Write (`POST` + Validate + `INSERT`)** | `13.46 µs`<br><sub>`p99: 33.35 µs`</sub> | `18.33 µs`<br><sub>`p99: 47.89 µs`</sub> | **`12.79 µs`**<br><sub>`p99: 13.04 µs`</sub> |
|
|
40
|
-
|
|
41
|
-
> Last Updated: 2026-11-24 (github action)
|
|
42
|
-
|
|
43
|
-
<!-- MARKER: MULTI_BENCH_END -->
|
|
44
|
-
|
|
45
|
-
### Head-to-Head Stress Test (10 Middlewares + Deep Path)
|
|
46
|
-
|
|
47
|
-
<!-- MARKER: PERFORMANCE_TABLE_START -->
|
|
48
|
-
|
|
49
|
-
| Framework | Latency | Speed |
|
|
50
|
-
| :--- | :--- | :--- |
|
|
51
|
-
| **BareJS** | **1.46 µs** | **Baseline** |
|
|
52
|
-
| Elysia | 1.63 µs | 1.11x slower |
|
|
53
|
-
| Hono | 5.41 µs | 3.70x slower |
|
|
19
|
+
```typescript
|
|
20
|
+
import { BareJS, Type, type Context } from 'barejs';
|
|
54
21
|
|
|
55
|
-
|
|
22
|
+
const app = new BareJS();
|
|
56
23
|
|
|
57
|
-
|
|
24
|
+
app.get('/', () => ({ hello: 'world' }));
|
|
58
25
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
26
|
+
app.post('/orders/:id', {
|
|
27
|
+
params: Type.Object({ id: Type.Integer() }),
|
|
28
|
+
body: Type.Object({ item: Type.String({ minLength: 1 }), qty: Type.Integer({ minimum: 1 }) }),
|
|
29
|
+
response: Type.Object({ id: Type.Number(), item: Type.String(), qty: Type.Number() })
|
|
30
|
+
}, (ctx: Context) => ({ id: ctx.params.id, ...ctx.body, internal_cost: 9999 })); // internal_cost is stripped
|
|
63
31
|
|
|
64
|
-
|
|
65
|
-
|
|
32
|
+
app.listen(3000);
|
|
33
|
+
```
|
|
66
34
|
|
|
67
35
|
---
|
|
68
36
|
|
|
69
|
-
##
|
|
37
|
+
## Why BareJS?
|
|
70
38
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
* **Concurrency-Safe Object Pooling & Dev UAF Guard**: Recycles `Context` instances through a lazy bounded LIFO stack (`0..65536`) with acquired slot clearing (`pool[slot] = undefined` while in-flight), shared pool-state synchronization across JIT recompilations, and complete framework-managed state cleanup on release. Timed-out contexts are detached and retired from the pool, and in development mode (`NODE_ENV=development` or unset) a zero-prod-overhead Proxy guard warns if a released `ctx` is accessed after response completion.
|
|
78
|
-
* **Dual Response Ergonomics & Full HTTP Methods**: Return plain objects/strings directly (Elysia style) OR use `ctx.json()`, `ctx.html()`, `ctx.text()`, `ctx.redirect()`, `ctx.send()`, with `get`, `post`, `put`, `patch`, `delete`, `options`, `head`, and `all`.
|
|
79
|
-
* **Unified Schema Validation & Auto-Coercion**: Validate `body`, `query`, `params`, `headers`, `response`, and `maxBodySize` (`413` DoS guard) in one object with **TypeBox**, **Zod**, or **Native JSON Schema**—with automatic `number`/`boolean` coercion on `query` and `params`.
|
|
80
|
-
* **Batteries-Included Zero-Trust Security Suite**: Built-in `securityHeaders()`, `cors()`, `csrf()`, `timeout()`, `rateLimit()`, `trustProxy(false)` anti-spoofing, `maxRequestBodySize` server cap, `bareAuth()` (constant-time HS256 JWT + `revokeToken()` / `isRevoked`), `Hash` (Argon2id), HMAC-signed cookies, `ctx.upload()` / streaming `ctx.uploadStream()`, and symlink-safe `staticFile()`.
|
|
81
|
-
* **Observability, Graceful Drain, Real-Time, RPC & OpenAPI 3.1**: Built-in `logger()` (`pretty`/`json` + `X-Request-Id`), `healthcheck()` (`/health` + `/ready`), `app.onDrain()` + IPC `DRAIN_REQUEST` graceful draining, parameterized WebSockets (`app.ws('/ws/:room')`), SSE (`ctx.sse`), JSON-RPC 2.0 (`app.rpc`), and OpenAPI 3.1 (`app.docs`) with `securitySchemes`, `servers`, and `tags`.
|
|
39
|
+
- **O(1) JIT Router & Pooling:** Compiles static routes into an inline `switch` fast-path and dynamic routes into a radix jump-table with a lazy LIFO `Context` pool (`0..65536`) and dev-mode Use-After-Free Proxy guard.
|
|
40
|
+
- **Unified Schema Validation:** Declarative `body`, `query`, `params`, `headers`, and `response` schemas with **TypeBox**, **Zod**, or **Native JSON Schema** — including auto-coercion, `413` `maxBodySize` guards, and automatic secret-field stripping.
|
|
41
|
+
- **End-to-End Type Safety:** `bareClient(app)` provides compile-time route, param, query, body, and response inference over HTTP or zero-network in-memory calls.
|
|
42
|
+
- **Batteries Included:** Auto-generated **OpenAPI 3.1** + Scalar UI (`app.docs`), **JSON-RPC 2.0** (`app.rpc`), **WebSockets** (`app.ws`), **SSE** (`ctx.sse`), **Compression** (`compress`), and **Static Files** (`staticFile`).
|
|
43
|
+
- **Zero-Trust Security & Resilience:** Built-in `bareAuth` (HS256/RS256/ES256/JWKS), `Hash` (Argon2id/bcrypt), HMAC-signed cookies, `cors`, `csrf`, `rateLimit`, `idempotency`, `circuitBreaker`, `createSingleflight`, and `app.onDrain`.
|
|
44
|
+
- **Multi-Runtime:** Startup driver selection (`bunDriver` / `nodeDriver`) keeps Bun native performance untouched while running the same app on Node.js (`>=20`) and Deno (`>=2.0`).
|
|
82
45
|
|
|
83
46
|
---
|
|
84
47
|
|
|
85
|
-
##
|
|
48
|
+
## Installation & Quick Start
|
|
49
|
+
|
|
50
|
+
<details open>
|
|
51
|
+
<summary><strong>Bun (>= 1.1.0)</strong></summary>
|
|
86
52
|
|
|
87
53
|
```bash
|
|
88
54
|
bun add barejs
|
|
89
55
|
```
|
|
90
56
|
|
|
91
57
|
```typescript
|
|
92
|
-
import { BareJS
|
|
58
|
+
import { BareJS } from 'barejs';
|
|
93
59
|
|
|
94
60
|
const app = new BareJS();
|
|
95
|
-
|
|
96
|
-
// 1. Direct return (Elysia style)
|
|
97
|
-
app.get('/', () => ({ hello: 'world' }));
|
|
98
|
-
app.get('/ping', () => 'pong');
|
|
99
|
-
|
|
100
|
-
// 2. Context helpers (Hono / Express style)
|
|
101
|
-
app.get('/welcome', (ctx: Context) => ctx.html('<h1>ສະບາຍດີ BareJS</h1>'));
|
|
102
|
-
app.get('/old', (ctx: Context) => ctx.redirect('/', 301));
|
|
103
|
-
|
|
104
|
-
// 3. Wildcard catch-all route
|
|
105
|
-
app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
|
|
106
|
-
|
|
61
|
+
app.get('/', () => ({ runtime: 'bun' }));
|
|
107
62
|
app.listen(3000);
|
|
108
63
|
```
|
|
109
64
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
## 📘 Comprehensive Guide
|
|
65
|
+
</details>
|
|
113
66
|
|
|
114
|
-
|
|
67
|
+
<details>
|
|
68
|
+
<summary><strong>Node.js (>= 20.0.0)</strong></summary>
|
|
115
69
|
|
|
116
|
-
|
|
70
|
+
```bash
|
|
71
|
+
npm install barejs
|
|
72
|
+
# Optional peer dependencies if using WebSockets or password hashing:
|
|
73
|
+
npm install ws @node-rs/argon2
|
|
74
|
+
```
|
|
117
75
|
|
|
118
76
|
```typescript
|
|
119
|
-
import { BareJS
|
|
77
|
+
import { BareJS } from 'barejs/node';
|
|
120
78
|
|
|
121
79
|
const app = new BareJS();
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
app.post('/orders/:orderId', {
|
|
125
|
-
detail: { summary: 'Create Order', tags: ['Orders'] },
|
|
126
|
-
params: Type.Object({ orderId: Type.Integer() }), // "42" -> 42
|
|
127
|
-
query: Type.Object({ notify: Type.Optional(Type.Boolean()) }), // "true" -> true
|
|
128
|
-
headers: Type.Object({ 'x-api-version': Type.Optional(Type.String()) }),
|
|
129
|
-
body: Type.Object({
|
|
130
|
-
item: Type.String({ minLength: 1 }),
|
|
131
|
-
qty: Type.Integer({ minimum: 1 })
|
|
132
|
-
}),
|
|
133
|
-
// Response schema automatically strips undeclared secret fields (e.g. internal_cost)!
|
|
134
|
-
response: Type.Object({
|
|
135
|
-
orderId: Type.Number(),
|
|
136
|
-
notify: Type.Optional(Type.Boolean()),
|
|
137
|
-
body: Type.Object({ item: Type.String(), qty: Type.Number() })
|
|
138
|
-
}),
|
|
139
|
-
maxBodySize: 512 * 1024 // 512 KB limit (returns 413 if exceeded)
|
|
140
|
-
}, (ctx: Context) => ({
|
|
141
|
-
orderId: ctx.params.orderId, // number
|
|
142
|
-
notify: ctx.query.notify, // boolean | undefined
|
|
143
|
-
body: ctx.body, // validated body
|
|
144
|
-
internal_cost: 9999 // automatically stripped before sending to client!
|
|
145
|
-
}));
|
|
146
|
-
|
|
147
|
-
// Standalone middleware validators are also supported:
|
|
148
|
-
app.post('/zod', Z.object({ email: Z.string().email() }), (ctx) => ctx.body);
|
|
149
|
-
app.post('/native', native({
|
|
150
|
-
properties: { title: { type: 'string' }, priority: { type: 'number' } },
|
|
151
|
-
required: ['title'] // 'priority' is optional
|
|
152
|
-
}), (ctx) => ctx.body);
|
|
80
|
+
app.get('/', () => ({ runtime: 'node' }));
|
|
81
|
+
app.listen(3000);
|
|
153
82
|
```
|
|
154
83
|
|
|
155
|
-
|
|
84
|
+
</details>
|
|
156
85
|
|
|
157
|
-
|
|
86
|
+
<details>
|
|
87
|
+
<summary><strong>Deno (>= 2.0)</strong></summary>
|
|
158
88
|
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
app.post('/session', async (ctx) => {
|
|
162
|
-
await ctx.setCookie('session_id', 'user_42', {
|
|
163
|
-
secret: process.env.COOKIE_SECRET!,
|
|
164
|
-
httpOnly: true,
|
|
165
|
-
secure: true,
|
|
166
|
-
sameSite: 'Strict',
|
|
167
|
-
maxAge: 3600
|
|
168
|
-
});
|
|
169
|
-
return { loggedIn: true };
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
app.get('/session', async (ctx) => {
|
|
173
|
-
const userId = await ctx.getSignedCookie('session_id', process.env.COOKIE_SECRET!);
|
|
174
|
-
if (!userId) return ctx.status(401).json({ error: 'Invalid or tampered cookie' });
|
|
175
|
-
return { userId };
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
// Safe Multipart File Upload (enforces size, file count, MIME allowlist & filename sanitization)
|
|
179
|
-
app.post('/upload', async (ctx) => {
|
|
180
|
-
const { fields, files } = await ctx.upload({
|
|
181
|
-
maxFileSize: 5 * 1024 * 1024, // 5 MB -> 413 if exceeded
|
|
182
|
-
maxFiles: 3, // -> 413 if exceeded
|
|
183
|
-
allowedTypes: ['image/png', 'image/jpeg', 'application/pdf'] // -> 415 if unsupported
|
|
184
|
-
});
|
|
185
|
-
return {
|
|
186
|
-
fields,
|
|
187
|
-
uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type }))
|
|
188
|
-
};
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
// True Streaming Multipart Upload (constant O(chunk) memory for large files)
|
|
192
|
-
app.post('/upload-stream', async (ctx) => {
|
|
193
|
-
const uploaded: string[] = [];
|
|
194
|
-
for await (const part of ctx.uploadStream({ maxFileSize: 500 * 1024 * 1024 })) {
|
|
195
|
-
if (part.type === 'file' && part.stream) {
|
|
196
|
-
await Bun.write(`./uploads/${part.safeName}`, new Response(part.stream));
|
|
197
|
-
uploaded.push(part.safeName!);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
return { uploaded };
|
|
201
|
-
});
|
|
89
|
+
```bash
|
|
90
|
+
deno add npm:barejs
|
|
202
91
|
```
|
|
203
92
|
|
|
204
|
-
---
|
|
205
|
-
|
|
206
|
-
### 3. 🛡️ Production Security Suite, Idempotency & Singleflight
|
|
207
|
-
|
|
208
93
|
```typescript
|
|
209
|
-
import {
|
|
210
|
-
BareJS, BareRouter, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
211
|
-
idempotency, createSingleflight, redisStore, compress,
|
|
212
|
-
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
213
|
-
} from 'barejs';
|
|
94
|
+
import { BareJS } from 'barejs';
|
|
214
95
|
|
|
215
96
|
const app = new BareJS();
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
app.use(securityHeaders());
|
|
220
|
-
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
221
|
-
app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
|
|
222
|
-
app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s
|
|
223
|
-
app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip
|
|
224
|
-
app.use(rateLimit({ windowMs: 60_000, max: 100, store }));
|
|
225
|
-
app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
|
|
226
|
-
|
|
227
|
-
// Payment/Order Double-Charge Protection (Idempotency-Key header)
|
|
228
|
-
// - Returns 409 Conflict if duplicate request is currently in-flight
|
|
229
|
-
// - Replays cached response with X-Idempotent-Replayed: true on retry
|
|
230
|
-
app.post('/payments', idempotency({ ttlMs: 86_400_000, store }), async (ctx) => {
|
|
231
|
-
const body = await ctx.jsonBody();
|
|
232
|
-
return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
// Cache-Stampede / Thundering-Herd Request Coalescing
|
|
236
|
-
const singleflight = createSingleflight();
|
|
237
|
-
app.get('/reports/daily', async () => {
|
|
238
|
-
// 100 concurrent requests coalesce into a SINGLE database query execution
|
|
239
|
-
return singleflight.do('daily-report', async () => ({ revenue: 125_000, generatedAt: Date.now() }));
|
|
240
|
-
});
|
|
241
|
-
|
|
242
|
-
// Argon2id Password Hashing & JWT Creation
|
|
243
|
-
app.post('/login', async (ctx) => {
|
|
244
|
-
const { password } = await ctx.jsonBody();
|
|
245
|
-
const hash = await Hash.make(password);
|
|
246
|
-
const valid = await Hash.verify(password, hash);
|
|
247
|
-
if (!valid) return ctx.status(401).send('Invalid credentials');
|
|
248
|
-
|
|
249
|
-
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET);
|
|
250
|
-
return { token };
|
|
251
|
-
});
|
|
252
|
-
|
|
253
|
-
// Protect routes with constant-time HS256 JWT or asymmetric RS256/ES256/JWKS (`ctx.user`)
|
|
254
|
-
app.get('/admin', bareAuth({ secret: SECRET, revocationStore: store }), hasRole('admin'), (ctx) => ({
|
|
255
|
-
user: ctx.user,
|
|
256
|
-
requestId: ctx.requestId
|
|
257
|
-
}));
|
|
258
|
-
app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user);
|
|
97
|
+
app.get('/', () => ({ runtime: 'deno' }));
|
|
98
|
+
Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));
|
|
259
99
|
```
|
|
260
100
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
### 4. 🧩 Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks
|
|
264
|
-
|
|
265
|
-
```typescript
|
|
266
|
-
// Enrich ctx with full TypeScript inference (auto-cleaned on pool release)
|
|
267
|
-
const appWithContext = app.derive((ctx) => ({
|
|
268
|
-
requestTime: Date.now(),
|
|
269
|
-
traceId: ctx.requestId
|
|
270
|
-
}));
|
|
271
|
-
|
|
272
|
-
appWithContext.get('/trace', (ctx) => ({
|
|
273
|
-
traceId: ctx.traceId, // typed as string
|
|
274
|
-
requestTime: ctx.requestTime // typed as number
|
|
275
|
-
}));
|
|
276
|
-
|
|
277
|
-
// Register a modular plugin
|
|
278
|
-
app.use({
|
|
279
|
-
name: 'health-plugin',
|
|
280
|
-
install(instance) {
|
|
281
|
-
instance.get('/healthz', (ctx: any) => ({ ok: true, traceId: ctx.traceId }));
|
|
282
|
-
}
|
|
283
|
-
});
|
|
284
|
-
|
|
285
|
-
// Server Lifecycle & Error Masking
|
|
286
|
-
app.onStart(() => console.log('Database ready'));
|
|
287
|
-
app.onDrain(async () => console.log('Draining in-flight requests...')); // Triggered on app.drain() or IPC DRAIN_REQUEST
|
|
288
|
-
app.onStop(async () => console.log('Cleaned up resources'));
|
|
289
|
-
app.onError((err, ctx) => ctx.status(err.status || 500).json({
|
|
290
|
-
status: 'error',
|
|
291
|
-
message: err.message,
|
|
292
|
-
requestId: ctx.requestId
|
|
293
|
-
}));
|
|
294
|
-
```
|
|
101
|
+
</details>
|
|
295
102
|
|
|
296
103
|
---
|
|
297
104
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
```typescript
|
|
301
|
-
import { BareJS, BareRouter, bareClient, Type } from 'barejs';
|
|
105
|
+
## Runtime Support
|
|
302
106
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
107
|
+
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) |
|
|
108
|
+
| :--- | :---: | :---: | :---: |
|
|
109
|
+
| **Router, Validation, OpenAPI, JSON-RPC, `bareClient`** | ✅ | ✅ | ✅ |
|
|
110
|
+
| **Security Middlewares (`cors`, `csrf`, `rateLimit`, `bareAuth`, `idempotency`)** | ✅ | ✅ | ✅ |
|
|
111
|
+
| **Streaming (`ctx.sse`, `ctx.upload`, `ctx.uploadStream`)** | ✅ | ✅ | ✅ |
|
|
112
|
+
| **Static Files (`staticFile`)** | ✅ | ✅ | ✅ |
|
|
113
|
+
| **Compression (`compress` — `gzip` / `br` / `zstd`)** | ✅ | ✅ (`gzip` / `br`) | ✅ (`gzip` / `br`) |
|
|
114
|
+
| **WebSockets (`app.ws`)** | ✅ Native | ⚠️ Requires `ws` | ✅ Native (`Deno.upgradeWebSocket`) |
|
|
115
|
+
| **Password Hashing (`Hash`)** | ✅ Native (`Argon2id` / `bcrypt`) | ✅ Native (`scrypt`) · Optional `Argon2id` | ✅ Native (`scrypt`) · Optional `Argon2id` |
|
|
307
116
|
|
|
308
|
-
|
|
117
|
+
---
|
|
309
118
|
|
|
310
|
-
|
|
311
|
-
app.ws('/ws/chat', {
|
|
312
|
-
open: (ws) => ws.send('connected'),
|
|
313
|
-
message: (ws, msg) => ws.send(`echo: ${msg}`)
|
|
314
|
-
});
|
|
119
|
+
## Benchmarks (Bun)
|
|
315
120
|
|
|
316
|
-
|
|
317
|
-
app.get('/events', (ctx) => ctx.sse(async (send) => {
|
|
318
|
-
send({ step: 1, msg: 'streaming...' }, 'progress', '1');
|
|
319
|
-
}));
|
|
121
|
+
Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitata) (`benchmarks/fair-suite.ts`). Bold values indicate the fastest **mean** latency. These micro-benchmarks measure framework overhead rather than end-to-end network HTTP throughput, and do not represent Node.js or Deno latency.
|
|
320
122
|
|
|
321
|
-
|
|
322
|
-
app.rpc('/rpc', {
|
|
323
|
-
add: ({ a, b }: { a: number; b: number }) => a + b
|
|
324
|
-
});
|
|
123
|
+
<!-- MARKER: MULTI_BENCH_SUMMARY_START -->
|
|
325
124
|
|
|
326
|
-
|
|
327
|
-
|
|
125
|
+
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
126
|
+
| :--- | :---: | :---: | :---: |
|
|
127
|
+
| **1. 100 Routes + Dynamic Params** | **`1.71 µs`**<br><sub>`p99: 10.38 µs`</sub> | `2.08 µs`<br><sub>`p99: 10.00 µs`</sub> | `4.57 µs`<br><sub>`p99: 18.29 µs`</sub> |
|
|
128
|
+
| **2. 10 Middlewares + Deep Path** | **`1.68 µs`**<br><sub>`p99: 8.94 µs`</sub> | `2.42 µs`<br><sub>`p99: 11.72 µs`</sub> | `4.61 µs`<br><sub>`p99: 19.55 µs`</sub> |
|
|
129
|
+
| **3. POST JSON + Schema Validation** | **`5.39 µs`**<br><sub>`p99: 20.60 µs`</sub> | `5.76 µs`<br><sub>`p99: 18.14 µs`</sub> | `5.65 µs`<br><sub>`p99: 20.73 µs`</sub> |
|
|
130
|
+
| **4. Async Handler + Query Parsing** | **`2.56 µs`**<br><sub>`p99: 11.55 µs`</sub> | `2.75 µs`<br><sub>`p99: 12.13 µs`</sub> | `3.63 µs`<br><sub>`p99: 13.92 µs`</sub> |
|
|
328
131
|
|
|
329
|
-
|
|
330
|
-
const res = await app.request('/api/users/42?full=true');
|
|
132
|
+
> Last Updated: 2026-11-24 (github action — `linux`, AMD EPYC 7763 64-Core Processor, Bun `1.4.5`, Elysia `1.4.21`, Hono `4.11.4`)
|
|
331
133
|
|
|
332
|
-
|
|
333
|
-
const inMemoryClient = bareClient(app);
|
|
334
|
-
const localRes = await inMemoryClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
134
|
+
<!-- MARKER: MULTI_BENCH_SUMMARY_END -->
|
|
335
135
|
|
|
336
|
-
|
|
337
|
-
const remoteRes = await httpClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
338
|
-
```
|
|
136
|
+
See **[BENCHMARKS.md](./BENCHMARKS.md)** for all 7 scenarios (including SQLite read/write and response secret stripping), methodology, notes, and local reproduction steps, or view the [Continuous Benchmark Dashboard](https://xarhang.github.io/bareJS/dev/benchmarks/).
|
|
339
137
|
|
|
340
138
|
---
|
|
341
139
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
```typescript
|
|
345
|
-
import { BareJS, logger, healthcheck, bareAuth, revokeToken } from 'barejs';
|
|
346
|
-
|
|
347
|
-
const app = new BareJS()
|
|
348
|
-
.trustProxy(false) // Ignore spoofed X-Forwarded-For when directly exposed
|
|
349
|
-
.use(logger({ format: 'json' })) // Structured JSON logs + X-Request-Id
|
|
350
|
-
.use(healthcheck({
|
|
351
|
-
path: '/health',
|
|
352
|
-
readyPath: '/ready',
|
|
353
|
-
version: '1.0.0',
|
|
354
|
-
checks: { db: async () => true }
|
|
355
|
-
}))
|
|
356
|
-
.use(bareAuth({
|
|
357
|
-
secret: process.env.JWT_SECRET!,
|
|
358
|
-
isRevoked: async (payload) => isBlockedInRedis(payload.jti)
|
|
359
|
-
}));
|
|
360
|
-
|
|
361
|
-
// Revoke a compromised token or jti immediately
|
|
362
|
-
revokeToken('compromised-jti-123', 3600_000);
|
|
363
|
-
|
|
364
|
-
// OpenAPI 3.1 with Bearer JWT securitySchemes
|
|
365
|
-
app.docs('/docs', {
|
|
366
|
-
title: 'Production API',
|
|
367
|
-
securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
|
|
368
|
-
security: [{ bearerAuth: [] }]
|
|
369
|
-
});
|
|
370
|
-
|
|
371
|
-
// Enforce server-level maxRequestBodySize (default: 10MB)
|
|
372
|
-
app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
|
|
373
|
-
```
|
|
374
|
-
|
|
375
|
-
---
|
|
140
|
+
## Documentation
|
|
376
141
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
| `ctx.params` | Route parameters (`:id` or `ctx.params['*']` for wildcard routes). |
|
|
383
|
-
| `ctx.query` / `ctx.getQuery(k)` | Lazy, prototype-pollution-safe parsed query parameters. |
|
|
384
|
-
| `await ctx.jsonBody(maxBytes?)` | Parses & caches JSON body (enforces `413` limit, default 1MB). |
|
|
385
|
-
| `await ctx.upload(options?)` | Safe `multipart/form-data` upload parser (`maxFileSize`, `maxFiles`, `allowedTypes`). |
|
|
386
|
-
| `ctx.uploadStream(options?)` | True streaming `multipart/form-data` async generator (`ReadableStream` per file part, $O(\text{chunk})$ memory). |
|
|
387
|
-
| `ctx.cookies` | Lazy parsed request cookies (`Record<string, string>`). |
|
|
388
|
-
| `await ctx.setCookie(k, v, opts?)` | Sets a cookie (`HttpOnly; SameSite=Lax` default, optional HMAC `secret`). |
|
|
389
|
-
| `await ctx.getSignedCookie(k, s)` | Verifies HMAC-SHA256 signed cookie in constant time. |
|
|
390
|
-
| `ctx.deleteCookie(k, opts?)` | Expires a cookie immediately. |
|
|
391
|
-
| `ctx.user` | Authenticated user payload from `bareAuth` or `basicAuth`. |
|
|
392
|
-
| `ctx.requestId` | Incoming `x-request-id` header or generated UUIDv4. |
|
|
393
|
-
| `ctx.status(code)` | Sets HTTP response status code (chainable). |
|
|
394
|
-
| `ctx.setHeader(name, value)` | Sets response header (chainable, copy-on-write safe). |
|
|
395
|
-
| `ctx.json(data)` | Returns `application/json` response. |
|
|
396
|
-
| `ctx.send(msg, extra?)` | Returns standardized `{ status, msg, ...extra }` JSON response. |
|
|
397
|
-
| `ctx.html(html, status?)` | Returns `text/html; charset=utf-8` response. |
|
|
398
|
-
| `ctx.text(text, status?)` | Returns `text/plain; charset=utf-8` response. |
|
|
399
|
-
| `ctx.redirect(url, status?)` | Returns HTTP redirect response (default `302`). |
|
|
400
|
-
| `ctx.sse(source)` | Streams Server-Sent Events (`text/event-stream`). |
|
|
401
|
-
| `ctx.set(k, v)` / `ctx.get(k)` | Per-request key-value storage (cleared on pool release). |
|
|
142
|
+
- **[Comprehensive Guide](./docs/guide.md)** — Validation & auto-coercion, cookies & uploads, security suite, `app.derive()`, WebSockets, SSE, JSON-RPC 2.0, OpenAPI 3.1, and `bareClient`.
|
|
143
|
+
- **[API & Configuration Reference](./docs/reference.md)** — Complete `Context` (`ctx`) API table, `poolSize`, `bare.config.ts`, and `NODE_ENV` settings.
|
|
144
|
+
- **[Benchmarks](./BENCHMARKS.md)** — Full 7-scenario results and reproduction instructions.
|
|
145
|
+
- **[Changelog](./CHANGELOG.md)** — Release history and migration notes.
|
|
146
|
+
- **[`llms.txt`](./llms.txt)** — Token-efficient API reference for AI coding assistants (Cursor, Copilot, Claude, Windsurf).
|
|
402
147
|
|
|
403
148
|
---
|
|
404
149
|
|
|
405
|
-
##
|
|
406
|
-
|
|
407
|
-
| Variable / File | Default | Description |
|
|
408
|
-
| :--- | :--- | :--- |
|
|
409
|
-
| `bare.config.ts` | Optional | Centralized config for `port` and Argon2/bcrypt `hash` parameters. |
|
|
410
|
-
| `poolSize` | `1024` | `new BareJS(poolSize)` — defines the maximum number of released `Context` instances retained in the lazy bounded LIFO stack (`0..65536`; `0` disables retention). Push and pop operations are $O(1)$ with acquired slots cleared while in-flight and shared pool state across JIT recompilations. |
|
|
411
|
-
| `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces and disable startup banner. |
|
|
412
|
-
|
|
413
|
-
---
|
|
150
|
+
## Status, Contributing & License
|
|
414
151
|
|
|
415
|
-
**
|
|
152
|
+
- **Status:** Active `0.1.x` development. Core HTTP routing, validation, security middlewares, and Bun runtime APIs are stable and verified in CI (`bun test`); the Node.js and Deno runtime drivers (`barejs/node`) are newly introduced in `v0.1.59`.
|
|
153
|
+
- **Contributing:** See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and release workflows.
|
|
154
|
+
- **License:** [MIT](./LICENSE) — Maintained by [xarhang](https://github.com/xarhang).
|