barejs 0.1.57 → 0.1.59

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
@@ -1,8 +1,8 @@
1
1
  <div align="center">
2
2
  <br />
3
3
  <h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
4
- <p><strong>The "Metal" of Web Frameworks</strong></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>
4
+ <p><strong>The batteries-included Bun web framework engineered for zero-overhead speed.</strong></p>
5
+ <p><i>BareJS delivers everything you need for production APIs out of the box—built-in <strong>TypeBox &amp; Zod validation</strong>, <strong>end-to-end type safety</strong> (<code>bareClient</code>), <strong>auto-generated OpenAPI 3.1</strong>, <strong>native WebSockets</strong>, <strong>JSON-RPC 2.0</strong>, <strong>resilience primitives</strong>, and <strong>zero-trust security</strong>—powered by a JIT-compiled O(1) router and LIFO object pooling.</i></p>
6
6
 
7
7
  <p>
8
8
  <a href="https://www.npmjs.com/package/barejs">
@@ -20,6 +20,23 @@
20
20
  </p>
21
21
  </div>
22
22
 
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
+
23
40
  ---
24
41
 
25
42
  ## 📊 Benchmarks: Multi-Scenario & Real-World Performance
@@ -28,17 +45,17 @@ All benchmark numbers below are **automatically generated on every push to `main
28
45
 
29
46
  <!-- MARKER: MULTI_BENCH_START -->
30
47
 
31
- | Scenario | **BareJS** 🏆 | **ElysiaJS** | **Hono** |
48
+ | Scenario | **BareJS** | **ElysiaJS** | **Hono** |
32
49
  | :--- | :---: | :---: | :---: |
33
- | **1. 100 Routes + Dynamic Params** | **`532 ns`**<br><sub>`p99: 2.99 µs`</sub> | `899 ns`<br><sub>`p99: 4.41 µs`</sub> | `2.13 µs`<br><sub>`p99: 9.98 µs`</sub> |
34
- | **2. 10 Middlewares + Deep Path** | **`529 ns`**<br><sub>`p99: 3.01 µs`</sub> | `887 ns`<br><sub>`p99: 4.20 µs`</sub> | `2.51 µs`<br><sub>`p99: 10.51 µs`</sub> |
35
- | **3. POST JSON + Schema Validation** | **`1.71 µs`**<br><sub>`p99: 7.36 µs`</sub> | `2.25 µs`<br><sub>`p99: 9.77 µs`</sub> | `2.29 µs`<br><sub>`p99: 11.39 µs`</sub> |
36
- | **4. Async Handler + Query Parsing** | **`970 ns`**<br><sub>`p99: 3.94 µs`</sub> | `1.11 µs`<br><sub>`p99: 4.30 µs`</sub> | `1.59 µs`<br><sub>`p99: 7.08 µs`</sub> |
37
- | **5. Response Schema Secret Stripping** | **`485 ns`**<br><sub>`p99: 2.92 µs`</sub> | `799 ns`<br><sub>`p99: 3.63 µs`</sub> | — |
38
- | **6. SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | **`14.96 µs`**<br><sub>`p99: 23.58 µs`</sub> | `15.11 µs`<br><sub>`p99: 24.29 µs`</sub> | `18.11 µs`<br><sub>`p99: 35.08 µs`</sub> |
39
- | **7. SQLite Write (`POST` + Validate + `INSERT`)** | **`5.27 µs`**<br><sub>`p99: 14.31 µs`</sub> | `6.39 µs`<br><sub>`p99: 17.90 µs`</sub> | `8.32 µs`<br><sub>`p99: 26.56 µs`</sub> |
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> |
40
57
 
41
- > Last Updated: 2026-11-20 (github action)
58
+ > Last Updated: 2026-11-24 (github action)
42
59
 
43
60
  <!-- MARKER: MULTI_BENCH_END -->
44
61
 
@@ -48,38 +65,17 @@ All benchmark numbers below are **automatically generated on every push to `main
48
65
 
49
66
  | Framework | Latency | Speed |
50
67
  | :--- | :--- | :--- |
