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