barejs 0.1.49 → 0.1.51

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.
Files changed (43) hide show
  1. package/README.md +257 -98
  2. package/dist/index.js +157 -94
  3. package/dist/types/client/index.d.ts +24 -22
  4. package/dist/types/core/bare.d.ts +83 -3
  5. package/dist/types/core/context.d.ts +47 -1
  6. package/dist/types/core/radix.d.ts +1 -0
  7. package/dist/types/core/router.d.ts +21 -10
  8. package/dist/types/index.d.ts +16 -8
  9. package/dist/types/security/auth.d.ts +10 -1
  10. package/dist/types/security/cors.d.ts +7 -3
  11. package/dist/types/security/csrf.d.ts +12 -0
  12. package/dist/types/security/idempotency.d.ts +22 -0
  13. package/dist/types/security/resilience.d.ts +17 -0
  14. package/dist/types/security/timeout.d.ts +6 -0
  15. package/dist/types/security/validators.d.ts +18 -0
  16. package/dist/types/utils/compress.d.ts +12 -0
  17. package/dist/types/utils/health.d.ts +17 -0
  18. package/dist/types/utils/logger.d.ts +22 -0
  19. package/dist/types/utils/openapi.d.ts +23 -1
  20. package/dist/types/utils/static.d.ts +5 -1
  21. package/llms.txt +138 -0
  22. package/package.json +3 -1
  23. package/src/client/index.ts +61 -18
  24. package/src/core/bare.ts +409 -49
  25. package/src/core/context.ts +266 -32
  26. package/src/core/radix.ts +37 -3
  27. package/src/core/router.ts +43 -16
  28. package/src/index.ts +25 -9
  29. package/src/security/auth.ts +68 -11
  30. package/src/security/cors.ts +85 -31
  31. package/src/security/csrf.ts +84 -0
  32. package/src/security/hash.ts +8 -2
  33. package/src/security/headers.ts +12 -3
  34. package/src/security/idempotency.ts +118 -0
  35. package/src/security/rateLimit.ts +1 -6
  36. package/src/security/resilience.ts +91 -0
  37. package/src/security/timeout.ts +32 -0
  38. package/src/security/validators.ts +201 -5
  39. package/src/utils/compress.ts +49 -0
  40. package/src/utils/health.ts +65 -0
  41. package/src/utils/logger.ts +66 -0
  42. package/src/utils/openapi.ts +59 -14
  43. package/src/utils/static.ts +71 -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.0.0-black?style=for-the-badge&logo=bun" alt="Bun Version">
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,77 @@
22
22
 
23
23
  ---
24
24
 
