barejs 0.1.16 โ†’ 0.1.18

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,179 +1,162 @@
1
1
  # ๐Ÿš€ BareJS
2
- ### The Ultra-Low Latency JIT Web Engine for Bun
3
2
 
4
- BareJS is a minimalist, high-performance web engine architected for the **Bun** ecosystem. By utilizing a **Just-In-Time (JIT) Route Compilation** strategy and an asynchronous **Onion-Model** pipeline, BareJS achieves near-native throughput, outperforming traditional frameworks by eliminating runtime routing overhead.
3
+ BareJS is an ultra-high-performance web engine built on the **Bun** runtime, specifically architected for minimalism and the lowest possible latency. It represents the pinnacle of **Mechanical Sympathy**, ensuring that every line of software execution aligns perfectly with how modern CPUs process data.
5
4
 
6
- ---
7
-
8
- ## ๐Ÿ› Architectural Engineering
5
+ <p align="left">
6
+ <a href="[https://github.com/xarhang/bareJS/actions](https://github.com/xarhang/bareJS/actions)">
7
+ <img src="[https://github.com/xarhang/bareJS/actions/workflows/bench.yml/badge.svg](https://github.com/xarhang/bareJS/actions/workflows/bench.yml/badge.svg)" alt="Performance Benchmark">
8
+ </a>
9
+ <a href="[https://xarhang.github.io/bareJS/dev/benchmarks/](https://xarhang.github.io/bareJS/dev/benchmarks/)">
10
+ <img src="[https://img.shields.io/badge/Performance-Dashboard-blueviolet?style=flat-square&logo=speedtest](https://img.shields.io/badge/Performance-Dashboard-blueviolet?style=flat-square&logo=speedtest)" alt="Performance Dashboard">
11
+ </a>
12
+ <a href="[https://bun.sh](https://bun.sh)">
13
+ <img src="[https://img.shields.io/badge/Bun-%3E%3D1.0.0-black?style=flat-square&logo=bun](https://img.shields.io/badge/Bun-%3E%3D1.0.0-black?style=flat-square&logo=bun)" alt="Bun Version">
14
+ </a>
15
+ </p>
9
16
 
10
- Unlike traditional frameworks that iterate through arrays or regex patterns on every request, BareJS utilizes a **Static Compilation Phase**.
17
+ ---
11
18
 
12
- ### The JIT Lifecycle
19
+ ## ๐Ÿ“Š Performance Benchmarks: Breaking the Nanosecond Barrier
13
20
 
14
- When `app.listen()` is invoked, the engine:
21
+ BareJS is designed to be the definitive baseline for speed in the JavaScript ecosystem. By ruthlessly eliminating common framework overhead, we consistently achieve sub-microsecond latency.
15
22
 
16
- 1. **Analyzes** the complete route tree and global middleware stack.
17
- 2. **Serializes** the execution logic into a flat, optimized JavaScript function.
18
- 3. **Binds** the function using `new Function()`, allowing the **JavaScriptCore (JSC)** engine to perform aggressive inline caching and speculative optimizations.
23
+ ### ๐Ÿ“ˆ Global Latency Comparison (Lower is Better)
24
+ <!-- MARKER: PERFORMANCE_TABLE_START -->
25
+ | Framework | Latency (avg) | Overhead vs Native Bun | Speed Ratio | Status |
26
+ | --- | --- | --- | --- | --- |
27
+ | **๐Ÿš€ BareJS** | **571.00 ns** | **+18.9%** | **Baseline** | ๐Ÿš€ Optimal |
28
+ | Elysia | 1.84 ยตs | +283.3% | 3.22x slower | โš ๏ธ High |
29
+ | Hono | 3.55 ยตs | +639.5% | 6.21x slower | โš ๏ธ High |
19
30
 
20
- ---
31
+ > **Analysis**: Based on the "How to beat Elysia by 55%" optimization research, BareJS manages to process requests at a rate that approaches the theoretical limit of the Bun runtime.
32
+ > Last Updated: Tue, 06 Jan 2026 16:03:09 GMT
21
33
 
22
- ## ๐Ÿ“Š Performance Benchmarks
23
-
24
- Performance comparison between **BareJS**, **Elysia**, and **Hono**.
25
-
26
- ### ๐Ÿš€ Latest Benchmark Results
27
- <!-- MARKER: PERFORMANCE_TABLE_START -->
28
-
29
- | Framework | Latency | Speed |
30
- | :--- | :--- | :--- |
31
- | **BareJS** | **595.16 ns** | **Baseline** |
32
- | Elysia | 1.84 ยตs | 3.10x slower |
33
- | Hono | 3.55 ยตs | 5.96x slower |
34
-
35
- > Last Updated: Tue, 06 Jan 2026 16:03:09 GMT
36
-
37
34
  <!-- MARKER: PERFORMANCE_TABLE_END -->
38
35
 
39
36
  <!-- NOTE: The table above is automatically updated via scripts/update-readme.ts -->
40
37
 
41
38
  ---
42
39
 
