barejs 0.1.51 → 0.1.54

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 CHANGED
@@ -24,33 +24,43 @@
24
24
 
25
25
  ## 📊 Benchmarks: Multi-Scenario & Real-World Performance
26
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`) |
27
+ All benchmark numbers below are **automatically generated on every push to `main`** by GitHub Actions running `benchmarks/fair-suite.ts`, `benchmarks/production-bench.ts`, and `benchmarks/head-to-head.ts` on real `mitata` runs.
39
28
 
40
- > Verified with **268 Automated Tests (5,634 assertions)** and **100.00% Function & 100.00% Line Coverage**.
29
+ <!-- MARKER: MULTI_BENCH_START -->
30
+
31
+ | Scenario | **BareJS** 🏆 | **ElysiaJS** | **Hono** |
32
+ | :--- | :---: | :---: | :---: |
33
+ | **1. 100 Routes + Dynamic Params** | **`574 ns`**<br><sub>`p99: 3.37 µs`</sub> | `824 ns`<br><sub>`p99: 3.69 µs`</sub> | `1.63 µs`<br><sub>`p99: 7.08 µs`</sub> |
34
+ | **2. 10 Middlewares + Deep Path** | **`508 ns`**<br><sub>`p99: 3.08 µs`</sub> | `843 ns`<br><sub>`p99: 3.48 µs`</sub> | `1.86 µs`<br><sub>`p99: 7.05 µs`</sub> |
35
+ | **3. POST JSON + Schema Validation** | `1.67 µs`<br><sub>`p99: 6.84 µs`</sub> | `1.90 µs`<br><sub>`p99: 7.07 µs`</sub> | **`1.62 µs`**<br><sub>`p99: 1.95 µs`</sub> |
36
+ | **4. Async Handler + Query Parsing** | **`869 ns`**<br><sub>`p99: 3.58 µs`</sub> | `999 ns`<br><sub>`p99: 3.98 µs`</sub> | `1.37 µs`<br><sub>`p99: 6.40 µs`</sub> |
37
+ | **5. Response Schema Secret Stripping** | **`208 ns`**<br><sub>`p99: 345 ns`</sub> | `775 ns`<br><sub>`p99: 3.46 µs`</sub> | — |
38
+ | **6. SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | **`10.24 µs`**<br><sub>`p99: 15.48 µs`</sub> | `10.49 µs`<br><sub>`p99: 16.36 µs`</sub> | `12.71 µs`<br><sub>`p99: 24.90 µs`</sub> |
39
+ | **7. SQLite Write (`POST` + Validate + `INSERT`)** | **`4.05 µs`**<br><sub>`p99: 10.64 µs`</sub> | `4.70 µs`<br><sub>`p99: 12.95 µs`</sub> | `6.22 µs`<br><sub>`p99: 6.46 µs`</sub> |
40
+
41
+ > Last Updated: 2026-11-19 (github action)
42
+
43
+ <!-- MARKER: MULTI_BENCH_END -->
44
+
45
+ ### Head-to-Head Stress Test (10 Middlewares + Deep Path)
41
46
 
42
47
  <!-- MARKER: PERFORMANCE_TABLE_START -->
43
48
 
44
49
  | Framework | Latency | Speed |
45
50
  | :--- | :--- | :--- |
46
- | **BareJS** | **0.87 µs** | **Baseline** |
47
- | Elysia | 1.14 µs | 1.31x slower |
48
- | Hono | 3.84 µs | 4.39x slower |
51
+ | **BareJS** | **0.51 µs** | **Baseline** |
52
+ | Elysia | 0.76 µs | 1.48x slower |
53
+ | Hono | 2.54 µs | 4.95x slower |
49
54
 
50
- > Last Updated: 2026-11-18 (github action)
55
+ > Last Updated: 2026-11-19 (github action)
51
56
 
52
57
  <!-- MARKER: PERFORMANCE_TABLE_END -->
53
58
 
59
+ > Verified with **268 Automated Tests (5,634 assertions)** and **100.00% Function & 100.00% Line Coverage**.
60
+ >
61
+ > [!TIP]
62
+ > **View our [Continuous Benchmark Dashboard](https://xarhang.github.io/bareJS/dev/benchmarks/)** for historical data and detailed performance trends.
63
+
54
64
  > [!TIP]
55
65
  > **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
66
 
@@ -60,7 +70,7 @@ BareJS is engineered to beat both **ElysiaJS** and **Hono** across routing, midd
60
70
 
61
71
  * **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
72
  * **$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.
73
+ * **Recursive JIT Response Projector & Mass-Assignment Guard**: Compiles `response` schemas into fixed-shape JS object literals to strip undeclared fields, and supports `stripUnknown: true` on `body` to prevent Mass-Assignment attacks.
64
74
  * **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
75
  * **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
76
  * **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.
@@ -185,25 +195,27 @@ app.post('/upload', async (ctx) => {
185
195
 
186
196
  ```typescript
