nextrush 2.0.1 → 3.0.0

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,1356 +1,235 @@
1
- <div align="center">
1
+ # NextRush
2
2
 
3
- # 🚀 NextRush v2
3
+ > Minimal, modular, high-performance Node.js framework
4
4
 
5
- **Modern, Type-Safe Web Framework for Node.js**
5
+ [![npm version](https://img.shields.io/npm/v/nextrush.svg)](https://www.npmjs.com/package/nextrush)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![Node.js](https://img.shields.io/badge/Node.js-≥22-339933?logo=node.js)](https://nodejs.org)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-3178C6?logo=typescript)](https://www.typescriptlang.org)
6
9
 
7
- _Koa-style Context • Express-inspired API • Enterprise Features Built-in_
10
+ ## Why NextRush?
8
11
 
9
- [![npm version](https://img.shields.io/npm/v/nextrush?color=brightgreen&style=for-the-badge)](https://www.npmjs.com/package/nextrush)
10
- [![Node.js](https://img.shields.io/badge/Node.js-20+-339933?style=for-the-badge&logo=node.js&logoColor=white)](https://nodejs.org/)
11
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.8+-3178C6?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
12
- [![License](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE)
13
- [![Tests](https://img.shields.io/badge/Tests-1461%20Passing-brightgreen?style=for-the-badge)](https://github.com/0xTanzim/nextrush)
14
- [![Zero Dependencies](https://img.shields.io/badge/Dependencies-0-brightgreen?style=for-the-badge)](https://github.com/0xTanzim/nextrush)
12
+ - **Fast** — 50-60% faster than Express, competes with Fastify and Hono
13
+ - **Minimal** — Core under 3,000 lines of code
14
+ - **Modular** — Install only what you need
15
+ - **Type-Safe** — Full TypeScript with zero `any`
16
+ - **Zero Dependencies** — No external runtime dependencies in core
15
17
 
16
- ```typescript
17
- import { createApp } from 'nextrush';
18
-
19
- const app = createApp();
20
-
21
- app.get('/hello', async ctx => {
22
- ctx.json({ message: 'Welcome to NextRush v2! 🎉' });
23
- });
24
-
25
- app.listen(3000);
26
- // Server running at http://localhost:3000
27
- ```
28
-
29
- [**📖 Documentation**](./docs) • [**🚀 Quick Start**](#-quick-start) • [**💡 Why NextRush?**](#-why-nextrush-v2)
30
-
31
- </div>
32
-
33
- ---
34
-
35
- ## 💡 Philosophy
36
-
37
- **NextRush v2 combines the best of three worlds**: Koa's elegant async context pattern, Express's intuitive helper methods, and Fastify's performance optimizations—all with **enterprise-grade features built directly into the core**.
38
-
39
- Unlike other frameworks that require dozens of plugins for production use, NextRush v2 includes security middleware, validation, templating, WebSocket support, and advanced logging out of the box. Choose your preferred API style: convenience methods, Express-like helpers, or Fastify-style configuration.
40
-
41
- **Built for teams that value type safety, developer experience, and production readiness without the plugin fatigue.**
42
-
43
- ---
44
-
45
- ## 🎯 Zero Dependencies Philosophy
46
-
47
- **NextRush v2 is built with ZERO runtime dependencies.** Every feature—from routing to WebSocket support—is implemented using only Node.js core modules.
48
-
49
- ### Why Zero Dependencies?
50
-
51
- - **🔒 Security** - No third-party vulnerabilities in your supply chain
52
- - **⚡ Faster Installs** - No dependency resolution, instant setup
53
- - **🛡️ Stability** - No breaking changes from external packages
54
- - **🔍 Full Control** - Every line of code is maintainable and auditable
55
- - **🚀 Performance** - Optimized for Node.js internals, no abstraction overhead
56
-
57
- ```bash
58
- # Check it yourself! Only devDependencies, ZERO runtime deps
59
- npm ls --production --depth=0
60
- # Result: (empty)
61
- ```
62
-
63
- **Every framework claims to be "lightweight." NextRush v2 proves it.**
64
-
65
- | Framework | Runtime Dependencies |
66
- | --------------- | ------------------------------------ |
67
- | **NextRush v2** | **0** ⭐ |
68
- | Express | 34+ packages |
69
- | Koa | 0 (but needs plugins for everything) |
70
- | Fastify | 20+ packages |
71
- | Hapi | 50+ packages |
72
-
73
- > **Built-in features without the dependency hell.** Security, validation, WebSocket, templates, logging, CQRS—all implemented with pure Node.js.
74
-
75
- ---
76
-
77
- ## 🎯 Why NextRush v2?
78
-
79
- NextRush v2 represents the evolution of Node.js web frameworks, synthesizing proven patterns from Express, Koa, and Fastify into a unified, type-safe framework with enterprise features integrated at the core.
80
-
81
- ### 🏆 Three API Styles, One Framework
82
-
83
- | **Convenience API** | **Enhanced API** | **Configuration API** |
84
- | ------------------- | ---------------- | --------------------- |
85
- | `ctx.json()` | `ctx.res.json()` | `{ handler, schema }` |
86
- | Clean & simple | Express-inspired | Fastify-style |
87
- | **Recommended** | Familiar pattern | Advanced use cases |
88
-
89
- ### ⚡ Performance That Scales
90
-
91
- - **Zero Dependencies** - Pure Node.js core, no third-party overhead
92
- - **13,261 RPS Average** - Competitive with established frameworks
93
- - **Optimized Router** - O(1) static path lookup, pre-compiled routes
94
- - **Memory Efficient** - ~60KB baseline, smallest footprint in class
95
- - **Smart Caching** - Template caching, efficient buffer management
96
- - **No Supply Chain Tax** - Every feature optimized for Node.js internals
97
-
98
- ### 🛡️ Enterprise Features Built-In
99
-
100
- Unlike other frameworks requiring extensive plugin ecosystems, NextRush v2 includes production-ready features in the core:
101
-
102
- ```typescript
103
- const app = createApp();
104
-
105
- // Security middleware (CORS, Helmet, Rate Limiting)
106
- app.use(app.cors({ origin: ['https://example.com'] }));
107
- app.use(app.helmet({ xssFilter: true }));
108
- app.use(app.rateLimiter({ max: 100, windowMs: 15 * 60 * 1000 }));
109
-
110
- // Smart body parser with auto-detection
111
- app.use(app.smartBodyParser({ maxSize: 10 * 1024 * 1024 }));
112
-
113
- // Advanced validation & sanitization
114
- const userData = validateRequest(ctx, userSchema);
115
- const cleanData = sanitizeInput(userData);
116
-
117
- // Custom error classes with contextual information
118
- throw new NotFoundError('User not found', {
119
- userId: ctx.params.id,
120
- suggestion: 'Verify the user ID is correct',
121
- });
122
-
123
- // Event-driven architecture (Simple + CQRS patterns)
124
- await app.events.emit('user.registered', { userId: user.id });
125
- await app.eventSystem.dispatch({ type: 'CreateUser', data: {...} });
126
-
127
- // Template engine with automatic XSS protection
128
- await ctx.render('profile.html', { user, isAdmin });
129
-
130
- // WebSocket support with room management
131
- wsApp.ws('/chat', socket => {
132
- socket.join('room1');
133
- socket.onMessage(data => wsApp.wsBroadcast(data, 'room1'));
134
- });
135
-
136
- // Structured logging with multiple transports
137
- ctx.logger.info('User action', { userId, action });
138
-
139
- // Dependency injection container
140
- const service = container.resolve('UserService');
141
- ```
142
-
143
- ### 🛡️ Type Safety First
144
-
145
- ```typescript
146
- // Full TypeScript integration with IntelliSense support
147
- import type { Context, Middleware, RouteHandler } from 'nextrush';
148
-
149
- app.get('/users/:id', async (ctx: Context) => {
150
- const userId: string = ctx.params.id; // Type-safe route parameters
151
- const userData: User = ctx.body; // Type-safe request body
152
- ctx.json({ user: userData }); // Type-safe response
153
- });
154
-
155
- // Type-safe middleware composition
156
- const authMiddleware: Middleware = async (ctx, next) => {
157
- ctx.state.user = await validateToken(ctx.headers.authorization);
158
- await next();
159
- };
160
- ```
161
-
162
- ### 🎭 Choose Your API Style
163
-
164
- ```typescript
165
- // Convenience Methods (Recommended)
166
- app.get('/users', async ctx => {
167
- ctx.json(await getUsers()); // Clean and concise
168
- });
169
-
170
- // Enhanced API (Express-inspired helpers)
171
- app.get('/users', async ctx => {
172
- ctx.res.json(await getUsers()); // Familiar Express-like methods
173
- });
174
-
175
- // Configuration API (Fastify-style)
176
- app.get('/users', {
177
- handler: async ctx => ctx.json(await getUsers()),
178
- schema: { response: { 200: UserSchema } },
179
- options: { tags: ['users'] },
180
- });
181
- ```
182
-
183
- ### 🌟 Core Features Comparison
184
-
185
- | Feature | NextRush v2 | Express | Fastify | Koa |
186
- | ----------------------------- | --------------- | --------------- | --------------- | ----------------- |
187
- | **Security Middleware** | Built-in | Plugin required | Plugin required | Plugin required |
188
- | **Validation & Sanitization** | Built-in | Plugin required | Built-in | Plugin required |
189
- | **Template Engine** | Built-in | Plugin required | Plugin required | Plugin required |
190
- | **WebSocket Support** | Built-in | Plugin required | Plugin required | Plugin required |
191
- | **Event System (CQRS)** | Dual system | Plugin required | Plugin required | Plugin required |
192
- | **Advanced Logging** | Plugin included | Plugin required | Plugin required | Plugin required |
193
- | **Error Classes** | 8 custom types | Basic | Basic | Basic |
194
- | **Dependency Injection** | Built-in | Plugin required | Plugin required | Plugin required |
195
- | **Smart Body Parser** | Auto-detection | Plugin required | Built-in | Plugin required |
196
- | **Static File Serving** | Plugin included | Built-in | Plugin required | Plugin required |
197
- | **TypeScript Support** | First-class | Community | First-class | Community |
198
- | **Dependencies** | **0** ⭐ | 34+ packages | 20+ packages | 0 (needs plugins) |
199
- | **Performance (RPS)** | ~13,261 | ~11,030 | ~22,717 | ~17,547 |
200
-
201
- ---
202
-
203
- ## ✨ Comprehensive Feature Set
204
-
205
- <table>
206
- <tr>
207
- <td width="50%">
208
-
209
- ### Modern Development
210
-
211
- - **TypeScript First** - Full type safety with IntelliSense
212
- - **Zero Dependencies** - Pure Node.js, minimal footprint
213
- - **ESM & CJS** - Universal module compatibility
214
- - **Plugin System** - Extensible architecture
215
- - **Smart Body Parser** - Auto-detection & zero-copy operations
216
- - **Template Engine** - Built-in HTML rendering with auto-escaping
217
-
218
- </td>
219
- <td width="50%">
18
+ ## This Package
220
19
 
221
- ### Production Ready
20
+ **`nextrush` is a meta package that re-exports the essentials:**
222
21
 
223
- - **Error Handling** - Custom error classes with context
224
- - **Advanced Logging** - Structured logs with multiple transports
225
- - **Security** - CORS, Helmet, Rate Limiting included
226
- - **Validation** - Schema validation & input sanitization
227
- - **Testing** - Test-friendly design, 1461 passing tests
228
- - **Static Files** - High-performance file serving
229
- - **Compression** - Gzip & Brotli support
22
+ - `createApp`, `Application` Create and manage application instances
23
+ - `createRouter`, `Router` Create and manage routers
24
+ - `listen`, `serve`, `createHandler` Start HTTP server (Node.js)
25
+ - `compose` Compose middleware
26
+ - Error classes (`HttpError`, `NotFoundError`, `BadRequestError`, `MethodNotAllowedError`, etc.)
27
+ - Error utilities (`createError`, `isHttpError`, `errorHandler`, `notFoundHandler`, `catchAsync`)
28
+ - TypeScript types (`Context`, `Middleware`, `Next`, `Plugin`, `RouteHandler`, `HttpMethod`, etc.)
29
+ - Constants (`VERSION`, `HttpStatus`, `ContentType`)
230
30
 
231
- </td>
232
- </tr>
233
- <tr>
234
- <td width="50%">
31
+ **Middleware and plugins are installed separately.** This is intentional — you only pay for what you use.
235
32
 
236
- ### Real-time & Events
237
-
238
- - **WebSocket Support** - RFC 6455 compliant implementation
239
- - **Room Management** - Built-in room system for grouping
240
- - **Broadcasting** - Efficient message delivery patterns
241
- - **Event System** - Simple events + CQRS/Event Sourcing
242
- - **Connection Pooling** - Scalable connection management
243
- - **Heartbeat** - Automatic connection health monitoring
244
- - **Pub/Sub** - Event-driven architecture support
245
-
246
- </td>
247
- <td width="50%">
248
-
249
- ### Developer Experience
250
-
251
- - **Enhanced Errors** - Contextual debugging information
252
- - **Request/Response Enhancers** - Express-inspired helpers
253
- - **Path Utilities** - URL & path manipulation tools
254
- - **Cookie Utilities** - Type-safe cookie management
255
- - **Dependency Injection** - Built-in DI container
256
- - **Dev Warnings** - Common mistake detection
257
- - **Performance Monitoring** - Built-in metrics collection
258
-
259
- </td>
260
- </tr>
261
- </table>
262
-
263
- ## 🚀 **Quick Start**
264
-
265
- ### Prerequisites
266
-
267
- - **Node.js**: >= 20.0.0
268
- - **pnpm**: >= 10.0.0 (recommended) or npm/yarn/bun
269
-
270
- ### Installation
33
+ ## Installation
271
34
 
272
35
  ```bash
273
- # pnpm (recommended)
274
36
  pnpm add nextrush
275
-
276
- # npm
277
- npm install nextrush
278
-
279
- # yarn
280
- yarn add nextrush
281
-
282
- # bun
283
- bun add nextrush
284
37
  ```
285
38
 
286
- ### Hello World
39
+ ## Quick Start
287
40
 
288
41
  ```typescript
289
- import { createApp } from 'nextrush';
42
+ import { createApp, createRouter, listen } from 'nextrush';
290
43
 
291
44
  const app = createApp();
45
+ const router = createRouter();
292
46
 
293
- app.get('/', async ctx => {
294
- ctx.json({
295
- message: 'Hello NextRush v2! 🚀',
296
- timestamp: new Date().toISOString(),
297
- });
47
+ router.get('/', (ctx) => {
48
+ ctx.json({ message: 'Hello NextRush!' });
298
49
  });
299
50
 
300
- app.listen(3000, () => {
301
- console.log('🚀 Server running on http://localhost:3000');
302
- });
303
- ```
304
-
305
- ### 30-Second API
306
-
307
- ```typescript
308
- import { createApp } from 'nextrush';
309
-
310
- const app = createApp({
311
- cors: true, // Enable CORS
312
- debug: true, // Development mode
313
- });
51
+ app.route('/', router);
314
52
 
315
- // Middleware
316
- app.use(async (ctx, next) => {
317
- console.log(`📝 ${ctx.method} ${ctx.path}`);
318
- await next();
319
- });
320
-
321
- // Routes with three different styles
322
- app.get('/simple', async ctx => {
323
- ctx.json({ style: 'convenience' });
324
- });
325
-
326
- app.get('/express', async ctx => {
327
- ctx.res.json({ style: 'express-like' });
328
- });
329
-
330
- app.post('/fastify', {
331
- handler: async ctx => ctx.json({ style: 'fastify-style' }),
332
- schema: {
333
- body: {
334
- type: 'object',
335
- properties: { name: { type: 'string' } },
336
- },
337
- },
338
- });
339
-
340
- app.listen(3000);
53
+ listen(app, 3000);
341
54
  ```
342
55
 
343
- ---
344
-
345
- ## 🎭 Multiple API Styles
56
+ ## Performance
346
57
 
347
- NextRush v2 is **Koa-style at its core** with **three distinct API styles**—choose the approach that best fits your team's preferences:
58
+ Benchmark snapshot from a single lab machine (Intel i5-8300H, 8 cores) running Node.js v25.1.0.
59
+ See https://nextrush.dev/docs/performance for methodology, versions, and reproducible scripts.
348
60
 
349
- ### Convenience Methods _(Recommended)_
61
+ | Framework | Hello World | POST JSON | Mixed Workload |
62
+ | --------------- | -------------- | -------------- | -------------- |
63
+ | Fastify | 48,045 RPS | 21,412 RPS | 48,493 RPS |
64
+ | **NextRush v3** | **43,268 RPS** | **20,438 RPS** | **43,283 RPS** |
65
+ | Hono | 37,476 RPS | 12,625 RPS | 38,759 RPS |
66
+ | Koa | 34,683 RPS | 17,664 RPS | 35,566 RPS |
67
+ | Express | 23,739 RPS | 14,417 RPS | 23,783 RPS |
350
68
 
351
- ```typescript
352
- app.get('/users/:id', async ctx => {
353
- const user = await findUser(ctx.params.id);
69
+ > Performance varies by hardware. See [Performance](https://nextrush.dev/docs/performance) for methodology and numbers.
354
70
 
355
- if (!user) {
356
- ctx.json({ error: 'User not found' }, 404);
357
- return;
358
- }
71
+ ## Adding Middleware
359
72
 
360
- ctx.json(user); // Clean and concise
361
- });
362
-
363
- app.post('/users', async ctx => {
364
- const user = await createUser(ctx.body);
365
- ctx.json(user, 201); // Status code as second parameter
366
- });
367
- ```
368
-
369
- ### Enhanced API _(Express-inspired)_
370
-
371
- ```typescript
372
- app.get('/users/:id', async ctx => {
373
- const user = await findUser(ctx.params.id);
73
+ Install what you need:
374
74
 
375
- if (!user) {
376
- ctx.res.status(404).json({ error: 'User not found' });
377
- return;
378
- }
379
-
380
- ctx.res.json(user); // Familiar Express-style methods
381
- });
382
-
383
- app.post('/users', async ctx => {
384
- const user = await createUser(ctx.body);
385
- ctx.res.status(201).json(user); // Chainable method calls
386
- });
387
- ```
388
-
389
- ### Configuration API _(Fastify-style)_
390
-
391
- ```typescript
392
- app.get('/users/:id', {
393
- handler: async ctx => {
394
- const user = await findUser(ctx.params.id);
395
- ctx.json(user || { error: 'Not found' }, user ? 200 : 404);
396
- },
397
- schema: {
398
- params: {
399
- type: 'object',
400
- properties: { id: { type: 'string', pattern: '^[0-9]+$' } },
401
- },
402
- response: {
403
- 200: { type: 'object', properties: { id: { type: 'string' } } },
404
- 404: { type: 'object', properties: { error: { type: 'string' } } },
405
- },
406
- },
407
- options: {
408
- name: 'getUser',
409
- description: 'Retrieve user by ID',
410
- tags: ['users'],
411
- },
412
- });
75
+ ```bash
76
+ pnpm add @nextrush/cors @nextrush/body-parser
413
77
  ```
414
78
 
415
- ---
416
-
417
- ## 🌐 Real-time WebSocket Support
418
-
419
- Production-ready WebSocket server with zero dependencies and full TypeScript support:
420
-
421
79
  ```typescript
422
- import { createApp, WebSocketPlugin, withWebSocket } from 'nextrush';
423
- import type { WSConnection } from 'nextrush';
80
+ import { createApp, listen } from 'nextrush';
81
+ import { cors } from '@nextrush/cors';
82
+ import { json } from '@nextrush/body-parser';
424
83
 
425
84
  const app = createApp();
426
85
 
427
- // Install WebSocket plugin
428
- const wsPlugin = new WebSocketPlugin({
429
- path: '/ws',
430
- heartbeatMs: 30000,
431
- maxConnections: 1000,
432
- verifyClient: async req => {
433
- // Optional: Custom authentication
434
- const token = new URL(req.url || '', 'http://localhost').searchParams.get(
435
- 'token'
436
- );
437
- return !!token;
438
- },
439
- });
440
- wsPlugin.install(app);
441
-
442
- // ✅ Get typed WebSocket application (Perfect IntelliSense!)
443
- const wsApp = withWebSocket(app);
444
-
445
- // Simple echo server with full type safety
446
- wsApp.ws('/echo', (socket: WSConnection) => {
447
- socket.send('Welcome!');
448
-
449
- socket.onMessage((data: string | Buffer) => {
450
- socket.send(`Echo: ${data}`);
451
- });
452
- });
453
-
454
- // Room-based chat system
455
- wsApp.ws('/chat', (socket: WSConnection) => {
456
- const room = 'general';
457
-
458
- socket.join(room);
459
- socket.send(`Joined room: ${room}`);
86
+ app.use(cors());
87
+ app.use(json());
460
88
 
461
- socket.onMessage((data: string | Buffer) => {
462
- // Broadcast to all users in room using app-level method
463
- wsApp.wsBroadcast(data.toString(), room);
464
- });
465
-
466
- socket.onClose((code, reason) => {
467
- console.log(`Client disconnected: ${code} - ${reason}`);
468
- });
89
+ app.use((ctx) => {
90
+ ctx.json({ body: ctx.body });
469
91
  });
470
92
 
471
- app.listen(3000);
472
- ```
473
-
474
- **Client Usage:**
475
-
476
- ```javascript
477
- // Browser WebSocket client
478
- const ws = new WebSocket('ws://localhost:3000/chat');
479
- ws.onopen = () => {
480
- console.log('Connected!');
481
- ws.send('Hello everyone!');
482
- };
483
- ws.onmessage = event => console.log('Received:', event.data);
484
- ws.onerror = error => console.error('Error:', error);
485
- ws.onclose = () => console.log('Disconnected');
486
-
487
- // With authentication token
488
- const wsAuth = new WebSocket('ws://localhost:3000/echo?token=your-jwt-token');
489
- ```
490
-
491
- ---
492
-
493
- ## 🛡️ Built-in Security Middleware
494
-
495
- ```typescript
496
- import { createApp } from 'nextrush';
497
-
498
- const app = createApp();
499
-
500
- // CORS - Cross-Origin Resource Sharing
501
- app.use(
502
- app.cors({
503
- origin: ['https://example.com'],
504
- credentials: true,
505
- methods: ['GET', 'POST', 'PUT', 'DELETE'],
506
- })
507
- );
508
-
509
- // Helmet - Security headers
510
- app.use(
511
- app.helmet({
512
- contentSecurityPolicy: true,
513
- xssFilter: true,
514
- noSniff: true,
515
- frameguard: { action: 'deny' },
516
- })
517
- );
518
-
519
- // Rate Limiting - DDoS protection
520
- app.use(
521
- app.rateLimiter({
522
- windowMs: 15 * 60 * 1000, // 15 minutes
523
- max: 100, // 100 requests per window
524
- message: 'Too many requests',
525
- })
526
- );
527
-
528
- // Request ID - Request tracing
529
- app.use(app.requestId());
530
-
531
- // Response Timer - Performance monitoring
532
- app.use(app.timer());
533
- ```
534
-
535
- **Included Security Features:**
536
-
537
- - **CORS** - Flexible origin control and credential handling
538
- - **Helmet** - 15+ security headers preconfigured
539
- - **Rate Limiting** - IP-based request throttling
540
- - **XSS Protection** - Automatic escaping in template engine
541
- - **Request Tracing** - Unique identifiers for request tracking
542
- - **Response Timing** - Performance measurement headers
543
-
544
- ---
545
-
546
- ## 📝 **Comprehensive Validation System**
547
-
548
- ## 📏 Comprehensive Validation System
549
-
550
- ```typescript
551
- import { validateRequest, sanitizeInput, ValidationError } from 'nextrush';
552
-
553
- // Define validation schema
554
- const userSchema = {
555
- name: {
556
- required: true,
557
- type: 'string',
558
- minLength: 2,
559
- maxLength: 50,
560
- },
561
- email: {
562
- required: true,
563
- type: 'email',
564
- },
565
- age: {
566
- type: 'number',
567
- min: 18,
568
- max: 120,
569
- },
570
- role: {
571
- enum: ['user', 'admin', 'moderator'],
572
- },
573
- };
574
-
575
- app.post('/users', async ctx => {
576
- try {
577
- // Validate request against schema
578
- const userData = validateRequest(ctx, userSchema);
579
-
580
- // Sanitize user input
581
- const cleanData = sanitizeInput(userData);
582
-
583
- const user = await createUser(cleanData);
584
- ctx.json({ user }, 201);
585
- } catch (error) {
586
- if (error instanceof ValidationError) {
587
- ctx.json(
588
- {
589
- error: 'Validation failed',
590
- details: error.errors,
591
- },
592
- 400
593
- );
594
- }
595
- }
596
- });
93
+ listen(app, 3000);
597
94
  ```
598
95
 
599
- **Validation Capabilities:**
600
-
601
- - **Type Checking** - string, number, boolean, email, URL, and more
602
- - **Length Validation** - minLength, maxLength constraints
603
- - **Range Validation** - min, max for numeric values
604
- - **Pattern Matching** - Regular expression validation
605
- - **Enum Validation** - Restricted value sets
606
- - **Custom Validation** - Extensible validation functions
607
- - **XSS Prevention** - Automatic input sanitization
608
-
609
- 📚 **[Complete Validation Guide →](./docs/api/validation-utilities.md)**
610
-
611
- **Validation Features:**
612
-
613
- - **Type Checking** - string, number, boolean, email, URL, etc.
614
- - **Length Validation** - minLength, maxLength
615
- - **Range Validation** - min, max for numbers
616
- - **Pattern Matching** - Regex validation
617
- - **Enum Validation** - Allowed values
618
- - **Custom Validation** - Your own validation functions
619
- - **XSS Prevention** - Auto-sanitization
96
+ ## Class-Based Controllers
620
97
 
621
- 📚 **[Complete Validation Guide →](./docs/api/validation-utilities.md)**
98
+ Class-based APIs (decorators, DI, controllers) are available via the `nextrush/class` subpath:
622
99
 
623
- ---
100
+ - `nextrush` — Functional API (`createApp`, `createRouter`, `listen`, errors, types)
101
+ - `nextrush/class` — Class-based API (`Controller`, `Get`, `Service`, `controllersPlugin`, etc.)
624
102
 
625
- ## 🎨 Template Engine
103
+ The `nextrush/class` entry auto-imports `reflect-metadata`, so you can use decorators and DI without any extra setup:
626
104
 
627
- ```typescript
628
- import { createApp, TemplatePlugin } from 'nextrush';
629
-
630
- const app = createApp();
631
-
632
- // Setup template engine
633
- const templatePlugin = new TemplatePlugin({
634
- viewsDir: './views',
635
- cache: true,
636
- helpers: {
637
- formatDate: date => new Date(date).toLocaleDateString(),
638
- currency: value => `$${Number(value).toFixed(2)}`,
639
- },
640
- });
641
-
642
- templatePlugin.install(app);
643
-
644
- // Use templates
645
- app.get('/users/:id', async ctx => {
646
- const user = await getUser(ctx.params.id);
647
-
648
- await ctx.render('user-profile.html', {
649
- title: 'User Profile',
650
- user,
651
- isAdmin: user.role === 'admin',
652
- });
653
- });
654
- ```
655
-
656
- **views/user-profile.html:**
657
-
658
- ```html
659
- <!DOCTYPE html>
660
- <html>
661
- <head>
662
- <title>{{title}}</title>
663
- </head>
664
- <body>
665
- <h1>{{user.name}}</h1>
666
- <p>Email: {{user.email}}</p>
667
- <p>Joined: {{user.createdAt | formatDate}}</p>
668
-
669
- {{#if isAdmin}}
670
- <button>Admin Panel</button>
671
- {{/if}}
672
-
673
- <!-- Loop through items -->
674
- {{#each user.posts}}
675
- <article>
676
- <h2>{{this.title}}</h2>
677
- <p>{{this.excerpt}}</p>
678
- </article>
679
- {{/each}}
680
- </body>
681
- </html>
105
+ ```bash
106
+ pnpm add nextrush
682
107
  ```
683
108
 
684
- **Template Features:**
685
-
686
- - **Auto-escaping** - XSS protection by default
687
- - **Control Structures** - if/else, loops, with blocks
688
- - **Helpers** - Built-in & custom transformation functions
689
- - **Partials** - Reusable template components
690
- - **Layouts** - Consistent page structure
691
- - **Caching** - Fast production performance
692
-
693
- 📚 **[Template Engine Documentation →](./docs/api/template-plugin.md)**
694
-
695
- ---
696
-
697
- ## 🚨 Advanced Error Handling
698
-
699
109
  ```typescript
700
- import {
701
- HttpError,
702
- BadRequestError,
703
- UnauthorizedError,
704
- ForbiddenError,
705
- NotFoundError,
706
- ConflictError,
707
- UnprocessableEntityError,
708
- TooManyRequestsError,
709
- InternalServerError,
710
- } from 'nextrush';
711
-
712
- // Custom error classes with proper status codes
713
- app.get('/users/:id', async ctx => {
714
- const user = await db.user.findById(ctx.params.id);
715
-
716
- if (!user) {
717
- throw new NotFoundError('User not found', {
718
- userId: ctx.params.id,
719
- suggestion: 'Check the user ID',
720
- });
721
- }
722
-
723
- if (ctx.state.user.id !== user.id) {
724
- throw new ForbiddenError("Cannot access other user's data", {
725
- requestedUserId: ctx.params.id,
726
- currentUserId: ctx.state.user.id,
727
- });
728
- }
729
-
730
- ctx.json({ user });
731
- });
110
+ import { createApp, createRouter, listen } from 'nextrush';
111
+ import { controllersPlugin, Controller, Get, Service } from 'nextrush/class';
732
112
 
733
- // Global error handler
734
- app.use(async (ctx, next) => {
735
- try {
736
- await next();
737
- } catch (error) {
738
- if (error instanceof HttpError) {
739
- ctx.json(
740
- {
741
- error: error.message,
742
- code: error.code,
743
- details: error.details,
744
- },
745
- error.statusCode
746
- );
747
- return;
748
- }
749
-
750
- // Unexpected errors
751
- ctx.json({ error: 'Internal server error' }, 500);
113
+ @Service()
114
+ class GreetService {
115
+ greet() {
116
+ return { message: 'Hello!' };
752
117
  }
753
- });
754
- ```
755
-
756
- **Error Classes:**
757
-
758
- - **BadRequestError (400)** - Invalid request data
759
- - **UnauthorizedError (401)** - Authentication required
760
- - **ForbiddenError (403)** - Insufficient permissions
761
- - **NotFoundError (404)** - Resource not found
762
- - **ConflictError (409)** - Resource conflicts
763
- - **UnprocessableEntityError (422)** - Business rule violations
764
- - **TooManyRequestsError (429)** - Rate limit exceeded
765
- - **InternalServerError (500)** - Server errors
766
-
767
- 📚 **[Complete Error Handling Guide →](./docs/api/errors.md)**
768
-
769
- ---
770
-
771
- ## 🎪 Event-Driven Architecture
772
-
773
- NextRush v2 includes dual event systems: Simple Events (Express-style) + Advanced Event System (CQRS/Event Sourcing).
774
-
775
- ### Simple Events API _(Express-style)_
776
-
777
- ```typescript
778
- // Emit events
779
- await app.events.emit('user.registered', {
780
- userId: user.id,
781
- email: user.email,
782
- });
783
-
784
- // Listen to events
785
- app.events.on('user.registered', async data => {
786
- await sendWelcomeEmail(data.email);
787
- await createDefaultProfile(data.userId);
788
- await trackAnalytics('User Registered', data);
789
- });
790
-
791
- // One-time handlers
792
- app.events.once('app.ready', async () => {
793
- await warmupCache();
794
- await initializeServices();
795
- });
796
- ```
797
-
798
- ### Advanced Event System _(CQRS/Event Sourcing)_
799
-
800
- ```typescript
801
- // Define commands
802
- interface CreateUserCommand {
803
- type: 'CreateUser';
804
- data: { name: string; email: string };
805
- metadata: { id: string; timestamp: Date; correlationId: string };
806
118
  }
807
119
 
808
- // Register command handlers
809
- app.eventSystem.registerCommandHandler(
810
- 'CreateUser',
811
- async (command: CreateUserCommand) => {
812
- const user = await db.user.create(command.data);
813
-
814
- // Emit domain event
815
- await app.eventSystem.emit({
816
- type: 'user.created',
817
- data: { userId: user.id, email: user.email },
818
- timestamp: new Date(),
819
- metadata: {
820
- aggregateId: user.id,
821
- version: 1,
822
- },
823
- });
824
-
825
- return user;
826
- }
827
- );
828
-
829
- // Subscribe to domain events
830
- app.eventSystem.subscribe('user.created', async event => {
831
- await analytics.track('User Created', {
832
- userId: event.data.userId,
833
- correlationId: event.metadata.correlationId,
834
- });
835
- });
836
-
837
- // Execute commands with CQRS
838
- app.post('/users', async ctx => {
839
- const command: CreateUserCommand = {
840
- type: 'CreateUser',
841
- data: ctx.body,
842
- metadata: {
843
- id: crypto.randomUUID(),
844
- timestamp: new Date(),
845
- correlationId: ctx.id,
846
- },
847
- };
848
-
849
- const user = await app.eventSystem.dispatch(command);
850
- ctx.json({ user }, 201);
851
- });
852
- ```
853
-
854
- **Event System Features:**
855
-
856
- - **Simple Events** - Express-style emit/on/once patterns
857
- - **CQRS** - Command Query Responsibility Segregation
858
- - **Event Sourcing** - Domain event tracking and replay
859
- - **Saga Patterns** - Complex workflow orchestration
860
- - **Pub/Sub** - Event broadcasting capabilities
861
- - **Correlation IDs** - Request tracing across services
862
- - **Event Store** - Event history and replay functionality
863
-
864
- 📚 **[Complete Event System Guide →](./docs/api/events.md)**
865
-
866
- ---
867
-
868
- ## 📊 Advanced Logging Plugin
869
-
870
- ```typescript
871
- import { LoggerPlugin } from 'nextrush';
872
-
873
- // Configure advanced logging
874
- const loggerPlugin = new LoggerPlugin({
875
- level: 'info',
876
- format: 'json',
877
- transports: [
878
- {
879
- type: 'console',
880
- colorize: true,
881
- },
882
- {
883
- type: 'file',
884
- filename: 'logs/app.log',
885
- maxSize: 10485760, // 10MB
886
- maxFiles: 5,
887
- },
888
- {
889
- type: 'file',
890
- filename: 'logs/errors.log',
891
- level: 'error',
892
- maxSize: 10485760,
893
- },
894
- ],
895
- includeTimestamp: true,
896
- includeMetadata: true,
897
- });
120
+ @Controller('/api')
121
+ class HelloController {
122
+ constructor(private svc: GreetService) {}
898
123
 
899
- loggerPlugin.install(app);
900
-
901
- // Use in routes
902
- app.get('/api/data', async ctx => {
903
- ctx.logger.info('Fetching data', {
904
- userId: ctx.state.user?.id,
905
- endpoint: '/api/data',
906
- });
907
-
908
- try {
909
- const data = await fetchData();
910
- ctx.logger.debug('Data fetched successfully', { count: data.length });
911
- ctx.json({ data });
912
- } catch (error) {
913
- ctx.logger.error('Failed to fetch data', {
914
- error: error.message,
915
- stack: error.stack,
916
- });
917
- throw error;
124
+ @Get()
125
+ hello() {
126
+ return this.svc.greet();
918
127
  }
919
- });
920
- ```
921
-
922
- **Logger Features:**
923
-
924
- - **Multiple Transports** - Console, file, and custom transports
925
- - **Log Levels** - debug, info, warn, error, fatal
926
- - **Structured Logging** - JSON format with metadata
927
- - **File Rotation** - Size-based and time-based rotation
928
- - **Colorized Output** - Enhanced development experience
929
- - **Performance Metrics** - Request timing and throughput tracking
930
- - **Custom Formatters** - Extensible log formatting
931
-
932
- 📚 **[Logger Plugin Documentation →](./docs/api/logger-plugin.md)**
933
-
934
- ---
935
-
936
- ## 🏗️ **Advanced Features**
937
-
938
- ### Modular Router System
939
-
940
- ```typescript
941
- import { createApp, createRouter } from 'nextrush';
128
+ }
942
129
 
943
130
  const app = createApp();
131
+ const router = createRouter();
944
132
 
945
- // Create sub-routers
946
- const userRouter = createRouter();
947
- const adminRouter = createRouter();
948
-
949
- // User routes
950
- userRouter.get('/profile', async ctx => ctx.json({ user: 'profile' }));
951
- userRouter.post('/login', async ctx => ctx.json({ message: 'Logged in' }));
952
-
953
- // Admin routes
954
- adminRouter.get('/dashboard', async ctx => ctx.json({ admin: 'dashboard' }));
955
- adminRouter.get('/users', async ctx => ctx.json({ admin: 'users list' }));
956
-
957
- // Mount routers
958
- app.use('/users', userRouter);
959
- app.use('/admin', adminRouter);
133
+ app.plugin(controllersPlugin({ router, root: './src' }));
134
+ app.route('/', router);
135
+ listen(app, 3000);
960
136
  ```
961
137
 
962
- ### Custom Middleware Development
138
+ > **tsconfig.json** must have `experimentalDecorators: true` and `emitDecoratorMetadata: true`. The `create-nextrush` scaffolder sets these automatically.
963
139
 
964
- ```typescript
965
- import type { Middleware, Context } from 'nextrush';
140
+ ## What's Included
966
141
 
967
- // Simple middleware
968
- const logger: Middleware = async (ctx, next) => {
969
- const start = Date.now();
970
- console.log(`🔄 ${ctx.method} ${ctx.path}`);
142
+ This meta package re-exports from:
971
143
 
972
- await next();
144
+ | Package | Exports |
145
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
146
+ | `@nextrush/core` | `createApp`, `Application`, `compose` |
147
+ | `@nextrush/router` | `createRouter`, `Router` |
148
+ | `@nextrush/adapter-node` | `listen`, `serve`, `createHandler` |
149
+ | `@nextrush/types` | `Context`, `Middleware`, `Next`, `Plugin`, `RouteHandler`, `HttpMethod`, `HttpStatus`, `ContentType` |
150
+ | `@nextrush/errors` | `HttpError`, `NextRushError`, error classes (4xx/5xx), `createError`, `isHttpError`, `errorHandler`, `notFoundHandler`, `catchAsync` |
973
151
 
974
- const duration = Date.now() - start;
975
- console.log(`✅ ${ctx.status} ${duration}ms`);
976
- };
152
+ ## Available Packages
977
153
 
978
- // Authentication middleware with proper error handling
979
- const requireAuth: Middleware = async (ctx, next) => {
980
- const token = ctx.headers.authorization?.replace('Bearer ', '');
154
+ ### Core (included in nextrush)
981
155
 
982
- if (!token) {
983
- throw new UnauthorizedError('Authentication token required', {
984
- hint: 'Include Authorization: Bearer <token> header',
985
- });
986
- }
156
+ | Package | Description |
157
+ | ------------------------ | ------------------------------------ |
158
+ | `@nextrush/core` | Application & middleware composition |
159
+ | `@nextrush/router` | High-performance radix tree router |
160
+ | `@nextrush/adapter-node` | Node.js HTTP adapter |
161
+ | `@nextrush/types` | Shared TypeScript types |
162
+ | `@nextrush/errors` | HTTP error classes |
987
163
 
988
- try {
989
- ctx.state.user = await validateToken(token);
990
- await next();
991
- } catch (error) {
992
- throw new UnauthorizedError('Invalid authentication token', {
993
- reason: error.message,
994
- });
995
- }
996
- };
997
-
998
- // Role-based authorization
999
- const requireRole = (role: string): Middleware => {
1000
- return async (ctx, next) => {
1001
- if (!ctx.state.user) {
1002
- throw new UnauthorizedError('Authentication required');
1003
- }
1004
-
1005
- if (!ctx.state.user.roles.includes(role)) {
1006
- throw new ForbiddenError(`${role} role required`, {
1007
- userRoles: ctx.state.user.roles,
1008
- requiredRole: role,
1009
- });
1010
- }
1011
-
1012
- await next();
1013
- };
1014
- };
1015
-
1016
- // Rate limiting middleware
1017
- const rateLimiter: Middleware = async (ctx, next) => {
1018
- const key = ctx.ip;
1019
- const limit = 100;
1020
- const windowMs = 15 * 60 * 1000;
1021
-
1022
- const requests = await getRequestCount(key, windowMs);
1023
-
1024
- if (requests >= limit) {
1025
- throw new TooManyRequestsError('Rate limit exceeded', {
1026
- limit,
1027
- retryAfter: Math.ceil(windowMs / 1000),
1028
- });
1029
- }
164
+ ### Middleware (install separately)
1030
165
 
1031
- await incrementRequestCount(key, windowMs);
1032
- await next();
1033
- };
166
+ | Package | Description |
167
+ | ----------------------- | -------------------------------------- |
168
+ | `@nextrush/body-parser` | JSON/form/text body parsing |
169
+ | `@nextrush/cors` | CORS headers |
170
+ | `@nextrush/helmet` | Security headers |
171
+ | `@nextrush/cookies` | Cookie handling |
172
+ | `@nextrush/compression` | Response compression (gzip/brotli) |
173
+ | `@nextrush/rate-limit` | Rate limiting with multiple algorithms |
174
+ | `@nextrush/request-id` | Request ID generation |
175
+ | `@nextrush/timer` | Request timing headers |
1034
176
 
1035
- // Use middleware
1036
- app.use(logger);
1037
- app.use('/api', requireAuth);
1038
- app.use('/admin', requireRole('admin'));
1039
- ```
177
+ ### Plugins (install separately)
1040
178
 
1041
- 📚 **[Middleware Development Guide →](./docs/guides/middleware-development.md)**
179
+ | Package | Description |
180
+ | ----------------------- | ------------------------------- |
181
+ | `@nextrush/logger` | Structured logging |
182
+ | `@nextrush/static` | Static file serving |
183
+ | `@nextrush/websocket` | WebSocket support with rooms |
184
+ | `@nextrush/template` | Multi-engine template rendering |
185
+ | `@nextrush/events` | Type-safe event emitter |
186
+ | `@nextrush/controllers` | Decorator-based controllers |
1042
187
 
1043
- ### Enhanced Response Methods
188
+ ### Advanced (install separately)
1044
189
 
1045
- ```typescript
1046
- // JSON response with status code
1047
- app.get('/api/users', async ctx => {
1048
- const users = await getUsers();
1049
- ctx.json({ users }, 200);
1050
- });
190
+ | Package | Description |
191
+ | ---------------------- | ------------------------------ |
192
+ | `@nextrush/di` | Dependency injection container |
193
+ | `@nextrush/decorators` | Controller & route decorators |
1051
194
 
1052
- // HTML response
1053
- app.get('/page', async ctx => {
1054
- ctx.html('<h1>Welcome to NextRush</h1>');
1055
- });
195
+ ### Dev Tools
1056
196
 
1057
- // File download with options
1058
- app.get('/download', async ctx => {
1059
- ctx.file('./document.pdf', {
1060
- filename: 'report.pdf',
1061
- contentType: 'application/pdf',
1062
- });
1063
- });
197
+ | Package | Description |
198
+ | ----------------- | --------------------------------------------------------- |
199
+ | `@nextrush/dev` | Hot reload dev server, production builds, code generators |
200
+ | `create-nextrush` | Project scaffolder (`pnpm create nextrush`) |
1064
201
 
1065
- // Redirect with status code
1066
- app.get('/old-url', async ctx => {
1067
- ctx.redirect('/new-url', 301); // Permanent redirect
1068
- });
202
+ ## Direct Package Usage
1069
203
 
1070
- // CSV export
1071
- app.get('/export/users', async ctx => {
1072
- const users = await getUsers();
1073
- const csv = users.map(u => `${u.name},${u.email}`).join('\n');
1074
- ctx.csv(`name,email\n${csv}`, 'users.csv');
1075
- });
1076
-
1077
- // Stream response
1078
- app.get('/stream', async ctx => {
1079
- const stream = fs.createReadStream('./large-file.txt');
1080
- ctx.stream(stream, 'text/plain');
1081
- });
1082
-
1083
- // Set custom headers
1084
- app.get('/api/data', async ctx => {
1085
- ctx.set('X-Custom-Header', 'value');
1086
- ctx.set('Cache-Control', 'max-age=3600');
1087
- ctx.json({ data: [] });
1088
- });
1089
-
1090
- // Cookie management
1091
- app.get('/set-cookie', async ctx => {
1092
- ctx.setCookie('session', 'abc123', {
1093
- httpOnly: true,
1094
- secure: true,
1095
- maxAge: 3600000,
1096
- sameSite: 'strict',
1097
- });
1098
- ctx.json({ message: 'Cookie set' });
1099
- });
1100
-
1101
- app.get('/get-cookie', async ctx => {
1102
- const session = ctx.getCookie('session');
1103
- ctx.json({ session });
1104
- });
1105
- ```
1106
-
1107
- 📚 **[Enhanced Request/Response API →](./docs/api/enhancers.md)**
1108
-
1109
- ## 📖 Complete API Reference
1110
-
1111
- ### Context Object
204
+ For maximum control, skip the meta package:
1112
205
 
1113
206
  ```typescript
1114
- // ===================== Request Properties =====================
1115
- ctx.req // Native HTTP request object
1116
- ctx.res // Enhanced response object
1117
- ctx.body // Parsed request body (JSON, form, etc.)
1118
- ctx.method // HTTP method (GET, POST, PUT, DELETE, etc.)
1119
- ctx.path // Request path (/users/123)
1120
- ctx.url // Full request URL
1121
- ctx.query // Query parameters (?page=1 → { page: '1' })
1122
- ctx.headers // Request headers (lowercase keys)
1123
- ctx.params // Route parameters (/users/:id → { id: '123' })
1124
- ctx.cookies // Parsed cookies
1125
- ctx.ip // Client IP address
1126
- ctx.secure // Is HTTPS?
1127
- ctx.protocol // Request protocol (http/https)
1128
- ctx.hostname // Request hostname
1129
- ctx.origin // Request origin (protocol + host)
1130
- ctx.state // Custom request-scoped state
1131
-
1132
- // ===================== Response Methods =====================
1133
- // Convenience API (Recommended)
1134
- ctx.json(data, status?) // Send JSON response
1135
- ctx.html(html, status?) // Send HTML response
1136
- ctx.text(text, status?) // Send plain text
1137
- ctx.csv(data, filename?) // Send CSV file
1138
- ctx.file(path, options?) // Send file download
1139
- ctx.stream(stream, contentType?) // Send stream response
1140
- ctx.redirect(url, status?) // Redirect to URL
1141
-
1142
- // Express-like API (Enhanced)
1143
- ctx.res.json(data, status?) // Send JSON
1144
- ctx.res.status(code) // Set status code (chainable)
1145
- ctx.res.send(data) // Auto-detect content type
1146
- ctx.res.sendFile(path) // Send file
1147
- ctx.res.render(template, data) // Render template
1148
-
1149
- // ===================== Header & Cookie Methods =====================
1150
- ctx.get(headerName) // Get request header
1151
- ctx.set(headerName, value) // Set response header
1152
- ctx.setCookie(name, value, opts) // Set cookie
1153
- ctx.getCookie(name) // Get cookie value
1154
- ctx.clearCookie(name) // Delete cookie
1155
-
1156
- // ===================== Utility Properties =====================
1157
- ctx.id // Unique request ID
1158
- ctx.logger // Request-scoped logger
1159
- ctx.services // DI container services
1160
- ctx.app // Application instance
207
+ import { createApp } from '@nextrush/core';
208
+ import { createRouter } from '@nextrush/router';
209
+ import { listen } from '@nextrush/adapter-node';
210
+ import { cors } from '@nextrush/cors';
1161
211
  ```
1162
212
 
1163
- ### Application Methods
1164
-
1165
- ```typescript
1166
- // ===================== HTTP Methods =====================
1167
- app.get(path, ...handlers) // GET route
1168
- app.post(path, ...handlers) // POST route
1169
- app.put(path, ...handlers) // PUT route
1170
- app.delete(path, ...handlers) // DELETE route
1171
- app.patch(path, ...handlers) // PATCH route
1172
- app.head(path, ...handlers) // HEAD route
1173
- app.options(path, ...handlers) // OPTIONS route
1174
- app.all(path, ...handlers) // All HTTP methods
1175
-
1176
- // ===================== Middleware =====================
1177
- app.use(...middleware) // Global middleware
1178
- app.use(path, ...middleware) // Path-specific middleware
1179
-
1180
- // ===================== Built-in Middleware =====================
1181
- app.cors(options) // CORS middleware
1182
- app.helmet(options) // Security headers
1183
- app.rateLimiter(options) // Rate limiting
1184
- app.compression(options) // Gzip/Brotli compression
1185
- app.requestId(options) // Request ID tracking
1186
- app.timer() // Response time header
1187
- app.smartBodyParser(options) // Auto body parsing
1188
-
1189
- // ===================== Event System =====================
1190
- app.events.emit(event, data) // Emit simple event
1191
- app.events.on(event, handler) // Listen to event
1192
- app.events.once(event, handler) // One-time listener
1193
- app.events.off(event, handler?) // Remove listener
1194
-
1195
- app.eventSystem.dispatch(op) // CQRS dispatch
1196
- app.eventSystem.executeCommand(c) // Execute command
1197
- app.eventSystem.executeQuery(q) // Execute query
1198
- app.eventSystem.subscribe(e, h) // Subscribe to domain event
1199
-
1200
- // ===================== Server Control =====================
1201
- app.listen(port, callback?) // Start HTTP server
1202
- app.close(callback?) // Stop server gracefully
1203
- ```
213
+ ## Error Handling
1204
214
 
1205
- ### Router Methods
215
+ Built-in HTTP error classes:
1206
216
 
1207
217
  ```typescript
1208
- // Create router
1209
- const router = createRouter('/prefix');
1210
-
1211
- // HTTP methods
1212
- router.get(path, handler);
1213
- router.post(path, handler);
1214
- router.put(path, handler);
1215
- router.delete(path, handler);
1216
- router.patch(path, handler);
1217
-
1218
- // Middleware
1219
- router.use(middleware);
1220
-
1221
- // Mount router
1222
- app.use('/api', router);
1223
- ```
218
+ import { NotFoundError, BadRequestError, HttpError } from 'nextrush';
1224
219
 
1225
- ---
1226
-
1227
- ## 🧪 Testing
1228
-
1229
- ```typescript
1230
- import { createApp } from 'nextrush';
1231
-
1232
- describe('NextRush Application', () => {
1233
- it('should handle GET requests', async () => {
1234
- const app = createApp();
1235
-
1236
- app.get('/test', async ctx => {
1237
- ctx.json({ message: 'OK' });
1238
- });
1239
-
1240
- // Your test implementation
1241
- });
220
+ app.use(async (ctx) => {
221
+ if (!user) throw new NotFoundError('User not found');
222
+ if (!valid) throw new BadRequestError('Invalid input');
1242
223
  });
1243
224
  ```
1244
225
 
1245
- ---
1246
-
1247
- ## 🔥 Enhanced Body Parser
1248
-
1249
- Enterprise-grade body parsing with zero-copy operations:
226
+ ## Version
1250
227
 
1251
228
  ```typescript
1252
- // Auto-parsing (recommended)
1253
- app.use(app.smartBodyParser());
1254
-
1255
- // Advanced configuration
1256
- app.use(
1257
- app.smartBodyParser({
1258
- maxSize: 10 * 1024 * 1024, // 10MB
1259
- enableStreaming: true,
1260
- autoDetectContentType: true,
1261
- enableMetrics: true,
1262
- })
1263
- );
1264
-
1265
- // Supports JSON, form-data, text, multipart
1266
- app.post('/api/data', ctx => {
1267
- const data = ctx.body; // Already parsed!
1268
- ctx.json({ received: data });
1269
- });
229
+ import { VERSION } from 'nextrush';
230
+ console.log(VERSION); // '3.0.0'
1270
231
  ```
1271
232
 
1272
- **Features:** Zero-copy buffers • Auto-detection • Streaming • Memory-pooled • Cross-platform
1273
-
1274
- 📚 **[Full Documentation →](./docs/api/built-in-middleware.md)**
1275
-
1276
- ## 📚 Documentation
1277
-
1278
- Comprehensive guides, API references, and architecture deep-dives:
1279
-
1280
- ### Getting Started
1281
-
1282
- - **[Getting Started Guide](./docs/guides/getting-started.md)** - Your first NextRush v2 app in 5 minutes
1283
- - **[Migration from Express](./docs/guides/migration-guide.md)** - Migrate from Express.js
1284
- - **[Migration from Fastify](./docs/guides/migration-guide.md)** - Migrate from Fastify
1285
-
1286
- ### Essential Guides
1287
-
1288
- - **[Routing Guide](./docs/api/routing.md)** - All three routing styles explained (Convenience, Enhanced, Fastify-style)
1289
- - **[Middleware Development](./docs/guides/middleware-development.md)** - Create custom middleware
1290
- - **[Plugin Development](./docs/guides/plugin-development.md)** - Build powerful plugins
1291
- - **[Error Handling Guide](./docs/guides/error-handling.md)** - Robust error management patterns
1292
- - **[Testing Guide](./docs/guides/testing-guide.md)** - Unit, integration, and E2E testing
1293
- - **[Production Deployment](./docs/guides/production-deployment.md)** - Deploy to production
1294
-
1295
- ### Core API Reference
1296
-
1297
- - **[Application API](./docs/api/application.md)** - Core application methods and lifecycle
1298
- - **[Context API](./docs/api/context.md)** - Request/response context (Koa-style)
1299
- - **[Routing API](./docs/api/routing.md)** - Router and route handlers
1300
- - **[Middleware API](./docs/api/middleware.md)** - Middleware system and patterns
1301
- - **[Built-in Middleware](./docs/api/built-in-middleware.md)** - CORS, Helmet, Rate Limiting, Body Parser
1302
- - **[Events API](./docs/api/events.md)** - Simple Events + Advanced Event System (CQRS)
1303
- - **[Enhanced Request/Response](./docs/api/enhancers.md)** - Express-like helper methods
1304
-
1305
- ### Advanced Features
1306
-
1307
- - **[Error Handling API](./docs/api/errors.md)** - Custom error classes and error middleware
1308
- - **[Validation Utilities](./docs/api/validation-utilities.md)** - Schema validation and data sanitization
1309
- - **[Configuration & Validation](./docs/api/configuration.md)** - Application configuration
1310
- - **[Path Utilities](./docs/api/path-utilities.md)** - URL and path manipulation helpers
1311
- - **[Developer Experience](./docs/api/developer-experience.md)** - Enhanced error messages and debugging
1312
-
1313
- ### Plugin APIs
1314
-
1315
- - **[Logger Plugin](./docs/api/logger-plugin.md)** - Advanced structured logging with transports
1316
- - **[WebSocket Plugin](./docs/api/websocket-plugin.md)** - Real-time WebSocket communication
1317
- - **[Static Files Plugin](./docs/api/static-files-plugin.md)** - High-performance static file serving
1318
- - **[Template Plugin](./docs/api/template-plugin.md)** - HTML template rendering engine
1319
-
1320
- ### Architecture Deep-Dives
1321
-
1322
- - **[Plugin System](./docs/architecture/plugin-system.md)** - Plugin architecture and lifecycle
1323
- - **[Dependency Injection](./docs/architecture/dependency-injection.md)** - DI container and service resolution
1324
- - **[Orchestration System](./docs/architecture/orchestration-system.md)** - Application orchestration patterns
1325
- - **[Optimized Router](./docs/architecture/optimized-router-deep-dive.md)** - Router internals and performance
1326
-
1327
- ### Performance & Benchmarks
1328
-
1329
- - **Benchmarks** - Performance comparisons with Express, Koa, and Fastify
1330
- - **Performance Guide** - Optimization techniques and best practices
1331
- - **Memory Management** - Efficient memory usage patterns
1332
-
1333
- ## 🤝 Contributing
1334
-
1335
- Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details on how to get started.
1336
-
1337
- ## 📄 License
1338
-
1339
- This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
1340
-
1341
- ## 🙏 Acknowledgments
1342
-
1343
- - **Express.js** - Intuitive API design patterns
1344
- - **Koa** - Powerful async middleware architecture
1345
- - **Fastify** - Object-based route configuration approach
1346
- - **TypeScript** - Type safety and enhanced developer experience
1347
-
1348
- ---
1349
-
1350
- <div align="center">
1351
-
1352
- **Built with precision by [Tanzim Hossain](https://github.com/0xTanzim)**
1353
-
1354
- [Report Bug](https://github.com/0xTanzim/nextrush/issues) • [Request Feature](https://github.com/0xTanzim/nextrush/issues) • [Discussions](https://github.com/0xTanzim/nextrush/discussions)
233
+ ## License
1355
234
 
1356
- </div>
235
+ MIT © [Tanzim Hossain](https://github.com/0xTanzim)