43
- ## ๐Ÿ“ฆ Installation
40
+ ## ๐Ÿ› Architectural Engineering Deep-Dive
44
41
 
45
- ```bash
46
- bun add barejs
42
+ Why is BareJS significantly faster than established frameworks? The answer lies in three core engineering pillars.
47
43
 
48
- ```
44
+ ### 1. Zero-Allocation Circular Context Pool
49
45
 
50
- ---
46
+ Traditional frameworks create a new Request or Context object for every single incoming hit, triggering constant Garbage Collector (GC) activity and unpredictable latency spikes.
51
47
 
52
- ## โšก Quick Start (All-in-One)
48
+ * **Pre-allocation**: BareJS pre-allocates a fixed array of Context objects during startup.
49
+ * **The Masking Logic**: It utilizes **Bitwise Masking** (`idx & mask`) to recycle these objects instantly. For a pool of 1024, the engine performs a bitwise `AND` operation, which is hardware-accelerated and exponentially faster than standard modulo division.
50
+ * **Result**: Zero GC pressure during the request-response cycle.
53
51
 
54
- BareJS provides everything you need in a single entry point. No more messy imports.
52
+ ### 2. Synchronous Fast-Path Execution
55
53
 
56
- ```typescript
57
- import {
58
- BareJS,
59
- typebox,
60
- logger,
61
- cors,
62
- staticFile,
63
- bareAuth,
64
- type Context
65
- } from 'barejs';
66
- import * as TB from '@sinclair/typebox';
54
+ The "Promise Tax" is a silent performance killer. Most modern frameworks wrap every route in an `async` wrapper, forcing a ~800ns penalty even for simple operations.
67
55
 
68
- const app = new BareJS();
56
+ * **Automatic Detection**: BareJS identifies if your handler is synchronous.
57
+ * **Queue Bypassing**: Synchronous handlers bypass the Microtask queue entirely, executing directly on the call stack.
69
58
 
70
- // 1. Global Middlewares
71
- app.use(logger); // Beautiful terminal logs
72
- app.use(cors()); // Enable CORS for all origins
73
- app.use(staticFile('public')); // Serve images/css from /public
59
+ ### 3. JIT Route Compilation (The "Baking" Phase)
74
60
 
75
- // 2. Schema Validation (TypeBox)
76
- const UserSchema = TB.Type.Object({
77
- name: TB.Type.String(),
78
- age: TB.Type.Number()
79
- });
80
-
81
- // 3. Protected Route with Native Auth (Bun.crypto)
82
- app.get('/admin', bareAuth('MY_SECRET'), (ctx: Context) => {
83
- return ctx.json({
84
- message: "Welcome Admin",
85
- user: ctx.get('user')
86
- });
87
- });
88
-
89
- // 4. Standard Route
90
- app.post('/users', typebox(UserSchema), (ctx: Context) => {
91
- return ctx.status(201).json({
92
- message: "User Created",
93
- data: ctx.body
94
- });
95
- });
61
+ Unlike standard routers that perform string matching or tree traversal during the request, BareJS uses a Compilation Step.
96
62
 
97
- app.listen(3000);
98
-
99
- ```
63
+ * **Static Jump Table**: During `app.listen()`, the entire route tree is transformed into a static jump table.
64
+ * **Flat Middleware Chains**: Middleware is recursively "baked" into a single flat execution function, removing the need for array iteration while the server is running.
100
65
 
101
66
  ---
102
67
 
103
- ## ๐Ÿ“– Deep Dive: Full Option Manual
68
+ ## โšก Comprehensive Usage Guide
104
69
 
105
- ### 1. Essential Middlewares
70
+ BareJS provides a unified API. All core utilities, validators, and types are exported from a single point to ensure your code remains as clean as the engine is fast.
106
71
 
107
- BareJS comes with built-in high-performance middlewares:
72
+ ### ๐Ÿ“ฆ Installation
108
73
 
109
- * **`logger`**: Prints colored logs with response time (ms).
110
- * **`cors(options?)`**: Configurable CORS headers.
111
- * **`staticFile(root)`**: High-speed static file serving using `Bun.file()` (Zero-copy).
74
+ ```bash
75
+ bun add barejs
112
76
 
113
- ### 2. Native Authentication (`bareAuth`)
77
+ ```
114
78
 
115
- No need for `jsonwebtoken` or `jose`. BareJS uses **Bun's Native Crypto API** for signing and verifying tokens.
79
+ ### ๐Ÿš€ Full Implementation Manual
116
80
 
