barejs 0.1.59 → 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 -361
- package/dist/index.js +98 -98
- package/dist/node.js +98 -98
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/src/core/bare.ts +31 -2
- package/src/runtime/node.ts +44 -3
package/README.md
CHANGED
|
@@ -1,430 +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 batteries-included
|
|
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
|
-
> [!TIP]
|
|
24
|
-
> **Using AI Coding Assistants (Cursor, Copilot, Claude, Windsurf)?** Point them to [`llms.txt`](./llms.txt) for a complete, token-efficient reference of every BareJS API.
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
## 🚀 Batteries Included, Zero Overhead
|
|
29
|
-
|
|
30
|
-
* **Core Performance**: $O(1)$ Radix Jump-Table Router (inline `switch` dispatch for static, `:params`, and `/*` wildcards), JIT-compiled route/middleware pipelines (`AsyncFunction` fast paths), and concurrency-safe lazy LIFO `Context` object pooling (`0..65536`) with dev-mode Use-After-Free Proxy guard.
|
|
31
|
-
* **Type Safety & Validation**: Unified declarative schema validation for `body`, `query`, `params`, `headers`, and `response` with **TypeBox**, **Zod**, or **Native JSON Schema**—featuring automatic `number`/`boolean` coercion, `maxBodySize` (`413`) DoS guard, `stripUnknown` Mass-Assignment protection, and **end-to-end type inference** (`bareClient(app)`) with zero runtime overhead.
|
|
32
|
-
* **API Documentation & RPC**: Automatic **OpenAPI 3.1** (`app.docs`) generation with `securitySchemes`, `servers`, and `tags` directly from route schemas, plus built-in **JSON-RPC 2.0** (`app.rpc`).
|
|
33
|
-
* **Real-Time & Streaming**: Native parameterized **WebSockets** (`app.ws('/ws/:room')`), **Server-Sent Events** (`ctx.sse`), and native zero-dependency Gzip compression (`compress` via `Bun.gzipSync`).
|
|
34
|
-
* **Built-In Resilience & Jobs**: Production `circuitBreaker` (`503 Retry-After`), `idempotency` (`409 IDEMPOTENT_IN_FLIGHT`), `createSingleflight` cache-stampede protection, and overlap-safe `app.cron` background jobs.
|
|
35
|
-
* **Zero-Trust Security & Utilities**: Built-in `securityHeaders()`, `cors()`, `csrf()`, `timeout()`, `rateLimit()`, `trustProxy(false)` anti-spoofing, `bareAuth()` (constant-time HS256 JWT + `revokeToken()`/`isRevoked`), `Hash` (Argon2id), HMAC-signed cookies, `ctx.upload()` / streaming `ctx.uploadStream()`, and symlink-safe `staticFile()`.
|
|
36
|
-
* **Ergonomics & Observability**: Dual response style (return plain objects/strings Elysia-style OR `ctx.json()`/`ctx.html()`/`ctx.text()`/`ctx.redirect()`/`ctx.send()`), `logger()` (`pretty`/`json` + `X-Request-Id`), `healthcheck()` (`/health` + `/ready`), and `app.onDrain()` + IPC `DRAIN_REQUEST` graceful draining.
|
|
37
|
-
|
|
38
|
-
> Verified with **423 Automated Tests (6,249 assertions)** and **100.00% Function & 100.00% Line Coverage**.
|
|
39
|
-
|
|
40
17
|
---
|
|
41
18
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
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.
|
|
45
|
-
|
|
46
|
-
<!-- MARKER: MULTI_BENCH_START -->
|
|
47
|
-
|
|
48
|
-
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
49
|
-
| :--- | :---: | :---: | :---: |
|
|
50
|
-
| **1. 100 Routes + Dynamic Params** | **`840 ns`**<br><sub>`p99: 5.14 µs`</sub> | `1.08 µs`<br><sub>`p99: 5.68 µs`</sub> | `2.22 µs`<br><sub>`p99: 10.76 µs`</sub> |
|
|
51
|
-
| **2. 10 Middlewares + Deep Path** | **`769 ns`**<br><sub>`p99: 4.30 µs`</sub> | `1.10 µs`<br><sub>`p99: 5.48 µs`</sub> | `2.46 µs`<br><sub>`p99: 11.15 µs`</sub> |
|
|
52
|
-
| **3. POST JSON + Schema Validation** | **`2.09 µs`**<br><sub>`p99: 8.99 µs`</sub> | `2.52 µs`<br><sub>`p99: 9.64 µs`</sub> | `2.65 µs`<br><sub>`p99: 10.97 µs`</sub> |
|
|
53
|
-
| **4. Async Handler + Query Parsing** | **`1.32 µs`**<br><sub>`p99: 6.52 µs`</sub> | `1.40 µs`<br><sub>`p99: 6.71 µs`</sub> | `1.83 µs`<br><sub>`p99: 8.79 µs`</sub> |
|
|
54
|
-
| **5. Response Schema Secret Stripping** | **`803 ns`**<br><sub>`p99: 5.86 µs`</sub> | `986 ns`<br><sub>`p99: 4.28 µs`</sub> | — |
|
|
55
|
-
| **6. SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | `12.70 µs`<br><sub>`p99: 21.52 µs`</sub> | **`12.64 µs`**<br><sub>`p99: 20.67 µs`</sub> | `15.65 µs`<br><sub>`p99: 33.22 µs`</sub> |
|
|
56
|
-
| **7. SQLite Write (`POST` + Validate + `INSERT`)** | **`4.79 µs`**<br><sub>`p99: 15.30 µs`</sub> | `6.33 µs`<br><sub>`p99: 20.52 µs`</sub> | `8.41 µs`<br><sub>`p99: 30.16 µs`</sub> |
|
|
57
|
-
|
|
58
|
-
> Last Updated: 2026-11-24 (github action)
|
|
19
|
+
```typescript
|
|
20
|
+
import { BareJS, Type, type Context } from 'barejs';
|
|
59
21
|
|
|
60
|
-
|
|
22
|
+
const app = new BareJS();
|
|
61
23
|
|
|
62
|
-
|
|
24
|
+
app.get('/', () => ({ hello: 'world' }));
|
|
63
25
|
|
|
64
|
-
|
|
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
|
|
65
31
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
| **BareJS** | **0.75 µs** | **Baseline** |
|
|
69
|
-
| Elysia | 0.92 µs | 1.22x slower |
|
|
70
|
-
| Hono | 3.16 µs | 4.20x slower |
|
|
32
|
+
app.listen(3000);
|
|
33
|
+
```
|
|
71
34
|
|
|
72
|
-
|
|
35
|
+
---
|
|
73
36
|
|
|
74
|
-
|
|
37
|
+
## Why BareJS?
|
|
75
38
|
|
|
76
|
-
|
|
77
|
-
|
|
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`).
|
|
78
45
|
|
|
79
46
|
---
|
|
80
47
|
|
|
81
|
-
##
|
|
48
|
+
## Installation & Quick Start
|
|
49
|
+
|
|
50
|
+
<details open>
|
|
51
|
+
<summary><strong>Bun (>= 1.1.0)</strong></summary>
|
|
82
52
|
|
|
83
53
|
```bash
|
|
84
54
|
bun add barejs
|
|
85
55
|
```
|
|
86
56
|
|
|
87
57
|
```typescript
|
|
88
|
-
import { BareJS
|
|
58
|
+
import { BareJS } from 'barejs';
|
|
89
59
|
|
|
90
60
|
const app = new BareJS();
|
|
91
|
-
|
|
92
|
-
// 1. Direct return (Elysia style)
|
|
93
|
-
app.get('/', () => ({ hello: 'world' }));
|
|
94
|
-
app.get('/ping', () => 'pong');
|
|
95
|
-
|
|
96
|
-
// 2. Context helpers (Hono / Express style)
|
|
97
|
-
app.get('/welcome', (ctx: Context) => ctx.html('<h1>ສະບາຍດີ BareJS</h1>'));
|
|
98
|
-
app.get('/old', (ctx: Context) => ctx.redirect('/', 301));
|
|
99
|
-
|
|
100
|
-
// 3. Wildcard catch-all route
|
|
101
|
-
app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
|
|
102
|
-
|
|
61
|
+
app.get('/', () => ({ runtime: 'bun' }));
|
|
103
62
|
app.listen(3000);
|
|
104
63
|
```
|
|
105
64
|
|
|
106
|
-
|
|
65
|
+
</details>
|
|
107
66
|
|
|
108
|
-
|
|
67
|
+
<details>
|
|
68
|
+
<summary><strong>Node.js (>= 20.0.0)</strong></summary>
|
|
109
69
|
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
// Node.js (>= 20)
|
|
116
|
-
import { BareJS } from 'barejs/node';
|
|
117
|
-
app.listen(3000);
|
|
118
|
-
|
|
119
|
-
// Deno / Web-Standard fetch hosts
|
|
120
|
-
Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));
|
|
70
|
+
```bash
|
|
71
|
+
npm install barejs
|
|
72
|
+
# Optional peer dependencies if using WebSockets or password hashing:
|
|
73
|
+
npm install ws @node-rs/argon2
|
|
121
74
|
```
|
|
122
75
|
|
|
123
|
-
> Optional peer dependencies on Node.js: install `ws` if using `app.ws()`, and `@node-rs/argon2` (or `bcryptjs`) if using `Hash`.
|
|
124
|
-
|
|
125
|
-
---
|
|
126
|
-
|
|
127
|
-
## 📘 Comprehensive Guide
|
|
128
|
-
|
|
129
|
-
### 1. ✅ Unified Route Validation & Auto-Coercion (`body`, `query`, `params`, `headers`)
|
|
130
|
-
|
|
131
|
-
Pass a schema object directly before your handler. BareJS automatically coerces numeric and boolean strings in `params` and `query`, enforces `maxBodySize` (`413 Payload Too Large`), and registers the route in OpenAPI `/docs`.
|
|
132
|
-
|
|
133
76
|
```typescript
|
|
134
|
-
import { BareJS
|
|
77
|
+
import { BareJS } from 'barejs/node';
|
|
135
78
|
|
|
136
79
|
const app = new BareJS();
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
app.post('/orders/:orderId', {
|
|
140
|
-
detail: { summary: 'Create Order', tags: ['Orders'] },
|
|
141
|
-
params: Type.Object({ orderId: Type.Integer() }), // "42" -> 42
|
|
142
|
-
query: Type.Object({ notify: Type.Optional(Type.Boolean()) }), // "true" -> true
|
|
143
|
-
headers: Type.Object({ 'x-api-version': Type.Optional(Type.String()) }),
|
|
144
|
-
body: Type.Object({
|
|
145
|
-
item: Type.String({ minLength: 1 }),
|
|
146
|
-
qty: Type.Integer({ minimum: 1 })
|
|
147
|
-
}),
|
|
148
|
-
// Response schema automatically strips undeclared secret fields (e.g. internal_cost)!
|
|
149
|
-
response: Type.Object({
|
|
150
|
-
orderId: Type.Number(),
|
|
151
|
-
notify: Type.Optional(Type.Boolean()),
|
|
152
|
-
body: Type.Object({ item: Type.String(), qty: Type.Number() })
|
|
153
|
-
}),
|
|
154
|
-
maxBodySize: 512 * 1024 // 512 KB limit (returns 413 if exceeded)
|
|
155
|
-
}, (ctx: Context) => ({
|
|
156
|
-
orderId: ctx.params.orderId, // number
|
|
157
|
-
notify: ctx.query.notify, // boolean | undefined
|
|
158
|
-
body: ctx.body, // validated body
|
|
159
|
-
internal_cost: 9999 // automatically stripped before sending to client!
|
|
160
|
-
}));
|
|
161
|
-
|
|
162
|
-
// Standalone middleware validators are also supported:
|
|
163
|
-
app.post('/zod', Z.object({ email: Z.string().email() }), (ctx) => ctx.body);
|
|
164
|
-
app.post('/native', native({
|
|
165
|
-
properties: { title: { type: 'string' }, priority: { type: 'number' } },
|
|
166
|
-
required: ['title'] // 'priority' is optional
|
|
167
|
-
}), (ctx) => ctx.body);
|
|
80
|
+
app.get('/', () => ({ runtime: 'node' }));
|
|
81
|
+
app.listen(3000);
|
|
168
82
|
```
|
|
169
83
|
|
|
170
|
-
|
|
84
|
+
</details>
|
|
171
85
|
|
|
172
|
-
|
|
86
|
+
<details>
|
|
87
|
+
<summary><strong>Deno (>= 2.0)</strong></summary>
|
|
173
88
|
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
app.post('/session', async (ctx) => {
|
|
177
|
-
await ctx.setCookie('session_id', 'user_42', {
|
|
178
|
-
secret: process.env.COOKIE_SECRET!,
|
|
179
|
-
httpOnly: true,
|
|
180
|
-
secure: true,
|
|
181
|
-
sameSite: 'Strict',
|
|
182
|
-
maxAge: 3600
|
|
183
|
-
});
|
|
184
|
-
return { loggedIn: true };
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
app.get('/session', async (ctx) => {
|
|
188
|
-
const userId = await ctx.getSignedCookie('session_id', process.env.COOKIE_SECRET!);
|
|
189
|
-
if (!userId) return ctx.status(401).json({ error: 'Invalid or tampered cookie' });
|
|
190
|
-
return { userId };
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
// Safe Multipart File Upload (enforces size, file count, MIME allowlist & filename sanitization)
|
|
194
|
-
app.post('/upload', async (ctx) => {
|
|
195
|
-
const { fields, files } = await ctx.upload({
|
|
196
|
-
maxFileSize: 5 * 1024 * 1024, // 5 MB -> 413 if exceeded
|
|
197
|
-
maxFiles: 3, // -> 413 if exceeded
|
|
198
|
-
allowedTypes: ['image/png', 'image/jpeg', 'application/pdf'] // -> 415 if unsupported
|
|
199
|
-
});
|
|
200
|
-
return {
|
|
201
|
-
fields,
|
|
202
|
-
uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type }))
|
|
203
|
-
};
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
// True Streaming Multipart Upload (constant O(chunk) memory for large files)
|
|
207
|
-
app.post('/upload-stream', async (ctx) => {
|
|
208
|
-
const uploaded: string[] = [];
|
|
209
|
-
for await (const part of ctx.uploadStream({ maxFileSize: 500 * 1024 * 1024 })) {
|
|
210
|
-
if (part.type === 'file' && part.stream) {
|
|
211
|
-
await Bun.write(`./uploads/${part.safeName}`, new Response(part.stream));
|
|
212
|
-
uploaded.push(part.safeName!);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
return { uploaded };
|
|
216
|
-
});
|
|
89
|
+
```bash
|
|
90
|
+
deno add npm:barejs
|
|
217
91
|
```
|
|
218
92
|
|
|
219
|
-
---
|
|
220
|
-
|
|
221
|
-
### 3. 🛡️ Production Security Suite, Idempotency & Singleflight
|
|
222
|
-
|
|
223
93
|
```typescript
|
|
224
|
-
import {
|
|
225
|
-
BareJS, BareRouter, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
226
|
-
idempotency, createSingleflight, redisStore, compress,
|
|
227
|
-
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
228
|
-
} from 'barejs';
|
|
94
|
+
import { BareJS } from 'barejs';
|
|
229
95
|
|
|
230
96
|
const app = new BareJS();
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
app.use(securityHeaders());
|
|
235
|
-
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
236
|
-
app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
|
|
237
|
-
app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s
|
|
238
|
-
app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip
|
|
239
|
-
app.use(rateLimit({ windowMs: 60_000, max: 100, store }));
|
|
240
|
-
app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
|
|
241
|
-
|
|
242
|
-
// Payment/Order Double-Charge Protection (Idempotency-Key header)
|
|
243
|
-
// - Returns 409 Conflict if duplicate request is currently in-flight
|
|
244
|
-
// - Replays cached response with X-Idempotent-Replayed: true on retry
|
|
245
|
-
app.post('/payments', idempotency({ ttlMs: 86_400_000, store }), async (ctx) => {
|
|
246
|
-
const body = await ctx.jsonBody();
|
|
247
|
-
return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
// Cache-Stampede / Thundering-Herd Request Coalescing
|
|
251
|
-
const singleflight = createSingleflight();
|
|
252
|
-
app.get('/reports/daily', async () => {
|
|
253
|
-
// 100 concurrent requests coalesce into a SINGLE database query execution
|
|
254
|
-
return singleflight.do('daily-report', async () => ({ revenue: 125_000, generatedAt: Date.now() }));
|
|
255
|
-
});
|
|
256
|
-
|
|
257
|
-
// Argon2id Password Hashing & JWT Creation
|
|
258
|
-
app.post('/login', async (ctx) => {
|
|
259
|
-
const { password } = await ctx.jsonBody();
|
|
260
|
-
const hash = await Hash.make(password);
|
|
261
|
-
const valid = await Hash.verify(password, hash);
|
|
262
|
-
if (!valid) return ctx.status(401).send('Invalid credentials');
|
|
263
|
-
|
|
264
|
-
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET);
|
|
265
|
-
return { token };
|
|
266
|
-
});
|
|
267
|
-
|
|
268
|
-
// Protect routes with constant-time HS256 JWT or asymmetric RS256/ES256/JWKS (`ctx.user`)
|
|
269
|
-
app.get('/admin', bareAuth({ secret: SECRET, revocationStore: store }), hasRole('admin'), (ctx) => ({
|
|
270
|
-
user: ctx.user,
|
|
271
|
-
requestId: ctx.requestId
|
|
272
|
-
}));
|
|
273
|
-
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));
|
|
274
99
|
```
|
|
275
100
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
### 4. 🧩 Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks
|
|
279
|
-
|
|
280
|
-
```typescript
|
|
281
|
-
// Enrich ctx with full TypeScript inference (auto-cleaned on pool release)
|
|
282
|
-
const appWithContext = app.derive((ctx) => ({
|
|
283
|
-
requestTime: Date.now(),
|
|
284
|
-
traceId: ctx.requestId
|
|
285
|
-
}));
|
|
286
|
-
|
|
287
|
-
appWithContext.get('/trace', (ctx) => ({
|
|
288
|
-
traceId: ctx.traceId, // typed as string
|
|
289
|
-
requestTime: ctx.requestTime // typed as number
|
|
290
|
-
}));
|
|
291
|
-
|
|
292
|
-
// Register a modular plugin
|
|
293
|
-
app.use({
|
|
294
|
-
name: 'health-plugin',
|
|
295
|
-
install(instance) {
|
|
296
|
-
instance.get('/healthz', (ctx: any) => ({ ok: true, traceId: ctx.traceId }));
|
|
297
|
-
}
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
// Server Lifecycle & Error Masking
|
|
301
|
-
app.onStart(() => console.log('Database ready'));
|
|
302
|
-
app.onDrain(async () => console.log('Draining in-flight requests...')); // Triggered on app.drain() or IPC DRAIN_REQUEST
|
|
303
|
-
app.onStop(async () => console.log('Cleaned up resources'));
|
|
304
|
-
app.onError((err, ctx) => ctx.status(err.status || 500).json({
|
|
305
|
-
status: 'error',
|
|
306
|
-
message: err.message,
|
|
307
|
-
requestId: ctx.requestId
|
|
308
|
-
}));
|
|
309
|
-
```
|
|
101
|
+
</details>
|
|
310
102
|
|
|
311
103
|
---
|
|
312
104
|
|
|
313
|
-
|
|
105
|
+
## Runtime Support
|
|
314
106
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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` |
|
|
322
116
|
|
|
323
|
-
|
|
117
|
+
---
|
|
324
118
|
|
|
325
|
-
|
|
326
|
-
app.ws('/ws/chat', {
|
|
327
|
-
open: (ws) => ws.send('connected'),
|
|
328
|
-
message: (ws, msg) => ws.send(`echo: ${msg}`)
|
|
329
|
-
});
|
|
119
|
+
## Benchmarks (Bun)
|
|
330
120
|
|
|
331
|
-
|
|
332
|
-
app.get('/events', (ctx) => ctx.sse(async (send) => {
|
|
333
|
-
send({ step: 1, msg: 'streaming...' }, 'progress', '1');
|
|
334
|
-
}));
|
|
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.
|
|
335
122
|
|
|
336
|
-
|
|
337
|
-
app.rpc('/rpc', {
|
|
338
|
-
add: ({ a, b }: { a: number; b: number }) => a + b
|
|
339
|
-
});
|
|
123
|
+
<!-- MARKER: MULTI_BENCH_SUMMARY_START -->
|
|
340
124
|
|
|
341
|
-
|
|
342
|
-
|
|
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> |
|
|
343
131
|
|
|
344
|
-
|
|
345
|
-
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`)
|
|
346
133
|
|
|
347
|
-
|
|
348
|
-
const inMemoryClient = bareClient(app);
|
|
349
|
-
const localRes = await inMemoryClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
134
|
+
<!-- MARKER: MULTI_BENCH_SUMMARY_END -->
|
|
350
135
|
|
|
351
|
-
|
|
352
|
-
const remoteRes = await httpClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
353
|
-
```
|
|
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/).
|
|
354
137
|
|
|
355
138
|
---
|
|
356
139
|
|
|
357
|
-
|
|
140
|
+
## Documentation
|
|
358
141
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
.use(logger({ format: 'json' })) // Structured JSON logs + X-Request-Id
|
|
365
|
-
.use(healthcheck({
|
|
366
|
-
path: '/health',
|
|
367
|
-
readyPath: '/ready',
|
|
368
|
-
version: '1.0.0',
|
|
369
|
-
checks: { db: async () => true }
|
|
370
|
-
}))
|
|
371
|
-
.use(bareAuth({
|
|
372
|
-
secret: process.env.JWT_SECRET!,
|
|
373
|
-
isRevoked: async (payload) => isBlockedInRedis(payload.jti)
|
|
374
|
-
}));
|
|
375
|
-
|
|
376
|
-
// Revoke a compromised token or jti immediately
|
|
377
|
-
revokeToken('compromised-jti-123', 3600_000);
|
|
378
|
-
|
|
379
|
-
// OpenAPI 3.1 with Bearer JWT securitySchemes
|
|
380
|
-
app.docs('/docs', {
|
|
381
|
-
title: 'Production API',
|
|
382
|
-
securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
|
|
383
|
-
security: [{ bearerAuth: [] }]
|
|
384
|
-
});
|
|
385
|
-
|
|
386
|
-
// Enforce server-level maxRequestBodySize (default: 10MB)
|
|
387
|
-
app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
|
|
388
|
-
```
|
|
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).
|
|
389
147
|
|
|
390
148
|
---
|
|
391
149
|
|
|
392
|
-
##
|
|
393
|
-
|
|
394
|
-
| Method / Property | Description |
|
|
395
|
-
| :--- | :--- |
|
|
396
|
-
| `ctx.req` | Raw incoming Bun `Request` object. |
|
|
397
|
-
| `ctx.params` | Route parameters (`:id` or `ctx.params['*']` for wildcard routes). |
|
|
398
|
-
| `ctx.query` / `ctx.getQuery(k)` | Lazy, prototype-pollution-safe parsed query parameters. |
|
|
399
|
-
| `await ctx.jsonBody(maxBytes?)` | Parses & caches JSON body (enforces `413` limit, default 1MB). |
|
|
400
|
-
| `await ctx.upload(options?)` | Safe `multipart/form-data` upload parser (`maxFileSize`, `maxFiles`, `allowedTypes`). |
|
|
401
|
-
| `ctx.uploadStream(options?)` | True streaming `multipart/form-data` async generator (`ReadableStream` per file part, $O(\text{chunk})$ memory). |
|
|
402
|
-
| `ctx.cookies` | Lazy parsed request cookies (`Record<string, string>`). |
|
|
403
|
-
| `await ctx.setCookie(k, v, opts?)` | Sets a cookie (`HttpOnly; SameSite=Lax` default, optional HMAC `secret`). |
|
|
404
|
-
| `await ctx.getSignedCookie(k, s)` | Verifies HMAC-SHA256 signed cookie in constant time. |
|
|
405
|
-
| `ctx.deleteCookie(k, opts?)` | Expires a cookie immediately. |
|
|
406
|
-
| `ctx.user` | Authenticated user payload from `bareAuth` or `basicAuth`. |
|
|
407
|
-
| `ctx.requestId` | Incoming `x-request-id` header or generated UUIDv4. |
|
|
408
|
-
| `ctx.status(code)` | Sets HTTP response status code (chainable). |
|
|
409
|
-
| `ctx.setHeader(name, value)` | Sets response header (chainable, copy-on-write safe). |
|
|
410
|
-
| `ctx.json(data)` | Returns `application/json` response. |
|
|
411
|
-
| `ctx.send(msg, extra?)` | Returns standardized `{ status, msg, ...extra }` JSON response. |
|
|
412
|
-
| `ctx.html(html, status?)` | Returns `text/html; charset=utf-8` response. |
|
|
413
|
-
| `ctx.text(text, status?)` | Returns `text/plain; charset=utf-8` response. |
|
|
414
|
-
| `ctx.redirect(url, status?)` | Returns HTTP redirect response (default `302`). |
|
|
415
|
-
| `ctx.sse(source)` | Streams Server-Sent Events (`text/event-stream`). |
|
|
416
|
-
| `ctx.set(k, v)` / `ctx.get(k)` | Per-request key-value storage (cleared on pool release). |
|
|
417
|
-
|
|
418
|
-
---
|
|
419
|
-
|
|
420
|
-
## ⚙️ Performance & Environment Configuration
|
|
421
|
-
|
|
422
|
-
| Variable / File | Default | Description |
|
|
423
|
-
| :--- | :--- | :--- |
|
|
424
|
-
| `bare.config.ts` | Optional | Centralized config for `port` and Argon2/bcrypt `hash` parameters. |
|
|
425
|
-
| `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. |
|
|
426
|
-
| `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces and disable startup banner. |
|
|
427
|
-
|
|
428
|
-
---
|
|
150
|
+
## Status, Contributing & License
|
|
429
151
|
|
|
430
|
-
**
|
|
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).
|