barejs 0.1.49 → 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 +219 -97
- package/dist/index.js +137 -75
- package/dist/types/client/index.d.ts +3 -1
- package/dist/types/core/bare.d.ts +10 -0
- package/dist/types/core/context.d.ts +45 -1
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +2 -1
- package/dist/types/index.d.ts +8 -4
- 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/idempotency.d.ts +22 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +16 -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 +4 -2
- package/src/core/bare.ts +200 -36
- package/src/core/context.ts +261 -32
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +16 -5
- package/src/index.ts +17 -5
- 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 +12 -3
- package/src/security/idempotency.ts +99 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +198 -5
- package/src/utils/openapi.ts +49 -14
- 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,53 +22,75 @@
|
|
|
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.
|
|
26
28
|
|
|
27
|
-
|
|
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`) |
|
|
39
|
+
|
|
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** | **0.
|
|
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
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
|
-
* **
|
|
52
|
-
* **
|
|
53
|
-
* **
|
|
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
|
+
---
|
|
54
72
|
|
|
55
|
-
## 🛠️ Installation
|
|
73
|
+
## 🛠️ Installation & Quick Start
|
|
56
74
|
|
|
57
75
|
```bash
|
|
58
76
|
bun add barejs
|
|
59
77
|
```
|
|
60
78
|
|
|
61
|
-
### The "Bare" Minimum
|
|
62
|
-
|
|
63
79
|
```typescript
|
|
64
|
-
import { BareJS, type Context } from 'barejs';
|
|
80
|
+
import { BareJS, Type, type Context } from 'barejs';
|
|
65
81
|
|
|
66
82
|
const app = new BareJS();
|
|
67
83
|
|
|
68
|
-
//
|
|
69
|
-
app.
|
|
84
|
+
// 1. Direct return (Elysia style)
|
|
85
|
+
app.get('/', () => ({ hello: 'world' }));
|
|
86
|
+
app.get('/ping', () => 'pong');
|
|
87
|
+
|
|
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));
|
|
70
91
|
|
|
71
|
-
|
|
92
|
+
// 3. Wildcard catch-all route
|
|
93
|
+
app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
|
|
72
94
|
|
|
73
95
|
app.listen(3000);
|
|
74
96
|
```
|
|
@@ -77,87 +99,175 @@ app.listen(3000);
|
|
|
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
|
-
ctx.status(500);
|
|
87
|
-
return { status: "error", message: err.message };
|
|
88
|
-
});
|
|
107
|
+
import { BareJS, Type, Z, native, type Context } from 'barejs';
|
|
89
108
|
|
|
90
|
-
app
|
|
91
|
-
const verbose = ctx.getQuery('verbose'); // Lazy-parsed only when accessed
|
|
92
|
-
return ctx.status(200).send("System is healthy", {
|
|
93
|
-
verbose: verbose === 'true',
|
|
94
|
-
uptime: process.uptime()
|
|
95
|
-
});
|
|
96
|
-
});
|
|
109
|
+
const app = new BareJS();
|
|
97
110
|
|
|
98
|
-
//
|
|
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);
|
|
99
141
|
```
|
|
100
142
|
|
|
101
|
-
|
|
143
|
+
---
|
|
102
144
|
|
|
103
|
-
|
|
104
|
-
import { bareAuth, createToken, basicAuth, hasRole, Password, Hash, type Context } from 'barejs';
|
|
145
|
+
### 2. 🍪 Cookies, HMAC Signed Cookies & Safe File Uploads
|
|
105
146
|
|
|
106
|
-
|
|
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
|
|
156
|
+
});
|
|
157
|
+
return { loggedIn: true };
|
|
158
|
+
});
|
|
107
159
|
|
|
108
|
-
app.
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const hash = await Password.make(body.password);
|
|
113
|
-
|
|
114
|
-
// Verify with ease
|
|
115
|
-
const isValid = await Hash.verify(body.password, hash);
|
|
116
|
-
|
|
117
|
-
if (isValid) {
|
|
118
|
-
const token = await createToken({ id: 1, role: 'admin' }, SECRET);
|
|
119
|
-
return { token };
|
|
120
|
-
}
|
|
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 };
|
|
121
164
|
});
|
|
122
165
|
|
|
123
|
-
//
|
|
124
|
-
app.
|
|
125
|
-
|
|
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
|
+
};
|
|
126
177
|
});
|
|
127
178
|
```
|
|
128
179
|
|
|
129
|
-
|
|
180
|
+
---
|
|
130
181
|
|
|
131
|
-
|
|
182
|
+
### 3. 🛡️ Production Security Suite, Idempotency & Singleflight
|
|
132
183
|
|
|
133
184
|
```typescript
|
|
134
|
-
import {
|
|
135
|
-
|
|
185
|
+
import {
|
|
186
|
+
BareJS, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
187
|
+
idempotency, createSingleflight,
|
|
188
|
+
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
189
|
+
} from 'barejs';
|
|
136
190
|
|
|
137
|
-
|
|
138
|
-
const
|
|
139
|
-
app.post('/user', typebox(Schema), (ctx) => ctx.json(ctx.body));
|
|
191
|
+
const app = new BareJS();
|
|
192
|
+
const SECRET = process.env.JWT_SECRET || 'super-secret-key';
|
|
140
193
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
app.
|
|
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) => {
|
|
205
|
+
const body = await ctx.jsonBody();
|
|
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() }));
|
|
214
|
+
});
|
|
215
|
+
|
|
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');
|
|
144
222
|
|
|
145
|
-
|
|
146
|
-
|
|
223
|
+
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET);
|
|
224
|
+
return { token };
|
|
225
|
+
});
|
|
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
|
+
}));
|
|
147
232
|
```
|
|
148
233
|
|
|
149
|
-
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
### 4. 🧩 Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks
|
|
150
237
|
|
|
151
238
|
```typescript
|
|
152
|
-
|
|
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
|
+
}));
|
|
153
244
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
+
});
|
|
257
|
+
|
|
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
|
+
}));
|
|
158
266
|
```
|
|
159
267
|
|
|
160
|
-
|
|
268
|
+
---
|
|
269
|
+
|
|
270
|
+
### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client
|
|
161
271
|
|
|
162
272
|
```typescript
|
|
163
273
|
import { BareJS, bareClient } from 'barejs';
|
|
@@ -175,7 +285,7 @@ app.get('/events', (ctx) => ctx.sse(async (send) => {
|
|
|
175
285
|
send({ step: 1, msg: 'streaming...' }, 'progress', '1');
|
|
176
286
|
}));
|
|
177
287
|
|
|
178
|
-
// JSON-RPC 2.0 Endpoint (single &
|
|
288
|
+
// JSON-RPC 2.0 Endpoint (single, batch & notifications)
|
|
179
289
|
app.rpc('/rpc', {
|
|
180
290
|
add: ({ a, b }: { a: number; b: number }) => a + b
|
|
181
291
|
});
|
|
@@ -183,38 +293,50 @@ app.rpc('/rpc', {
|
|
|
183
293
|
// Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs)
|
|
184
294
|
app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' });
|
|
185
295
|
|
|
186
|
-
// Type-Safe
|
|
187
|
-
const
|
|
188
|
-
const
|
|
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 } });
|
|
189
302
|
```
|
|
190
303
|
|
|
191
304
|
---
|
|
192
305
|
|
|
193
|
-
## 🧠 Context
|
|
306
|
+
## 🧠 Complete `Context` (`ctx`) Reference
|
|
194
307
|
|
|
195
308
|
| Method / Property | Description |
|
|
196
|
-
|
|
|
309
|
+
| :--- | :--- |
|
|
197
310
|
| `ctx.req` | Raw incoming Bun `Request` object. |
|
|
198
|
-
| `ctx.params` | Route parameters (
|
|
199
|
-
| `ctx.query` |
|
|
200
|
-
| `ctx.
|
|
201
|
-
| `ctx.
|
|
202
|
-
| `ctx.
|
|
203
|
-
| `ctx.
|
|
204
|
-
| `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`). |
|
|
205
328
|
| `ctx.sse(source)` | Streams Server-Sent Events (`text/event-stream`). |
|
|
206
|
-
| `ctx.
|
|
207
|
-
| `ctx.set / ctx.get` | Manual storage within the request lifecycle. |
|
|
329
|
+
| `ctx.set(k, v)` / `ctx.get(k)` | Per-request key-value storage (cleared on pool release). |
|
|
208
330
|
|
|
209
331
|
---
|
|
210
332
|
|
|
211
|
-
## ⚙️ Performance
|
|
333
|
+
## ⚙️ Performance & Environment Configuration
|
|
212
334
|
|
|
213
|
-
|
|
|
214
|
-
|
|
|
215
|
-
| `bare.config.ts` |
|
|
216
|
-
| `
|
|
217
|
-
| `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. |
|
|
218
340
|
|
|
219
341
|
---
|
|
220
342
|
|