51
- | **BareJS** | **0.52 µs** | **Baseline** |
52
- | Elysia | 0.85 µs | 1.64x slower |
53
- | Hono | 3.30 µs | 6.32x slower |
68
+ | **BareJS** | **0.75 µs** | **Baseline** |
69
+ | Elysia | 0.92 µs | 1.22x slower |
70
+ | Hono | 3.16 µs | 4.20x slower |
54
71
 
55
- > Last Updated: 2026-11-20 (github action)
72
+ > Last Updated: 2026-11-24 (github action)
56
73
 
57
74
  <!-- MARKER: PERFORMANCE_TABLE_END -->
58
75
 
59
- > Verified with **401 Automated Tests (6,129 assertions)** and **100.00% Function & 100.00% Line Coverage**.
60
- >
61
76
  > [!TIP]
62
77
  > **View our [Continuous Benchmark Dashboard](https://xarhang.github.io/bareJS/dev/benchmarks/)** for historical data and detailed performance trends.
63
78
 
64
- > [!TIP]
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.
66
-
67
- ---
68
-
69
- ## 🚀 Key Features
70
-
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.
72
- * **$O(1)$ Radix Jump-Table Router**: Compiles static branches, dynamic `:params`, and catch-all wildcards (`/*`) into inline `switch` jump-tables.
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.
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.
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.
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.
77
- * **Concurrency-Safe Object Pooling**: Recycles `Context` instances via a LIFO free-list stack with automatic cleanup on release—zero cross-request state leakage.
78
- * **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`.
79
- * **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`.
80
- * **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()`.
81
- * **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`.
82
-
83
79
  ---
84
80
 
85
81
  ## 🛠️ Installation & Quick Start
@@ -107,6 +103,25 @@ app.get('/assets/*', (ctx: Context) => ({ path: ctx.params['*'] }));
107
103
  app.listen(3000);
108
104
  ```
109
105
 
106
+ ### 🌐 Multi-Runtime (Bun, Node.js, Deno)
107
+
108
+ BareJS selects its runtime driver **once at startup**—preserving 100% zero-overhead native speed on Bun while running the exact same app on Node.js (`>=20`) and Deno:
109
+
110
+ ```typescript
111
+ // Bun (Native Mode — default)
112
+ import { BareJS } from 'barejs';
113
+ app.listen(3000);
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));
121
+ ```
122
+
123
+ > Optional peer dependencies on Node.js: install `ws` if using `app.ws()`, and `@node-rs/argon2` (or `bcryptjs`) if using `Hash`.
124
+
110
125
  ---
111
126
 
112
127
  ## 📘 Comprehensive Guide
@@ -187,6 +202,18 @@ app.post('/upload', async (ctx) => {
187
202
  uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type }))
188
203
  };
189
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
+ });
190
217
  ```
191
218
 
192
219
  ---
@@ -272,6 +299,7 @@ app.use({
272
299
 
273
300
  // Server Lifecycle & Error Masking
274
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
275
303
  app.onStop(async () => console.log('Cleaned up resources'));
276
304
  app.onError((err, ctx) => ctx.status(err.status || 500).json({
277
305
  status: 'error',
@@ -370,6 +398,7 @@ app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
370
398
  | `ctx.query` / `ctx.getQuery(k)` | Lazy, prototype-pollution-safe parsed query parameters. |
371
399
  | `await ctx.jsonBody(maxBytes?)` | Parses & caches JSON body (enforces `413` limit, default 1MB). |
372
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). |
373
402
  | `ctx.cookies` | Lazy parsed request cookies (`Record<string, string>`). |
374
403
  | `await ctx.setCookie(k, v, opts?)` | Sets a cookie (`HttpOnly; SameSite=Lax` default, optional HMAC `secret`). |
375
404
  | `await ctx.getSignedCookie(k, s)` | Verifies HMAC-SHA256 signed cookie in constant time. |
@@ -393,7 +422,7 @@ app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
393
422
  | Variable / File | Default | Description |
394
423
  | :--- | :--- | :--- |
395
424
  | `bare.config.ts` | Optional | Centralized config for `port` and Argon2/bcrypt `hash` parameters. |
396
- | `poolSize` | `1024` | `new BareJS(poolSize)` — rounded up to power of 2 for $O(1)$ pooling. |
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. |
397
426
  | `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces and disable startup banner. |
398
427
 
399
428
  ---