25
- </div>
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
- ## 📊 Benchmarks: Real-World Performance
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 **268 Automated Tests (5,634 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.85 µs** | **Baseline** |
35
- | Elysia | 1.30 µs | 1.52x slower |
36
- | Hono | 5.00 µs | 5.88x slower |
46
+ | **BareJS** | **0.87 µs** | **Baseline** |
47
+ | Elysia | 1.14 µs | 1.31x slower |
48
+ | Hono | 3.84 µs | 4.39x slower |
37
49
 
38
- > Last Updated: 2026-11-17 (github action)
50
+ > Last Updated: 2026-11-18 (github action)
39
51
 
40
52
  <!-- MARKER: PERFORMANCE_TABLE_END -->
41
53
 
42
54
  > [!TIP]
43
- > **View our [Continuous Benchmark Dashboard**](https://xarhang.github.io/bareJS/dev/benchmarks/) for historical data and detailed performance trends.
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**: Routes and middleware chains are flattened into a single function at runtime.
48
- * **Concurrency-Safe Object Pooling**: Recycles `Context` objects via a free-list stack, drastically reducing GC pressure with zero cross-request leakage.
49
- * **Internal High-Performance Logger**: Zero-overhead logging integrated directly into the JIT engine.
50
- * **Precise Radix Router**: Optimized segment matching for deep-nested paths and lazy query parsing (`ctx.query`).
51
- * **Real-Time & RPC Ready**: Built-in **Native WebSocket (`app.ws`)**, **SSE (`ctx.sse`)**, **JSON-RPC 2.0 (`app.rpc`)**, and **Type-Safe `bareClient`**.
52
- * **AOT OpenAPI 3.1 Docs**: Zero-runtime-cost `app.docs()` with Scalar UI generated from TypeBox, Zod, and Native schemas.
53
- * **Mechanical Sympathy**: Intentionally designed to align with JSC/V8 optimization and Bun's I/O.
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 & Mass-Assignment Guard**: Compiles `response` schemas into fixed-shape JS object literals (`1.89 µs`, 28% faster than ElysiaJS), and supports `stripUnknown: true` on `body` to prevent Mass-Assignment attacks.
64
+ * **Built-In Resilience (`circuitBreaker`, `idempotency`, `createSingleflight`, `app.cron`)**: Prevent cascading failures (`503 Retry-After`), double-charges (`409 IDEMPOTENT_IN_FLIGHT`), cache stampedes (100 concurrent calls -> 1 DB hit), and overlapping background jobs.
65
+ * **Native Zero-Dep Gzip (`compress`)**: Compresses responses via Bun's native C/Zig `Bun.gzipSync` with `minSize` threshold and automatic SSE/204/304 bypass.
66
+ * **End-to-End Type Inference (`bareClient(app)`)**: Automatic compile-time inference of route paths (across all HTTP methods on shared paths), `params`, `query`, `headers`, `body`, and `response` types directly from your `BareJS` app or mounted `BareRouter`—with zero runtime overhead.
67
+ * **Concurrency-Safe Object Pooling**: Recycles `Context` instances via a LIFO free-list stack with automatic cleanup on release—zero cross-request state leakage.
68
+ * **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`.
69
+ * **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`.
70
+ * **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()`, and symlink-safe `staticFile()`.
71
+ * **Observability, Real-Time, RPC & OpenAPI 3.1**: Built-in `logger()` (`pretty`/`json` + `X-Request-Id`), `healthcheck()` (`/health` + `/ready`), 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`.
72
+
73
+ ---
54
74
 
55
- ## 🛠️ Installation
75
+ ## 🛠️ Installation & Quick Start
56
76
 
57
77
  ```bash
58
78
  bun add barejs
59
79
  ```
60
80
 
61
- ### The "Bare" Minimum
62
-
63
81
  ```typescript
64
- import { BareJS, type Context } from 'barejs';
82
+ import { BareJS, Type, type Context } from 'barejs';
65
83
 
66
84
  const app = new BareJS();
67
85
 
68
- // Enable Internal Logger
69
- app.useLog(true);
86
+ // 1. Direct return (Elysia style)
87
+ app.get('/', () => ({ hello: 'world' }));
88
+ app.get('/ping', () => 'pong');
70
89
 
71
- app.get('/', (ctx: Context) => ctx.json({ hello: "world" }));
90
+ // 2. Context helpers (Hono / Express style)
91
+ app.get('/welcome', (ctx: Context) => ctx.html('<h1>ສະບາຍດີ BareJS</h1>'));
92
+ app.get('/old', (ctx: Context) => ctx.redirect('/', 301));
93
+
94
+ // 3. Wildcard catch-all route
95
+ app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
72
96
 
73
97
  app.listen(3000);
74
98
  ```
@@ -77,87 +101,175 @@ app.listen(3000);
77
101
 
78
102
  ## 📘 Comprehensive Guide
79
103
 
80
- ### 1. ⚡ Standardized Response, Lazy Query & Error Hook
104
+ ### 1. ✅ Unified Route Validation & Auto-Coercion (`body`, `query`, `params`, `headers`)
81
105
 
82
- BareJS v0.1.49 provides a fluent API for responses, lazy query parsing, and centralized error handling.
106
+ 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
107
 
84
108
  ```typescript
85
- app.onError((err, ctx) => {
86
- ctx.status(500);
87
- return { status: "error", message: err.message };
88
- });
109
+ import { BareJS, Type, Z, native, type Context } from 'barejs';
89
110
 
90
- app.get('/api/v1/health', (ctx: Context) => {
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
- });
111
+ const app = new BareJS();
112
+
113
+ // Declarative RouteSchemas (works with TypeBox, Zod, or Native JSON Schema)
114
+ app.post('/orders/:orderId', {
115
+ detail: { summary: 'Create Order', tags: ['Orders'] },
116
+ params: Type.Object({ orderId: Type.Integer() }), // "42" -> 42
117
+ query: Type.Object({ notify: Type.Optional(Type.Boolean()) }), // "true" -> true
118
+ headers: Type.Object({ 'x-api-version': Type.Optional(Type.String()) }),
119
+ body: Type.Object({
120
+ item: Type.String({ minLength: 1 }),
121
+ qty: Type.Integer({ minimum: 1 })
122
+ }),
123
+ // Response schema automatically strips undeclared secret fields (e.g. internal_cost)!
124
+ response: Type.Object({
125
+ orderId: Type.Number(),
126
+ notify: Type.Optional(Type.Boolean()),
127
+ body: Type.Object({ item: Type.String(), qty: Type.Number() })
128
+ }),
129
+ maxBodySize: 512 * 1024 // 512 KB limit (returns 413 if exceeded)
130
+ }, (ctx: Context) => ({
131
+ orderId: ctx.params.orderId, // number
132
+ notify: ctx.query.notify, // boolean | undefined
133
+ body: ctx.body, // validated body
134
+ internal_cost: 9999 // automatically stripped before sending to client!
135
+ }));
97
136
 
98
- // Output: { "status": "success", "msg": "System is healthy", "verbose": ..., "uptime": ... }
137
+ // Standalone middleware validators are also supported:
138
+ app.post('/zod', Z.object({ email: Z.string().email() }), (ctx) => ctx.body);
139
+ app.post('/native', native({
140
+ properties: { title: { type: 'string' }, priority: { type: 'number' } },
141
+ required: ['title'] // 'priority' is optional
142
+ }), (ctx) => ctx.body);
99
143
  ```
100
144
 
101
- ### 2. 🛡️ Security & Authentication (Dual-API)
145
+ ---
102
146
 
103
- ```typescript
104
- import { bareAuth, createToken, basicAuth, hasRole, Password, Hash, type Context } from 'barejs';
147
+ ### 2. 🍪 Cookies, HMAC Signed Cookies & Safe File Uploads
105
148
 
106
- const SECRET = process.env.JWT_SECRET || "your-secret";
149
+ ```typescript
150
+ // HMAC-SHA256 Signed Cookies (HttpOnly & SameSite=Lax by default)
151
+ app.post('/session', async (ctx) => {
152
+ await ctx.setCookie('session_id', 'user_42', {
153
+ secret: process.env.COOKIE_SECRET!,
154
+ httpOnly: true,
155
+ secure: true,
156
+ sameSite: 'Strict',
157
+ maxAge: 3600
158
+ });
159
+ return { loggedIn: true };
160
+ });
107
161
 
108
- app.post('/register', async (ctx: Context) => {
109
- const body = await ctx.jsonBody();
110
-
111
- // High-performance Argon2id Hashing (64MB default)
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
- }
162
+ app.get('/session', async (ctx) => {
163
+ const userId = await ctx.getSignedCookie('session_id', process.env.COOKIE_SECRET!);
164
+ if (!userId) return ctx.status(401).json({ error: 'Invalid or tampered cookie' });
165
+ return { userId };
121
166
  });
122
167
 
123
- // Protect routes with constant-time JWT middleware & RBAC
124
- app.get('/me', bareAuth(SECRET), hasRole('admin'), (ctx: Context) => {
125
- return ctx.send("Authenticated", { user: ctx.get('user') });
168
+ // Safe Multipart File Upload (enforces size, file count, MIME allowlist & filename sanitization)
169
+ app.post('/upload', async (ctx) => {
170
+ const { fields, files } = await ctx.upload({
171
+ maxFileSize: 5 * 1024 * 1024, // 5 MB -> 413 if exceeded
172
+ maxFiles: 3, // -> 413 if exceeded
173
+ allowedTypes: ['image/png', 'image/jpeg', 'application/pdf'] // -> 415 if unsupported
174
+ });
175
+ return {
176
+ fields,
177
+ uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type }))
178
+ };
126
179
  });
127
180
  ```
128
181
 
129
- ### 3. ✅ Data Validation (3 Styles)
182
+ ---
130
183
 
131
- BareJS is the only engine that offers JIT-optimized validation paths.
184
+ ### 3. 🛡️ Production Security Suite, Idempotency & Singleflight
132
185
 
133
186
  ```typescript
134
- import { typebox, zod, native, t, type Context } from 'barejs';
135
- import { z } from 'zod';
187
+ import {
188
+ BareJS, securityHeaders, cors, csrf, timeout, rateLimit,
189
+ idempotency, createSingleflight,
190
+ bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
191
+ } from 'barejs';
136
192
 
137
- // Style A: TypeBox (JIT Optimized - Recommended)
138
- const Schema = t.Object({ name: t.String() });
139
- app.post('/user', typebox(Schema), (ctx) => ctx.json(ctx.body));
193
+ const app = new BareJS();
194
+ const SECRET = process.env.JWT_SECRET || 'super-secret-key';
140
195
 
141
- // Style B: Zod (Industry Standard)
142
- const ZodSchema = z.object({ age: z.number() });
143
- app.post('/age', zod(ZodSchema), (ctx) => ctx.json(ctx.body));
196
+ app.use(securityHeaders());
197
+ app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
198
+ app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
199
+ app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s
200
+ app.use(rateLimit({ windowMs: 60_000, max: 100 }));
201
+ app.use(staticFile('public', { maxAge: 3600, etag: true })); // ETag, 304, Range 206/416
202
+
203
+ // Payment/Order Double-Charge Protection (Idempotency-Key header)
204
+ // - Returns 409 Conflict if duplicate request is currently in-flight
205
+ // - Replays cached response with X-Idempotent-Replayed: true on retry
206
+ app.post('/payments', idempotency({ ttlMs: 86_400_000 }), async (ctx) => {
207
+ const body = await ctx.jsonBody();
208
+ return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
209
+ });
144
210
 
145
- // Style C: Native (Zero Dependency - Simple Checks)
146
- app.post('/native', native({ properties: { id: { type: 'number' } } }), (ctx) => ctx.json(ctx.body));
211
+ // Cache-Stampede / Thundering-Herd Request Coalescing
212
+ const singleflight = createSingleflight();
213
+ app.get('/reports/daily', async () => {
214
+ // 100 concurrent requests coalesce into a SINGLE database query execution
215
+ return singleflight.do('daily-report', async () => ({ revenue: 125_000, generatedAt: Date.now() }));
216
+ });
217
+
218
+ // Argon2id Password Hashing & JWT Creation
219
+ app.post('/login', async (ctx) => {
220
+ const { password } = await ctx.jsonBody();
221
+ const hash = await Hash.make(password);
222
+ const valid = await Hash.verify(password, hash);
223
+ if (!valid) return ctx.status(401).send('Invalid credentials');
224
+
225
+ const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET);
226
+ return { token };
227
+ });
228
+
229
+ // Protect routes with constant-time JWT verification & RBAC (`ctx.user`)
230
+ app.get('/admin', bareAuth({ secret: SECRET }), hasRole('admin'), (ctx) => ({
231
+ user: ctx.user,
232
+ requestId: ctx.requestId
233
+ }));
147
234
  ```
148
235
 
149
- ### 4. 🔌 Essential Production Middleware
236
+ ---
237
+
238
+ ### 4. 🧩 Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks
150
239
 
151
240
  ```typescript
152
- import { cors, rateLimit, securityHeaders, staticFile } from 'barejs';
241
+ // Enrich ctx with full TypeScript inference (auto-cleaned on pool release)
242
+ const appWithContext = app.derive((ctx) => ({
243
+ requestTime: Date.now(),
244
+ traceId: ctx.requestId
245
+ }));
153
246
 
154
- app.use(securityHeaders());
155
- app.use(cors({ origin: 'https://example.com' }));
156
- app.use(rateLimit({ windowMs: 60_000, max: 100 }));
157
- app.use(staticFile("public"));
247
+ appWithContext.get('/trace', (ctx) => ({
248
+ traceId: ctx.traceId, // typed as string
249
+ requestTime: ctx.requestTime // typed as number
250
+ }));
251
+
252
+ // Register a modular plugin
253
+ app.use({
254
+ name: 'health-plugin',
255
+ install(instance) {
256
+ instance.get('/healthz', (ctx: any) => ({ ok: true, traceId: ctx.traceId }));
257
+ }
258
+ });
259
+
260
+ // Server Lifecycle & Error Masking
261
+ app.onStart(() => console.log('Database ready'));
262
+ app.onStop(async () => console.log('Cleaned up resources'));
263
+ app.onError((err, ctx) => ctx.status(err.status || 500).json({
264
+ status: 'error',
265
+ message: err.message,
266
+ requestId: ctx.requestId
267
+ }));
158
268
  ```
159
269
 
160
- ### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI & RPC
270
+ ---
271
+
272
+ ### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client
161
273
 
162
274
  ```typescript
163
275
  import { BareJS, bareClient } from 'barejs';
@@ -175,7 +287,7 @@ app.get('/events', (ctx) => ctx.sse(async (send) => {
175
287
  send({ step: 1, msg: 'streaming...' }, 'progress', '1');
176
288
  }));
177
289
 
178
- // JSON-RPC 2.0 Endpoint (single & batch)
290
+ // JSON-RPC 2.0 Endpoint (single, batch & notifications)
179
291
  app.rpc('/rpc', {
180
292
  add: ({ a, b }: { a: number; b: number }) => a + b
181
293
  });
@@ -183,38 +295,85 @@ app.rpc('/rpc', {
183
295
  // Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs)
184
296
  app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' });
185
297
 
186
- // Type-Safe HTTP RPC Client
187
- const client = bareClient('http://localhost:3000');
188
- const user = await client.get('/users/:id', { params: { id: 42 }, query: { full: true } });
298
+ // Type-Safe Client (Zero-Network In-Memory for tests/SSR OR Network URL)
299
+ const inMemoryClient = bareClient(app);
300
+ const localRes = await inMemoryClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
301
+
302
+ const httpClient = bareClient('http://localhost:3000');
303
+ const remoteRes = await httpClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
304
+ ```
305
+
306
+ ---
307
+
308
+ ### 6. 🛡️ Production Observability & Zero-Trust Hardening
309
+
310
+ ```typescript
311
+ import { BareJS, logger, healthcheck, bareAuth, revokeToken } from 'barejs';
312
+
313
+ const app = new BareJS()
314
+ .trustProxy(false) // Ignore spoofed X-Forwarded-For when directly exposed
315
+ .use(logger({ format: 'json' })) // Structured JSON logs + X-Request-Id
316
+ .use(healthcheck({
317
+ path: '/health',
318
+ readyPath: '/ready',
319
+ version: '1.0.0',
320
+ checks: { db: async () => true }
321
+ }))
322
+ .use(bareAuth({
323
+ secret: process.env.JWT_SECRET!,
324
+ isRevoked: async (payload) => isBlockedInRedis(payload.jti)
325
+ }));
326
+
327
+ // Revoke a compromised token or jti immediately
328
+ revokeToken('compromised-jti-123', 3600_000);
329
+
330
+ // OpenAPI 3.1 with Bearer JWT securitySchemes
331
+ app.docs('/docs', {
332
+ title: 'Production API',
333
+ securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
334
+ security: [{ bearerAuth: [] }]
335
+ });
336
+
337
+ // Enforce server-level maxRequestBodySize (default: 10MB)
338
+ app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
189
339
  ```
190
340
 
191
341
  ---
192
342
 
193
- ## 🧠 Context API
343
+ ## 🧠 Complete `Context` (`ctx`) Reference
194
344
 
195
345
  | Method / Property | Description |
196
- | --- | --- |
346
+ | :--- | :--- |
197
347
  | `ctx.req` | Raw incoming Bun `Request` object. |
198
- | `ctx.params` | Route parameters (e.g., `:id`). |
199
- | `ctx.query` | **Lazy** parsed query parameters object. |
200
- | `ctx.getQuery(key)` | Returns a single query parameter value lazily. |
201
- | `ctx.jsonBody()` | **[Async]** Parses and caches JSON body for performance. |
202
- | `ctx.status(code)` | Sets the HTTP status code (**Chainable**). |
203
- | `ctx.send(msg, ext)` | Returns a standardized JSON response. |
204
- | `ctx.json(data)` | Returns an optimized raw JSON response. |
348
+ | `ctx.params` | Route parameters (`:id` or `ctx.params['*']` for wildcard routes). |
349
+ | `ctx.query` / `ctx.getQuery(k)` | Lazy, prototype-pollution-safe parsed query parameters. |
350
+ | `await ctx.jsonBody(maxBytes?)` | Parses & caches JSON body (enforces `413` limit, default 1MB). |
351
+ | `await ctx.upload(options?)` | Safe `multipart/form-data` upload parser (`maxFileSize`, `maxFiles`, `allowedTypes`). |
352
+ | `ctx.cookies` | Lazy parsed request cookies (`Record<string, string>`). |
353
+ | `await ctx.setCookie(k, v, opts?)` | Sets a cookie (`HttpOnly; SameSite=Lax` default, optional HMAC `secret`). |
354
+ | `await ctx.getSignedCookie(k, s)` | Verifies HMAC-SHA256 signed cookie in constant time. |
355
+ | `ctx.deleteCookie(k, opts?)` | Expires a cookie immediately. |
356
+ | `ctx.user` | Authenticated user payload from `bareAuth` or `basicAuth`. |
357
+ | `ctx.requestId` | Incoming `x-request-id` header or generated UUIDv4. |
358
+ | `ctx.status(code)` | Sets HTTP response status code (chainable). |
359
+ | `ctx.setHeader(name, value)` | Sets response header (chainable, copy-on-write safe). |
360
+ | `ctx.json(data)` | Returns `application/json` response. |
361
+ | `ctx.send(msg, extra?)` | Returns standardized `{ status, msg, ...extra }` JSON response. |
362
+ | `ctx.html(html, status?)` | Returns `text/html; charset=utf-8` response. |
363
+ | `ctx.text(text, status?)` | Returns `text/plain; charset=utf-8` response. |
364
+ | `ctx.redirect(url, status?)` | Returns HTTP redirect response (default `302`). |
205
365
  | `ctx.sse(source)` | Streams Server-Sent Events (`text/event-stream`). |
206
- | `ctx.setHeader(k, v)` | Sets a response header. |
207
- | `ctx.set / ctx.get` | Manual storage within the request lifecycle. |
366
+ | `ctx.set(k, v)` / `ctx.get(k)` | Per-request key-value storage (cleared on pool release). |
208
367
 
209
368
  ---
210
369
 
211
- ## ⚙️ Performance Tuning
370
+ ## ⚙️ Performance & Environment Configuration
212
371
 
213
- | OS Variable / File | Default | Description |
214
- | --- | --- | --- |
215
- | `bare.config.ts` | - | Centralized config for Port and Hash algorithms. |
216
- | `BARE_POOL_SIZE` | `1024` | Context pool size (**Must be Power of 2**). |
217
- | `NODE_ENV` | `development` | Set to `production` to enable peak JIT optimizations. |
372
+ | Variable / File | Default | Description |
373
+ | :--- | :--- | :--- |
374
+ | `bare.config.ts` | Optional | Centralized config for `port` and Argon2/bcrypt `hash` parameters. |
375
+ | `poolSize` | `1024` | `new BareJS(poolSize)` — rounded up to power of 2 for $O(1)$ pooling. |
376
+ | `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces and disable startup banner. |
218
377
 
219
378
  ---
220
379