187
197
  import {
188
- BareJS, securityHeaders, cors, csrf, timeout, rateLimit,
189
- idempotency, createSingleflight,
198
+ BareJS, BareRouter, securityHeaders, cors, csrf, timeout, rateLimit,
199
+ idempotency, createSingleflight, redisStore, compress,
190
200
  bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
191
201
  } from 'barejs';
192
202
 
193
203
  const app = new BareJS();
194
204
  const SECRET = process.env.JWT_SECRET || 'super-secret-key';
205
+ const store = redisStore(Bun.redis, { prefix: 'myapp:' }); // Optional: omit for zero-overhead in-memory Map
195
206
 
196
207
  app.use(securityHeaders());
197
208
  app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
198
209
  app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
199
210
  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
211
+ app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip
212
+ app.use(rateLimit({ windowMs: 60_000, max: 100, store }));
213
+ app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
202
214
 
203
215
  // Payment/Order Double-Charge Protection (Idempotency-Key header)
204
216
  // - Returns 409 Conflict if duplicate request is currently in-flight
205
217
  // - Replays cached response with X-Idempotent-Replayed: true on retry
206
- app.post('/payments', idempotency({ ttlMs: 86_400_000 }), async (ctx) => {
218
+ app.post('/payments', idempotency({ ttlMs: 86_400_000, store }), async (ctx) => {
207
219
  const body = await ctx.jsonBody();
208
220
  return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
209
221
  });
@@ -226,11 +238,12 @@ app.post('/login', async (ctx) => {
226
238
  return { token };
227
239
  });
228
240
 
229
- // Protect routes with constant-time JWT verification & RBAC (`ctx.user`)
230
- app.get('/admin', bareAuth({ secret: SECRET }), hasRole('admin'), (ctx) => ({
241
+ // Protect routes with constant-time HS256 JWT or asymmetric RS256/ES256/JWKS (`ctx.user`)
242
+ app.get('/admin', bareAuth({ secret: SECRET, revocationStore: store }), hasRole('admin'), (ctx) => ({
231
243
  user: ctx.user,
232
244
  requestId: ctx.requestId
233
245
  }));
246
+ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user);
234
247
  ```
235
248
 
236
249
  ---
@@ -272,9 +285,14 @@ app.onError((err, ctx) => ctx.status(err.status || 500).json({
272
285
  ### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client
273
286
 
274
287
  ```typescript
275
- import { BareJS, bareClient } from 'barejs';
288
+ import { BareJS, BareRouter, bareClient, Type } from 'barejs';
276
289
 
277
- const app = new BareJS();
290
+ const usersRouter = new BareRouter().get('/users/:id', {
291
+ params: Type.Object({ id: Type.Integer() }),
292
+ query: Type.Object({ full: Type.Optional(Type.Boolean()) }),
293
+ }, (ctx) => ({ id: ctx.params.id, full: ctx.query.full }));
294
+
295
+ const app = new BareJS().route('/api', usersRouter); // Preserves full route type inference!
278
296
 
279
297
  // Native Bun WebSocket
280
298
  app.ws('/ws/chat', {
@@ -295,12 +313,15 @@ app.rpc('/rpc', {
295
313
  // Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs)
296
314
  app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' });
297
315
 
316
+ // Ergonomic in-memory test helper
317
+ const res = await app.request('/api/users/42?full=true');
318
+
298
319
  // Type-Safe Client (Zero-Network In-Memory for tests/SSR OR Network URL)
299
320
  const inMemoryClient = bareClient(app);
300
- const localRes = await inMemoryClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
321
+ const localRes = await inMemoryClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
301
322
 
302
323
  const httpClient = bareClient('http://localhost:3000');
303
- const remoteRes = await httpClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
324
+ const remoteRes = await httpClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
304
325
  ```
305
326
 
306
327
  ---