barejs 0.1.48 → 0.1.50
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 +243 -84
- package/dist/index.js +162 -67
- package/dist/types/client/index.d.ts +50 -0
- package/dist/types/core/bare.d.ts +24 -1
- package/dist/types/core/context.d.ts +54 -2
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +3 -1
- package/dist/types/index.d.ts +14 -6
- package/dist/types/security/auth.d.ts +3 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/headers.d.ts +9 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/rateLimit.d.ts +9 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +16 -0
- package/dist/types/utils/openapi.d.ts +15 -0
- package/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +123 -0
- package/src/core/bare.ts +352 -40
- package/src/core/context.ts +356 -33
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +17 -5
- package/src/index.ts +32 -8
- package/src/security/auth.ts +2 -1
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/headers.ts +68 -0
- package/src/security/idempotency.ts +99 -0
- package/src/security/rateLimit.ts +76 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +206 -9
- package/src/utils/openapi.ts +151 -0
- package/src/utils/static.ts +62 -5
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
<br />
|
|
3
3
|
<h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
|
|
4
4
|
<p><strong>The "Metal" of Web Frameworks</strong></p>
|
|
5
|
-
<p><i>An ultra-high-performance web engine built for Bun, architected strictly for Mechanical Sympathy.</i></p>
|
|
5
|
+
<p><i>An ultra-high-performance JIT-compiled web engine built for Bun, architected strictly for Mechanical Sympathy, Zero-Trust Security, and Effortless Developer Experience.</i></p>
|
|
6
6
|
|
|
7
7
|
<p>
|
|
8
8
|
<a href="https://www.npmjs.com/package/barejs">
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
<img src="https://img.shields.io/github/actions/workflow/status/xarhang/barejs/bench.yml?branch=main&label=Performance&style=for-the-badge&logo=github" alt="Performance">
|
|
13
13
|
</a>
|
|
14
14
|
<a href="https://bun.sh">
|
|
15
|
-
<img src="https://img.shields.io/badge/Bun-%3E%3D1.
|
|
15
|
+
<img src="https://img.shields.io/badge/Bun-%3E%3D1.1.0-black?style=for-the-badge&logo=bun" alt="Bun Version">
|
|
16
16
|
</a>
|
|
17
17
|
<a href="https://github.com/xarhang/barejs/blob/main/LICENSE">
|
|
18
18
|
<img src="https://img.shields.io/github/license/xarhang/barejs?style=for-the-badge&color=blue" alt="License">
|
|
@@ -22,162 +22,321 @@
|
|
|
22
22
|
|
|
23
23
|
---
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
## 📊 Benchmarks: Multi-Scenario & Real-World Performance
|
|
26
|
+
|
|
27
|
+
BareJS is engineered to beat both **ElysiaJS** and **Hono** across routing, middleware pipelines, schema validation, recursive response secret stripping, and real SQLite database workloads—while matching raw **Bun Native (`Bun.serve`)** HTTP throughput.
|
|
28
|
+
|
|
29
|
+
| Scenario (`benchmarks/fair-suite.ts` & `production-bench.ts`) | **BareJS** 🏆 | **Bun Native** | **ElysiaJS** | **Hono** |
|
|
30
|
+
| :--- | :---: | :---: | :---: | :---: |
|
|
31
|
+
| **1. 100 Routes + Dynamic Params** | **`1.85 µs`** (`792 ns` min) | `2.86 µs` | `2.31 µs` | `4.77 µs` |
|
|
32
|
+
| **2. 10 Middlewares + Deep Path** | **`1.82 µs`** (`970 B` RAM) | `2.54 µs` | `2.71 µs` (`1.14 KB`) | `5.34 µs` (`1.81 KB`) |
|
|
33
|
+
| **3. POST JSON + Schema Validation** | **`5.00 µs`** (`2.26 KB`) | `5.04 µs` | `5.45 µs` (`2.24 KB`) | `5.51 µs` (`3.53 KB`) |
|
|
34
|
+
| **4. Async Handler + Query Parsing** | **`2.83 µs`** (`1.22 KB` RAM) | `2.99 µs` | `2.92 µs` (`1.58 KB`) | `4.19 µs` (`1.80 KB`) |
|
|
35
|
+
| **5. Live HTTP Server (`Bun.serve` + `fetch`)** | **`45.33 µs`** (`p99: 94 µs`) | `46.63 µs` (`p99: 126 µs`) | `49.31 µs` (`p99: 145 µs`) | `68.54 µs` (`p99: 162 µs`) |
|
|
36
|
+
| **6. Response Schema Secret Stripping** | **`2.01 µs`** (`653 B` RAM) | — | `2.40 µs` (`893 B` RAM) | — |
|
|
37
|
+
| **7. Live SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | **`91.53 µs`** (`p99: 218 µs`) | — | `94.51 µs` (`p99: 277 µs`) | `103.66 µs` (`p99: 543 µs`) |
|
|
38
|
+
| **8. Live SQLite Write (`POST` + Validate + `INSERT`)** | **`88.37 µs`** (`2.84 KB`) | — | `88.51 µs` (`2.95 KB`) | `103.73 µs` (`3.33 KB`) |
|
|
26
39
|
|
|
27
|
-
|
|
40
|
+
> Verified with **209 Automated Tests (2,878 assertions)** and **100.00% Function & 100.00% Line Coverage**.
|
|
28
41
|
|
|
29
|
-
BareJS leads in complex, real-world scenarios. We measure engine efficiency using a **stress test** involving **10+ middlewares** and **deep radix tree routing** to ensure performance holds under high concurrency.
|
|
30
42
|
<!-- MARKER: PERFORMANCE_TABLE_START -->
|
|
31
43
|
|
|
32
44
|
| Framework | Latency | Speed |
|
|
33
45
|
| :--- | :--- | :--- |
|
|
34
|
-
| **BareJS** | **
|
|
35
|
-
| Elysia | 1.
|
|
36
|
-
| Hono |
|
|
46
|
+
| **BareJS** | **0.95 µs** | **Baseline** |
|
|
47
|
+
| Elysia | 1.17 µs | 1.23x slower |
|
|
48
|
+
| Hono | 4.06 µs | 4.26x slower |
|
|
37
49
|
|
|
38
|
-
> Last Updated: 2026-11-
|
|
50
|
+
> Last Updated: 2026-11-17 (github action)
|
|
39
51
|
|
|
40
52
|
<!-- MARKER: PERFORMANCE_TABLE_END -->
|
|
41
53
|
|
|
42
54
|
> [!TIP]
|
|
43
|
-
> **
|
|
55
|
+
> **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.
|
|
56
|
+
|
|
57
|
+
---
|
|
44
58
|
|
|
45
59
|
## 🚀 Key Features
|
|
46
60
|
|
|
47
|
-
* **JIT Pipeline Compilation**:
|
|
48
|
-
*
|
|
49
|
-
* **
|
|
50
|
-
* **
|
|
51
|
-
* **
|
|
61
|
+
* **JIT Pipeline Compilation**: Flattens routes and middleware chains into direct JavaScript functions at startup, using `AsyncFunction` single-handler fast paths and conditional bytecode inlining.
|
|
62
|
+
* **$O(1)$ Radix Jump-Table Router**: Compiles static branches, dynamic `:params`, and catch-all wildcards (`/*`) into inline `switch` jump-tables.
|
|
63
|
+
* **Recursive JIT Response Projector (`compileProjector`)**: Compiles `response` schemas (**TypeBox**, **Zod**, or **Native**) into fixed-shape JS object literals that strip undeclared secret fields (`passwordHash`, `secretToken`) recursively at **`2.01 µs` (`653 B` RAM)**—19.4% faster and 27% lower memory than ElysiaJS.
|
|
64
|
+
* **Built-In Payment Idempotency & Singleflight Coalescing**: Prevent double-charges and race conditions with `idempotency()` (`409 IDEMPOTENT_IN_FLIGHT` + `X-Idempotent-Replayed: true`), and eliminate cache-stampede / thundering-herd DB overload with `createSingleflight()`.
|
|
65
|
+
* **Concurrency-Safe Object Pooling**: Recycles `Context` instances via a LIFO free-list stack with automatic cleanup on release—zero cross-request state leakage.
|
|
66
|
+
* **Dual Response Ergonomics**: Return plain objects/strings directly (Elysia style) OR use chainable `ctx.json()`, `ctx.html()`, `ctx.text()`, `ctx.redirect()`, `ctx.send()` helpers (Hono/Express style).
|
|
67
|
+
* **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`.
|
|
68
|
+
* **Batteries-Included Security Suite**: Built-in `securityHeaders()` (frozen zero-alloc), `cors()` (allowlist/predicate/credentials), `csrf()` (`Sec-Fetch-Site` + `Origin`/`Referer` + double-submit token), `timeout()` (`408`), `rateLimit()` (bounded LRU), `bareAuth()` (constant-time HS256 JWT), `Hash` (Argon2id), HMAC-signed `HttpOnly` cookies, and safe `ctx.upload()`.
|
|
69
|
+
* **Real-Time, RPC, OpenAPI 3.1 & Zero-Network Client**: Native WebSocket (`app.ws`), Server-Sent Events (`ctx.sse`), JSON-RPC 2.0 (`app.rpc`), Scalar OpenAPI 3.1 UI (`app.docs`), and `bareClient(app | url)` (supports both in-memory zero-port execution and network HTTP).
|
|
70
|
+
|
|
71
|
+
---
|
|
52
72
|
|
|
53
|
-
## 🛠️ Installation
|
|
73
|
+
## 🛠️ Installation & Quick Start
|
|
54
74
|
|
|
55
75
|
```bash
|
|
56
76
|
bun add barejs
|
|
57
|
-
|
|
58
77
|
```
|
|
59
78
|
|
|
60
|
-
### The "Bare" Minimum
|
|
61
|
-
|
|
62
79
|
```typescript
|
|
63
|
-
import { BareJS, type Context } from 'barejs';
|
|
80
|
+
import { BareJS, Type, type Context } from 'barejs';
|
|
64
81
|
|
|
65
82
|
const app = new BareJS();
|
|
66
83
|
|
|
67
|
-
//
|
|
68
|
-
app.
|
|
84
|
+
// 1. Direct return (Elysia style)
|
|
85
|
+
app.get('/', () => ({ hello: 'world' }));
|
|
86
|
+
app.get('/ping', () => 'pong');
|
|
69
87
|
|
|
70
|
-
|
|
88
|
+
// 2. Context helpers (Hono / Express style)
|
|
89
|
+
app.get('/welcome', (ctx: Context) => ctx.html('<h1>ສະບາຍດີ BareJS</h1>'));
|
|
90
|
+
app.get('/old', (ctx: Context) => ctx.redirect('/', 301));
|
|
71
91
|
|
|
72
|
-
|
|
92
|
+
// 3. Wildcard catch-all route
|
|
93
|
+
app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
|
|
73
94
|
|
|
95
|
+
app.listen(3000);
|
|
74
96
|
```
|
|
75
97
|
|
|
76
98
|
---
|
|
77
99
|
|
|
78
100
|
## 📘 Comprehensive Guide
|
|
79
101
|
|
|
80
|
-
### 1.
|
|
102
|
+
### 1. ✅ Unified Route Validation & Auto-Coercion (`body`, `query`, `params`, `headers`)
|
|
81
103
|
|
|
82
|
-
|
|
104
|
+
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`.
|
|
83
105
|
|
|
84
106
|
```typescript
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
107
|
+
import { BareJS, Type, Z, native, type Context } from 'barejs';
|
|
108
|
+
|
|
109
|
+
const app = new BareJS();
|
|
110
|
+
|
|
111
|
+
// Declarative RouteSchemas (works with TypeBox, Zod, or Native JSON Schema)
|
|
112
|
+
app.post('/orders/:orderId', {
|
|
113
|
+
detail: { summary: 'Create Order', tags: ['Orders'] },
|
|
114
|
+
params: Type.Object({ orderId: Type.Integer() }), // "42" -> 42
|
|
115
|
+
query: Type.Object({ notify: Type.Optional(Type.Boolean()) }), // "true" -> true
|
|
116
|
+
headers: Type.Object({ 'x-api-version': Type.Optional(Type.String()) }),
|
|
117
|
+
body: Type.Object({
|
|
118
|
+
item: Type.String({ minLength: 1 }),
|
|
119
|
+
qty: Type.Integer({ minimum: 1 })
|
|
120
|
+
}),
|
|
121
|
+
// Response schema automatically strips undeclared secret fields (e.g. internal_cost)!
|
|
122
|
+
response: Type.Object({
|
|
123
|
+
orderId: Type.Number(),
|
|
124
|
+
notify: Type.Optional(Type.Boolean()),
|
|
125
|
+
body: Type.Object({ item: Type.String(), qty: Type.Number() })
|
|
126
|
+
}),
|
|
127
|
+
maxBodySize: 512 * 1024 // 512 KB limit (returns 413 if exceeded)
|
|
128
|
+
}, (ctx: Context) => ({
|
|
129
|
+
orderId: ctx.params.orderId, // number
|
|
130
|
+
notify: ctx.query.notify, // boolean | undefined
|
|
131
|
+
body: ctx.body, // validated body
|
|
132
|
+
internal_cost: 9999 // automatically stripped before sending to client!
|
|
133
|
+
}));
|
|
134
|
+
|
|
135
|
+
// Standalone middleware validators are also supported:
|
|
136
|
+
app.post('/zod', Z.object({ email: Z.string().email() }), (ctx) => ctx.body);
|
|
137
|
+
app.post('/native', native({
|
|
138
|
+
properties: { title: { type: 'string' }, priority: { type: 'number' } },
|
|
139
|
+
required: ['title'] // 'priority' is optional
|
|
140
|
+
}), (ctx) => ctx.body);
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
### 2. 🍪 Cookies, HMAC Signed Cookies & Safe File Uploads
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
// HMAC-SHA256 Signed Cookies (HttpOnly & SameSite=Lax by default)
|
|
149
|
+
app.post('/session', async (ctx) => {
|
|
150
|
+
await ctx.setCookie('session_id', 'user_42', {
|
|
151
|
+
secret: process.env.COOKIE_SECRET!,
|
|
152
|
+
httpOnly: true,
|
|
153
|
+
secure: true,
|
|
154
|
+
sameSite: 'Strict',
|
|
155
|
+
maxAge: 3600
|
|
89
156
|
});
|
|
157
|
+
return { loggedIn: true };
|
|
90
158
|
});
|
|
91
159
|
|
|
92
|
-
|
|
160
|
+
app.get('/session', async (ctx) => {
|
|
161
|
+
const userId = await ctx.getSignedCookie('session_id', process.env.COOKIE_SECRET!);
|
|
162
|
+
if (!userId) return ctx.status(401).json({ error: 'Invalid or tampered cookie' });
|
|
163
|
+
return { userId };
|
|
164
|
+
});
|
|
93
165
|
|
|
166
|
+
// Safe Multipart File Upload (enforces size, file count, MIME allowlist & filename sanitization)
|
|
167
|
+
app.post('/upload', async (ctx) => {
|
|
168
|
+
const { fields, files } = await ctx.upload({
|
|
169
|
+
maxFileSize: 5 * 1024 * 1024, // 5 MB -> 413 if exceeded
|
|
170
|
+
maxFiles: 3, // -> 413 if exceeded
|
|
171
|
+
allowedTypes: ['image/png', 'image/jpeg', 'application/pdf'] // -> 415 if unsupported
|
|
172
|
+
});
|
|
173
|
+
return {
|
|
174
|
+
fields,
|
|
175
|
+
uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type }))
|
|
176
|
+
};
|
|
177
|
+
});
|
|
94
178
|
```
|
|
95
179
|
|
|
96
|
-
|
|
180
|
+
---
|
|
97
181
|
|
|
98
|
-
|
|
99
|
-
import { bareAuth, createToken, Password, Hash, type Context } from 'barejs';
|
|
182
|
+
### 3. 🛡️ Production Security Suite, Idempotency & Singleflight
|
|
100
183
|
|
|
101
|
-
|
|
184
|
+
```typescript
|
|
185
|
+
import {
|
|
186
|
+
BareJS, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
187
|
+
idempotency, createSingleflight,
|
|
188
|
+
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
189
|
+
} from 'barejs';
|
|
102
190
|
|
|
103
|
-
app
|
|
191
|
+
const app = new BareJS();
|
|
192
|
+
const SECRET = process.env.JWT_SECRET || 'super-secret-key';
|
|
193
|
+
|
|
194
|
+
app.use(securityHeaders());
|
|
195
|
+
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
196
|
+
app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
|
|
197
|
+
app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s
|
|
198
|
+
app.use(rateLimit({ windowMs: 60_000, max: 100 }));
|
|
199
|
+
app.use(staticFile('public', { maxAge: 3600, etag: true })); // ETag, 304, Range 206/416
|
|
200
|
+
|
|
201
|
+
// Payment/Order Double-Charge Protection (Idempotency-Key header)
|
|
202
|
+
// - Returns 409 Conflict if duplicate request is currently in-flight
|
|
203
|
+
// - Replays cached response with X-Idempotent-Replayed: true on retry
|
|
204
|
+
app.post('/payments', idempotency({ ttlMs: 86_400_000 }), async (ctx) => {
|
|
104
205
|
const body = await ctx.jsonBody();
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const token = await createToken({ id: 1 }, SECRET);
|
|
114
|
-
return { token };
|
|
115
|
-
}
|
|
206
|
+
return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Cache-Stampede / Thundering-Herd Request Coalescing
|
|
210
|
+
const singleflight = createSingleflight();
|
|
211
|
+
app.get('/reports/daily', async () => {
|
|
212
|
+
// 100 concurrent requests coalesce into a SINGLE database query execution
|
|
213
|
+
return singleflight.do('daily-report', async () => ({ revenue: 125_000, generatedAt: Date.now() }));
|
|
116
214
|
});
|
|
117
215
|
|
|
118
|
-
//
|
|
119
|
-
app.
|
|
120
|
-
|
|
216
|
+
// Argon2id Password Hashing & JWT Creation
|
|
217
|
+
app.post('/login', async (ctx) => {
|
|
218
|
+
const { password } = await ctx.jsonBody();
|
|
219
|
+
const hash = await Hash.make(password);
|
|
220
|
+
const valid = await Hash.verify(password, hash);
|
|
221
|
+
if (!valid) return ctx.status(401).send('Invalid credentials');
|
|
222
|
+
|
|
223
|
+
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET);
|
|
224
|
+
return { token };
|
|
121
225
|
});
|
|
122
226
|
|
|
227
|
+
// Protect routes with constant-time JWT verification & RBAC (`ctx.user`)
|
|
228
|
+
app.get('/admin', bareAuth({ secret: SECRET }), hasRole('admin'), (ctx) => ({
|
|
229
|
+
user: ctx.user,
|
|
230
|
+
requestId: ctx.requestId
|
|
231
|
+
}));
|
|
123
232
|
```
|
|
124
233
|
|
|
125
|
-
|
|
234
|
+
---
|
|
126
235
|
|
|
127
|
-
|
|
236
|
+
### 4. 🧩 Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks
|
|
128
237
|
|
|
129
238
|
```typescript
|
|
130
|
-
|
|
131
|
-
|
|
239
|
+
// Enrich ctx with full TypeScript inference (auto-cleaned on pool release)
|
|
240
|
+
const appWithContext = app.derive((ctx) => ({
|
|
241
|
+
requestTime: Date.now(),
|
|
242
|
+
traceId: ctx.requestId
|
|
243
|
+
}));
|
|
244
|
+
|
|
245
|
+
appWithContext.get('/trace', (ctx) => ({
|
|
246
|
+
traceId: ctx.traceId, // typed as string
|
|
247
|
+
requestTime: ctx.requestTime // typed as number
|
|
248
|
+
}));
|
|
249
|
+
|
|
250
|
+
// Register a modular plugin
|
|
251
|
+
app.use({
|
|
252
|
+
name: 'health-plugin',
|
|
253
|
+
install(instance) {
|
|
254
|
+
instance.get('/healthz', (ctx: any) => ({ ok: true, traceId: ctx.traceId }));
|
|
255
|
+
}
|
|
256
|
+
});
|
|
132
257
|
|
|
133
|
-
//
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
app.
|
|
258
|
+
// Server Lifecycle & Error Masking
|
|
259
|
+
app.onStart(() => console.log('Database ready'));
|
|
260
|
+
app.onStop(async () => console.log('Cleaned up resources'));
|
|
261
|
+
app.onError((err, ctx) => ctx.status(err.status || 500).json({
|
|
262
|
+
status: 'error',
|
|
263
|
+
message: err.message,
|
|
264
|
+
requestId: ctx.requestId
|
|
265
|
+
}));
|
|
266
|
+
```
|
|
137
267
|
|
|
138
|
-
|
|
139
|
-
const ZodSchema = z.object({ age: z.number() });
|
|
140
|
-
app.post('/age', zod(ZodSchema), (ctx) => ctx.json(ctx.body));
|
|
268
|
+
---
|
|
141
269
|
|
|
142
|
-
|
|
143
|
-
app.post('/native', native({ properties: { id: { type: 'number' } } }), (ctx) => ctx.json(ctx.body));
|
|
270
|
+
### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client
|
|
144
271
|
|
|
145
|
-
```
|
|
272
|
+
```typescript
|
|
273
|
+
import { BareJS, bareClient } from 'barejs';
|
|
146
274
|
|
|
147
|
-
|
|
275
|
+
const app = new BareJS();
|
|
148
276
|
|
|
149
|
-
|
|
150
|
-
|
|
277
|
+
// Native Bun WebSocket
|
|
278
|
+
app.ws('/ws/chat', {
|
|
279
|
+
open: (ws) => ws.send('connected'),
|
|
280
|
+
message: (ws, msg) => ws.send(`echo: ${msg}`)
|
|
281
|
+
});
|
|
151
282
|
|
|
152
|
-
|
|
153
|
-
app.
|
|
283
|
+
// Server-Sent Events (SSE)
|
|
284
|
+
app.get('/events', (ctx) => ctx.sse(async (send) => {
|
|
285
|
+
send({ step: 1, msg: 'streaming...' }, 'progress', '1');
|
|
286
|
+
}));
|
|
154
287
|
|
|
288
|
+
// JSON-RPC 2.0 Endpoint (single, batch & notifications)
|
|
289
|
+
app.rpc('/rpc', {
|
|
290
|
+
add: ({ a, b }: { a: number; b: number }) => a + b
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs)
|
|
294
|
+
app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' });
|
|
295
|
+
|
|
296
|
+
// Type-Safe Client (Zero-Network In-Memory for tests/SSR OR Network URL)
|
|
297
|
+
const inMemoryClient = bareClient(app);
|
|
298
|
+
const localRes = await inMemoryClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
299
|
+
|
|
300
|
+
const httpClient = bareClient('http://localhost:3000');
|
|
301
|
+
const remoteRes = await httpClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
155
302
|
```
|
|
156
303
|
|
|
157
304
|
---
|
|
158
305
|
|
|
159
|
-
## 🧠 Context
|
|
306
|
+
## 🧠 Complete `Context` (`ctx`) Reference
|
|
160
307
|
|
|
161
308
|
| Method / Property | Description |
|
|
162
|
-
|
|
|
309
|
+
| :--- | :--- |
|
|
163
310
|
| `ctx.req` | Raw incoming Bun `Request` object. |
|
|
164
|
-
| `ctx.params` | Route parameters (
|
|
165
|
-
| `ctx.
|
|
166
|
-
| `ctx.
|
|
167
|
-
| `ctx.
|
|
168
|
-
| `ctx.
|
|
169
|
-
| `ctx.
|
|
170
|
-
| `ctx.
|
|
311
|
+
| `ctx.params` | Route parameters (`:id` or `ctx.params['*']` for wildcard routes). |
|
|
312
|
+
| `ctx.query` / `ctx.getQuery(k)` | Lazy, prototype-pollution-safe parsed query parameters. |
|
|
313
|
+
| `await ctx.jsonBody(maxBytes?)` | Parses & caches JSON body (enforces `413` limit, default 1MB). |
|
|
314
|
+
| `await ctx.upload(options?)` | Safe `multipart/form-data` upload parser (`maxFileSize`, `maxFiles`, `allowedTypes`). |
|
|
315
|
+
| `ctx.cookies` | Lazy parsed request cookies (`Record<string, string>`). |
|
|
316
|
+
| `await ctx.setCookie(k, v, opts?)` | Sets a cookie (`HttpOnly; SameSite=Lax` default, optional HMAC `secret`). |
|
|
317
|
+
| `await ctx.getSignedCookie(k, s)` | Verifies HMAC-SHA256 signed cookie in constant time. |
|
|
318
|
+
| `ctx.deleteCookie(k, opts?)` | Expires a cookie immediately. |
|
|
319
|
+
| `ctx.user` | Authenticated user payload from `bareAuth` or `basicAuth`. |
|
|
320
|
+
| `ctx.requestId` | Incoming `x-request-id` header or generated UUIDv4. |
|
|
321
|
+
| `ctx.status(code)` | Sets HTTP response status code (chainable). |
|
|
322
|
+
| `ctx.setHeader(name, value)` | Sets response header (chainable, copy-on-write safe). |
|
|
323
|
+
| `ctx.json(data)` | Returns `application/json` response. |
|
|
324
|
+
| `ctx.send(msg, extra?)` | Returns standardized `{ status, msg, ...extra }` JSON response. |
|
|
325
|
+
| `ctx.html(html, status?)` | Returns `text/html; charset=utf-8` response. |
|
|
326
|
+
| `ctx.text(text, status?)` | Returns `text/plain; charset=utf-8` response. |
|
|
327
|
+
| `ctx.redirect(url, status?)` | Returns HTTP redirect response (default `302`). |
|
|
328
|
+
| `ctx.sse(source)` | Streams Server-Sent Events (`text/event-stream`). |
|
|
329
|
+
| `ctx.set(k, v)` / `ctx.get(k)` | Per-request key-value storage (cleared on pool release). |
|
|
171
330
|
|
|
172
331
|
---
|
|
173
332
|
|
|
174
|
-
## ⚙️ Performance
|
|
333
|
+
## ⚙️ Performance & Environment Configuration
|
|
175
334
|
|
|
176
|
-
|
|
|
177
|
-
|
|
|
178
|
-
| `bare.config.ts` |
|
|
179
|
-
| `
|
|
180
|
-
| `NODE_ENV` | `development` | Set to `production` to
|
|
335
|
+
| Variable / File | Default | Description |
|
|
336
|
+
| :--- | :--- | :--- |
|
|
337
|
+
| `bare.config.ts` | Optional | Centralized config for `port` and Argon2/bcrypt `hash` parameters. |
|
|
338
|
+
| `poolSize` | `1024` | `new BareJS(poolSize)` — rounded up to power of 2 for $O(1)$ pooling. |
|
|
339
|
+
| `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces and disable startup banner. |
|
|
181
340
|
|
|
182
341
|
---
|
|
183
342
|
|