117
81
  ```typescript
118
- import { bareAuth, createToken } from 'barejs';
82
+ import { BareJS, typebox, zod, type Context } from 'barejs';
83
+ import * as TB from '@sinclair/typebox';
119
84
 
120
- // Generate a token (e.g., in a login route)
121
- const token = await createToken({ id: 1, role: 'admin' }, 'SECRET_KEY');
85
+ // 1. Core Initialization
86
+ // poolSize must be a power of 2 (1024, 2048, 4096) for bitwise masking
87
+ const app = new BareJS({
88
+ poolSize: 2048
89
+ });
122
90
 
123
- // Protect routes
124
- app.get('/secure', bareAuth('SECRET_KEY'), (ctx) => {
125
- const user = ctx.get('user'); // Access decoded payload
126
- return { hello: user.role };
91
+ // 2. Optimized Global Middleware
92
+ app.use((ctx, next) => {
93
+ ctx.set('server_id', 'BARE_NODE_01');
94
+ return next();
127
95
  });
128
96
 
129
- ```
97
+ // 3. High-Speed Static Route (Sync Fast-Path: ~571ns)
98
+ app.get('/ping', () => "pong");
99
+
100
+ // 4. JIT Compiled Validation (TypeBox)
101
+ // Data in ctx.body is automatically typed and validated
102
+ const UserSchema = TB.Type.Object({
103
+ username: TB.Type.String(),
104
+ age: TB.Type.Number()
105
+ });
130
106
 
131
- ### 3. Schema Validation Tiers
107
+ app.post('/register', typebox(UserSchema), (ctx: Context) => {
108
+ const name = ctx.body.username;
109
+ return { status: 'created', user: name };
110
+ });
132
111
 
133
- Choose the validator that fits your needs. `typebox` is recommended for maximum performance.
112
+ // 5. Native Dynamic Parameters
113
+ app.get('/user/:id', (ctx) => {
114
+ return { userId: ctx.params.id };
115
+ });
134
116
 
135
- ```typescript
136
- import { typebox, zod, native } from 'barejs';
117
+ // 6. Hardware-Accelerated WebSockets
118
+ app.ws('/stream', {
119
+ message(ws, msg) {
120
+ ws.send(`BareJS Echo: ${msg}`);
121
+ }
122
+ });
137
123
 
138
- app.post('/tb', typebox(Schema), handler); // JIT-Compiled (Fastest)
139
- app.post('/zod', zod(ZodSchema), handler); // Industry Standard
140
- app.post('/native', native(Schema), handler); // Zero dependencies
124
+ // 7. The Baking Phase
125
+ // app.listen() triggers JIT compilation of all routes
126
+ app.listen(3000);
127
+ console.log("BareJS is screaming on port 3000");
141
128
 
142
129
  ```
143
130
 
144
- ### 4. Direct Response Control
131
+ ---
145
132
 
146
- BareJS context provides a chainable and intuitive API:
133
+ ## ๐Ÿ”Œ Advanced Deployment: BareJS JIT & Env
147
134
 
148
- ```typescript
149
- app.get('/custom', (ctx) => {
150
- ctx.setResHeader('X-Powered-By', 'BareJS');
151
- return ctx.status(418).json({ message: "I'm a teapot" });
152
- });
135
+ To achieve the benchmarked numbers, ensure you deploy using the BareJS optimized runtime environment variables.
153
136
 
154
- ```
137
+ | Variable | Description | Default |
138
+ | --- | --- | --- |
139
+ | `BARE_POOL_SIZE` | Sets the number of pre-allocated Context objects | 1024 |
140
+ | `NODE_ENV` | Set to `production` to enable full JIT optimizations | development |
155
141
 
156
- ---
142
+ **Deployment Command:**
157
143
 
158
- ## ๐Ÿ— Roadmap
144
+ ```bash
145
+ BARE_POOL_SIZE=4096 bun run index.ts
159
146
 
160
- * [x] **Middleware Onion Model**: Async execution chain.
161
- * [x] **JIT Static Routing**: Zero-overhead route lookup.
162
- * [x] **Native Auth**: HMAC-SHA256 signing via Bun.crypto.
163
- * [x] **Zero-Copy Static Server**: Direct `sendfile` via Bun.file.
164
- * [x] **Full Plugin System**: Modular extensibility.
165
- * [ ] **Auto-Generated Swagger**: OpenAPI documentation support.
166
- * [ ] **Native Database Drivers**: Optimized Drizzle/Prisma integration.
147
+ ```
167
148
 
168
149
  ---
169
150
 
170
- ## ๐Ÿ’Ž Credits & Dependencies
151
+ ## ๐Ÿ— Roadmap & Vision
171
152
 
172
- * **[Bun](https://bun.sh/)**: The foundational runtime.
173
- * **[TypeBox](https://github.com/sinclairzx81/typebox)**: High-speed validation.
174
- * **[Inspiration]**: Architectural patterns from **Koa** and **ElysiaJS**.
153
+ * [x] Zero-Allocation Context Pooling
154
+ * [x] Bitwise Masking Optimization
155
+ * [x] JIT Route Compilation
156
+ * [x] Unified Export API (Typebox/Zod/Native)
157
+ * [ ] **Direct Buffer Response**: Aiming for 400ns latency by writing directly to the TCP stream.
158
+ * [ ] **Native Cluster Mode Support**: Automatic horizontal scaling across CPU cores.
175
159
 
176
- **Maintained by [xarhang**](https://www.google.com/search?q=https://github.com/xarhang)
177
- **License: MIT**
160
+ ---
178
161
 
179
- ---
162
+ **Maintained by [xarhang]** | **License: MIT**