UNPKG

nextrush

Version:

๐ŸŽ“ LEARNING PROJECT: My first attempt at building a Node.js web framework with Express-compatible API. Educational purposes only - NOT recommended for production use. Features TypeScript, zero dependencies, and plugin architecture.

1,323 lines (1,289 loc) โ€ข 100 kB
import { IncomingMessage, ServerResponse } from 'http'; import { ParsedUrlQuery } from 'querystring'; import { Socket } from 'net'; import { Writable } from 'stream'; type Dict<T = unknown> = Record<string, T>; /** * HTTP-related type definitions */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'ALL'; type ContentType = 'application/json' | 'application/x-www-form-urlencoded' | 'text/plain' | 'text/html' | 'multipart/form-data' | string; interface ParsedRequest extends IncomingMessage { query: ParsedUrlQuery; params: Dict<string>; body: unknown; pathname: string; originalUrl: string; } interface ParsedResponse extends ServerResponse { locals: Dict<unknown>; } interface RequestContext { request: ParsedRequest; response: ParsedResponse; params: Dict<string>; query: ParsedUrlQuery; body: unknown; startTime: number; } interface BodyParserOptions { maxSize?: number; timeout?: number; allowedContentTypes?: ContentType[]; strict?: boolean; } /** * ๐Ÿ”ฅ Optimized Error Handler - Simple and Efficient * - Memory optimized with smart caching * - Performance-first design * - Enterprise-grade error classification */ interface ErrorHandlerConfig { includeStack?: boolean; logErrors?: boolean; customErrorHandler?: (error: Error, context: RequestContext) => void; enableMetrics?: boolean; sanitizeProductionErrors?: boolean; } declare class ErrorHandler { private config; private errorCount; private lastErrorTime; constructor(config?: ErrorHandlerConfig); /** * Handle an error and send appropriate HTTP response */ handle(error: Error, context: RequestContext): Promise<void>; /** * Convert any error to NextRushError with smart classification */ private normalizeError; /** * Intelligent error classification */ private classifyError; /** * Send formatted error response */ private sendErrorResponse; /** * Smart error logging */ private logError; /** * Utility methods */ private shouldIncludeStack; private extractCorrelationId; private handleFallbackError; /** * Configure the error handler */ configure(config: Partial<ErrorHandlerConfig>): void; /** * Get basic metrics */ getMetrics(): { totalErrors: number; lastErrorTime: number; }; /** * Reset metrics */ resetMetrics(): void; } /** * Express-style request and response interfaces * Making NextRush familiar and easy to use */ interface ValidationRule$1 { required?: boolean; type?: 'string' | 'number' | 'email' | 'url' | 'boolean'; minLength?: number; maxLength?: number; min?: number; max?: number; custom?: (value: any) => boolean; message?: string; sanitize?: SanitizeOptions; } interface ValidationResult$1 { isValid: boolean; errors: Record<string, string[]>; sanitized: Record<string, any>; } interface SanitizeOptions { trim?: boolean; escape?: boolean; lowercase?: boolean; uppercase?: boolean; removeHtml?: boolean; removeSpecialChars?: boolean; } interface RateLimitInfo { limit: number; remaining: number; reset: number; retryAfter: number; } interface UserAgentInfo { raw: string; browser: string; os: string; device: string; isBot: boolean; isMobile: boolean; } interface RequestTiming { start: number; duration: number; timestamp: string; } interface NextRushRequest extends IncomingMessage { params: Record<string, string>; query: ParsedUrlQuery; body: any; pathname: string; originalUrl: string; path: string; files: Record<string, any>; cookies: Record<string, string>; signedCookies?: Record<string, string>; session: Record<string, any>; locals: Record<string, any>; startTime: number; id?: string; middlewareStack?: string[]; param(name: string): string | undefined; header(name: string): string | undefined; get(name: string): string | undefined; ip(): string; secure(): boolean; protocol(): string; hostname(): string; fullUrl(): string; is(type: string): boolean; accepts(types: string | string[]): string | false; fresh: boolean; stale: boolean; parseCookies(): Record<string, string>; validate(rules: Record<string, ValidationRule$1>): ValidationResult$1; sanitize(value: any, options?: SanitizeOptions): any; sanitizeObject(obj: any, options?: any): any; rateLimit(): RateLimitInfo; fingerprint(): string; userAgent(): UserAgentInfo; timing(): RequestTiming; getRequestTiming(): any; isValidEmail(email: string): boolean; isValidUrl(url: string): boolean; sanitizeValue(value: any, rule: ValidationRule$1): any; parseBrowser(ua: string): string; parseOS(ua: string): string; parseDevice(ua: string): string; isBot(ua: string): boolean; isMobile(ua: string): boolean; } interface NextRushResponse extends ServerResponse { locals: Record<string, any>; status(code: number): NextRushResponse; json(data: any): void; send(data: string | Buffer | object): void; html(data: string): void; text(data: string): void; xml(data: string): void; csv(data: any[], filename?: string): void; stream(stream: NodeJS.ReadableStream, contentType?: string, options?: { bufferSize?: number; highWaterMark?: number; enableCompression?: boolean; }): void; sendFile(filePath: string, options?: { maxAge?: number; lastModified?: boolean; etag?: boolean; dotfiles?: 'allow' | 'deny' | 'ignore'; root?: string; headers?: Record<string, string>; acceptRanges?: boolean; }): void; download(filePath: string, filename?: string, options?: any): void; getSmartContentType(filePath: string): string; generateETag(stats: any): string; redirect(url: string, status?: number): void; redirectPermanent(url: string): void; redirectTemporary(url: string): void; set(field: string, value: string): NextRushResponse; set(fields: Record<string, string>): NextRushResponse; header(field: string, value: string): NextRushResponse; removeHeader(field: string): NextRushResponse; get(field: string): string | undefined; cookie(name: string, value: string, options?: { maxAge?: number; expires?: Date; path?: string; domain?: string; secure?: boolean; httpOnly?: boolean; sameSite?: 'strict' | 'lax' | 'none'; signed?: boolean; }): NextRushResponse; clearCookie(name: string, options?: any): NextRushResponse; render(template: string, data?: any): void; getContentTypeFromExtension(ext: string): string; getNestedValue(obj: any, path: string): any; isTruthy(value: any): boolean; cache(seconds: number): NextRushResponse; noCache(): NextRushResponse; cors(origin?: string): NextRushResponse; security(): NextRushResponse; compress(): NextRushResponse; success(data: any, message?: string): void; error(message: string, code?: number, details?: any): void; paginate(data: any[], page: number, limit: number, total: number): void; time(label?: string): NextRushResponse; } type ExpressHandler$1 = (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>; type ExpressMiddleware$1 = (req: NextRushRequest, res: NextRushResponse, next: () => void) => void | Promise<void>; /** * Routing-related type definitions */ type Path = string | RegExp; interface RouteHandler$1 { (context: RequestContext): Promise<void> | void; } interface MiddlewareHandler$1 { (context: RequestContext, next: () => Promise<void>): Promise<void> | void; } interface RouterOptions { caseSensitive?: boolean; strict?: boolean; mergeParams?: boolean; useOptimizedMatcher?: boolean; enableCaching?: boolean; cacheSize?: number; enablePrefixOptimization?: boolean; enableMetrics?: boolean; } interface Route { id: string; path: Path; method: HttpMethod; handler: RouteHandler$1; middleware?: MiddlewareHandler$1[]; metadata?: Record<string, any>; } declare class Router { private routeManager; private globalMiddleware; private routerOptions; constructor(options?: RouterOptions); /** * Add global middleware that runs for all routes */ use(middleware: MiddlewareHandler$1 | ExpressMiddleware$1): this; /** * Register a GET route */ get(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; get(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; get(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; get(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Register a POST route */ post(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; post(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; post(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; post(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; post(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; post(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; post(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; post(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; post(path: Path, middleware1: MiddlewareHandler$1 | ExpressMiddleware$1, middleware2: MiddlewareHandler$1 | ExpressMiddleware$1, middleware3: MiddlewareHandler$1 | ExpressMiddleware$1, handler: RouteHandler$1): this; post(path: Path, middleware1: MiddlewareHandler$1 | ExpressMiddleware$1, middleware2: MiddlewareHandler$1 | ExpressMiddleware$1, middleware3: MiddlewareHandler$1 | ExpressMiddleware$1, handler: ExpressHandler$1): this; /** * Register a PUT route */ put(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; put(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; put(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; put(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; put(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; put(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; put(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; put(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Register a DELETE route */ delete(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; delete(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; delete(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; delete(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; delete(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; delete(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; delete(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; delete(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Register a PATCH route */ patch(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; patch(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; patch(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; patch(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; patch(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; patch(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; patch(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; patch(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Register a HEAD route */ head(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; head(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; head(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; head(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; head(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; head(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; head(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; head(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Register an OPTIONS route */ options(path: Path, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; options(path: Path, handler: (context: RequestContext) => void | Promise<void>): this; options(path: Path, middleware: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; options(path: Path, middleware: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; options(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; options(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; options(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>): this; options(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: (context: RequestContext) => void | Promise<void>): this; /** * Handle incoming request */ handle(context: RequestContext): Promise<void>; /** * Execute middleware chain and route handler */ private executeMiddlewareChain; /** * Add a route with the specified method (internal) */ private registerRoute; /** * Add a route to this router (public API for mounting) */ addRoute(method: HttpMethod, path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal method for Application class - allows spreading middleware */ private _addRoute; /** * Internal GET method for Application class */ _get(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal POST method for Application class */ _post(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal PUT method for Application class */ _put(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal DELETE method for Application class */ _delete(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal PATCH method for Application class */ _patch(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal HEAD method for Application class */ _head(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Internal OPTIONS method for Application class */ _options(path: Path, handler: RouteHandler$1 | ExpressHandler$1, middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]): this; /** * Get all registered routes */ getRoutes(method?: HttpMethod): Route[]; /** * Get router statistics */ getStats(): { globalMiddleware: number; totalRoutes: number; routesByMethod: Record<HttpMethod, number>; methods: HttpMethod[]; performanceStats?: any; }; /** * Clear all routes and middleware */ clear(): void; /** * Create a sub-router with merged options */ createSubRouter(options?: Partial<RouterOptions>): Router; /** * Mount another router with a path prefix */ mount(pathPrefix: string, router: Router): this; private combinePaths; /** * Configure the router */ configure(options: Partial<RouterOptions>): void; /** * Check if a handler is an Express-style handler */ private isExpressHandler; /** * Convert Express-style handler to NextRush handler */ private convertHandler; /** * Check if middleware is Express-style */ private isExpressMiddleware; /** * Convert Express-style middleware to NextRush middleware */ private convertMiddleware; } /** * ๐Ÿš€ NextRush Simple Event System * Lightweight event-driven architecture for request/response tracking */ type EventCallback<T = any> = (data: T) => void | Promise<void>; /** * ๐ŸŽฏ Simple Event Emitter */ declare class SimpleEventEmitter { private events; private maxListeners; /** * Add event listener */ on<T = any>(event: string, callback: EventCallback<T>): this; /** * Add one-time event listener */ once<T = any>(event: string, callback: EventCallback<T>): this; /** * Remove event listener */ off<T = any>(event: string, callback: EventCallback<T>): this; /** * Remove all listeners for event or all events */ removeAllListeners(event?: string): this; /** * Emit event */ emit<T = any>(event: string, data?: T): boolean; /** * Get listener count for event */ listenerCount(event: string): number; /** * Get all event names */ eventNames(): string[]; /** * Get listeners for event */ listeners<T = any>(event: string): EventCallback<T>[]; /** * Set max listeners */ setMaxListeners(max: number): this; /** * Get max listeners */ getMaxListeners(): number; } /** * ๐Ÿš€ NextRush WebSocket - Type Definitions * Zero-dependency WebSocket implementation using raw Node.js * RFC 6455 compliant with advanced room and event management */ /** * WebSocket connection states (RFC 6455) */ declare enum WebSocketReadyState { CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3 } /** * NextRush WebSocket Connection * Pure Node.js implementation with advanced features */ interface NextRushWebSocket { id: string; socket: Socket; readyState: WebSocketReadyState; protocol: string; extensions: string[]; send(data: string | Buffer | object): void; ping(data?: Buffer): void; pong(data?: Buffer): void; close(code?: number, reason?: string): void; broadcast(data: string | Buffer | object, room?: string): void; join(room: string): Promise<void>; leave(room: string): Promise<void>; to(room: string): RoomEmitter; emit(event: string, ...args: any[]): void; on(event: string, handler: (...args: any[]) => void): void; off(event: string, handler?: (...args: any[]) => void): void; once(event: string, handler: (...args: any[]) => void): void; ip: string; userAgent: string; origin: string; rooms: Set<string>; isAlive: boolean; lastPing: number; metadata: Record<string, any>; connectedAt: Date; lastActivity: Date; } /** * Room-based messaging interface */ interface RoomEmitter { emit(event: string, ...args: any[]): void; send(data: string | Buffer | object): void; broadcast(data: string | Buffer | object): void; except(socketId: string): RoomEmitter; to(room: string): RoomEmitter; } /** * WebSocket event handlers */ type WebSocketHandler = (socket: NextRushWebSocket, req: NextRushRequest) => void | Promise<void>; /** * Core interfaces for NextRush framework * Based on old codebase patterns but modernized for new architecture */ type RouteHandler = (context: RequestContext) => void | Promise<void>; type ExpressHandler = (req: NextRushRequest, res: NextRushResponse) => void | Promise<void>; type MiddlewareHandler = (context: RequestContext, next: () => void) => void | Promise<void>; type ExpressMiddleware = (req: NextRushRequest, res: NextRushResponse, next: () => void) => void | Promise<void>; /** * Minimal Application interface - defines core methods that components need */ interface MinimalApplication$1 { get(path: Path, handler: ExpressHandler): MinimalApplication$1; get(path: Path, handler: RouteHandler): MinimalApplication$1; get(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; get(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; get(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; get(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; get(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; post(path: Path, handler: ExpressHandler): MinimalApplication$1; post(path: Path, handler: RouteHandler): MinimalApplication$1; post(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; post(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; post(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; post(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; post(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; put(path: Path, handler: ExpressHandler): MinimalApplication$1; put(path: Path, handler: RouteHandler): MinimalApplication$1; put(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; put(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; put(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; put(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; put(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; delete(path: Path, handler: ExpressHandler): MinimalApplication$1; delete(path: Path, handler: RouteHandler): MinimalApplication$1; delete(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; delete(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; delete(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; delete(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; delete(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; patch(path: Path, handler: ExpressHandler): MinimalApplication$1; patch(path: Path, handler: RouteHandler): MinimalApplication$1; patch(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; patch(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; patch(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; patch(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; patch(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; head(path: Path, handler: ExpressHandler): MinimalApplication$1; head(path: Path, handler: RouteHandler): MinimalApplication$1; head(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; head(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; head(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; head(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; head(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; options(path: Path, handler: ExpressHandler): MinimalApplication$1; options(path: Path, handler: RouteHandler): MinimalApplication$1; options(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; options(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; options(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; options(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; options(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; all(path: Path, handler: ExpressHandler): MinimalApplication$1; all(path: Path, handler: RouteHandler): MinimalApplication$1; all(path: Path, middleware: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; all(path: Path, middleware: MiddlewareHandler, handler: RouteHandler): MinimalApplication$1; all(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; all(path: Path, middleware1: ExpressMiddleware, middleware2: ExpressMiddleware, middleware3: ExpressMiddleware, handler: ExpressHandler): MinimalApplication$1; all(path: Path, ...args: (RouteHandler | ExpressHandler | MiddlewareHandler | ExpressMiddleware)[]): MinimalApplication$1; use(...args: any[]): MinimalApplication$1; static(path: string, root?: string): MinimalApplication$1; setViews: (path: string) => MinimalApplication$1; render: (...args: any[]) => MinimalApplication$1; ws: (path: string, handler: WebSocketHandler) => MinimalApplication$1; listen(port: number | string, hostname?: string | (() => void), callback?: () => void): MinimalApplication$1; close: (callback?: () => void) => MinimalApplication$1; } /** * Component lifecycle interface */ interface Lifecycle$1 { /** * Called when component is installed into application */ install?(app: MinimalApplication$1): void | Promise<void>; /** * Called when component is uninstalled from application */ uninstall?(app: MinimalApplication$1): void | Promise<void>; /** * Called when application starts */ start?(): void | Promise<void>; /** * Called when application stops */ stop?(): void | Promise<void>; } /** * Abstract base class for components * Provides a foundation for extensible components with inheritance * * @abstract * @example * ```typescript * class RouterComponent extends BaseComponent { * constructor() { * super('Router'); * } * * public install(app: MinimalApplication): void { * app.get = this.get.bind(this); * app.post = this.post.bind(this); * } * } * ``` */ /** * Abstract base class for all components * Enables OOP with inheritance for extensible component behavior */ declare abstract class BaseComponent implements Lifecycle$1 { /** * Unique component name * @readonly */ readonly name: string; /** * Component initialization status * @protected */ protected isInitialized: boolean; /** * Component running status * @protected */ protected isRunning: boolean; /** * Reference to the application instance * @protected */ protected app?: MinimalApplication$1; /** * Create a new base component * @param name - Unique component name */ constructor(name: string); /** * Install component on application (abstract - must be implemented) * @param app - Minimal application instance * @abstract */ abstract install(app: MinimalApplication$1): void | Promise<void>; /** * Start component (optional override) * Called when application starts */ start(): Promise<void>; /** * Stop component (optional override) * Called when application stops */ stop(): Promise<void>; /** * Check if component is initialized * @returns True if component is initialized */ getIsInitialized(): boolean; /** * Check if component is running * @returns True if component is running */ getIsRunning(): boolean; /** * Get component information * @returns Component information object */ getInfo(): ComponentInfo; /** * Set application reference (called during installation) * @param app - Application instance * @protected */ protected setApp(app: MinimalApplication$1): void; /** * Ensure component is initialized * @throws Error if component is not initialized * @protected */ protected ensureInitialized(): void; /** * Ensure component is running * @throws Error if component is not running * @protected */ protected ensureRunning(): void; /** * Log component message with name prefix * @param level - Log level * @param message - Log message * @param meta - Optional metadata * @protected */ protected log(level: 'info' | 'warn' | 'error', message: string, meta?: any): void; } /** * Component information interface */ interface ComponentInfo { name: string; isInitialized: boolean; isRunning: boolean; type: 'component' | 'plugin'; } /** * ๐Ÿ”Œ BasePlugin - Core Plugin Implementation * * According to copilot instructions, all features must be implemented as plugins * inheriting from BasePlugin under src/plugins/ */ /** * Plugin Registry interface for event system and plugin access */ interface PluginRegistry { emit(event: string, ...args: any[]): void; on(event: string, listener: (...args: any[]) => void): void; off(event: string, listener: (...args: any[]) => void): void; getPlugin?(name: string): BasePlugin | undefined; } /** * Base Plugin class that all NextRush plugins must inherit from * Follows the copilot instructions for unified plugin architecture */ declare abstract class BasePlugin { abstract name: string; protected registry: PluginRegistry; constructor(registry: PluginRegistry); /** * Install the plugin into the application * This is where plugins register their capabilities (app.get, app.use, etc.) */ abstract install(app: Application): void; /** * Start the plugin - activate its functionality */ abstract start(): void; /** * Stop the plugin - deactivate its functionality */ abstract stop(): void; /** * Emit events to other plugins */ protected emit(event: string, ...args: any[]): void; /** * Listen to events from other plugins */ protected on(event: string, listener: (...args: any[]) => void): void; /** * Remove event listener */ protected off(event: string, listener: (...args: any[]) => void): void; } /** * ๐Ÿš€ MEGA ULTIMATE PARSER - NextRush Framework * * SINGLE UNIFIED PARSER WITH NODEJS RAW POWER + V8 ENGINE OPTIMIZATION * * Features: * - ๐Ÿ”ฅ Zero-copy buffer operations using Node.js raw power * - ๐Ÿš€ V8 engine optimizations for maximum performance * - ๐Ÿง  AI-like content type auto-detection * - ๐ŸŒŠ Streaming parser with backpressure handling * - ๐Ÿ’พ Memory-pooled buffer management * - โšก CPU-optimized parsing with vectorized operations * - ๐ŸŽฏ Smart caching and pre-compiled patterns * - ๐Ÿ›ก๏ธ Enterprise-grade error handling * - ๐Ÿ“Š Real-time performance metrics collection * * This replaces ALL existing parsers with a single unified solution. * * @author NextRush Framework Team * @version 2.0.0 - MEGA ULTIMATE EDITION * @since 1.0.0 */ /** * ๐Ÿ”ง Ultimate parser configuration with enterprise-grade settings * * @interface MegaUltimateParserOptions */ interface MegaUltimateParserOptions { /** Maximum body size in bytes (default: 10MB) */ maxSize?: number; /** Request timeout in milliseconds (default: 30s) */ timeout?: number; /** Enable streaming for large payloads (default: true) */ enableStreaming?: boolean; /** Streaming threshold in bytes (default: 50MB) */ streamingThreshold?: number; /** Buffer pool size for optimization (default: 100) */ poolSize?: number; /** Enable fast validation (default: true) */ fastValidation?: boolean; /** Auto-detect content type (default: true) */ autoDetectContentType?: boolean; /** Strict content type checking (default: false) */ strictContentType?: boolean; /** Enable debug logging (default: false) */ debug?: boolean; /** Maximum number of files for multipart (default: 10) */ maxFiles?: number; /** Maximum file size for uploads (default: 5MB) */ maxFileSize?: number; /** Memory storage for files (default: true) */ memoryStorage?: boolean; /** Upload directory for disk storage */ uploadDir?: string; /** Character encoding (default: 'utf8') */ encoding?: BufferEncoding; } /** * ๐Ÿ“Š Performance metrics for monitoring * * @interface MegaParserMetrics */ interface MegaParserMetrics { /** Total requests processed */ totalRequests: number; /** Total parsing time in milliseconds */ totalParseTime: number; /** Average parsing time per request */ averageParseTime: number; /** Peak memory usage in bytes */ peakMemoryUsage: number; /** Cache hit ratio (0-1) */ cacheHitRatio: number; /** Parse success rate (0-1) */ successRate: number; /** Total bytes processed */ totalBytesProcessed: number; } /** * ๐Ÿš€ Body Parser Plugin v2.0 - MEGA ULTIMATE EDITION * * SINGLE UNIFIED PARSER THAT REPLACES ALL OTHER PARSERS * * Features: * - ๐Ÿ”ฅ Node.js raw power + V8 optimizations * - ๐Ÿง  Smart auto-detection * - โšก Zero-copy operations * - ๐Ÿ“Š Performance monitoring * - ๐Ÿ›ก๏ธ Enterprise-grade error handling * * This plugin replaces: * - All http/parsers/* files * - All old body parser implementations * - Enhanced request parsing conflicts * * @author NextRush Framework Team * @version 2.0.0 - MEGA ULTIMATE EDITION */ /** * ๐Ÿš€ MEGA ULTIMATE Body Parser Plugin * * The single, unified body parser that handles ALL request body parsing * with maximum performance and zero conflicts. * * @class BodyParserPlugin * @extends BasePlugin */ declare class BodyParserPlugin extends BasePlugin { name: string; /** The mega ultimate parser instance */ private megaParser; /** Plugin options merged from application config */ private options; /** Debug logging flag */ private debug; /** * Initialize the mega ultimate body parser plugin * * @param registry - Plugin registry for event communication */ constructor(registry: any); /** * ๐Ÿ”Œ Install the body parser plugin * * @param app - Application instance */ install(app: Application): void; /** * ๐Ÿš€ Start the body parser plugin */ start(): void; /** * ๐Ÿ›‘ Stop the body parser plugin and cleanup resources */ stop(): void; /** * ๐Ÿ”ง Install the ultimate auto body parser middleware * * This replaces ALL existing body parsing logic with a single unified solution * * @param app - Application instance */ private installAutoBodyParser; /** * ๐ŸŽฏ Set request body with FIXED property descriptor * * This fixes the middleware chain issue where req.body becomes undefined * * @param req - Request object * @param body - Parsed body data */ private setRequestBody; /** * ๐Ÿ“Š Get performance metrics from the mega parser * * @returns MegaParserMetrics - Performance metrics */ getMetrics(): MegaParserMetrics; /** * ๐Ÿ”ง Update parser options at runtime * * @param newOptions - New parser options */ updateOptions(newOptions: Partial<MegaUltimateParserOptions>): void; /** * ๐Ÿงน Manual cleanup method for removing debug logs */ static removeDebugLogs(): void; } /** * ๐ŸŽจ Middleware Composition Functions - NextRush Framework * * Provides Express-like middleware composition functions: * - compose() - Combine multiple middleware * - when() - Conditional middleware * - unless() - Exclusion middleware * - named() - Debug middleware with names */ /** * Compose multiple middleware into a single middleware function * Optimized for performance with minimal function calls * * @example * const authFlow = compose(checkApiKey, checkUser, rateLimit); * app.get('/protected', authFlow, handler); */ declare function compose(...middlewares: ExpressMiddleware$1[]): ExpressMiddleware$1; /** * Conditionally apply middleware based on a condition function * * @example * const mobileOnly = when( * (req) => req.headers['user-agent']?.includes('Mobile'), * mobileOptimization * ); */ declare function when(condition: (req: NextRushRequest) => boolean, middleware: ExpressMiddleware$1): ExpressMiddleware$1; /** * Apply middleware UNLESS a condition is true (opposite of when) * * @example * const authExceptPublic = unless( * (req) => req.path.startsWith('/public'), * requireAuth * ); */ declare function unless(condition: (req: NextRushRequest) => boolean, middleware: ExpressMiddleware$1): ExpressMiddleware$1; /** * Give middleware a name for easier debugging and tracking * * @example * app.use(named('rate-limiter', rateLimitMiddleware)); * app.use(named('auth-check', authMiddleware)); */ declare function named(name: string, middleware: ExpressMiddleware$1): ExpressMiddleware$1; /** * Create a group of middleware that can be applied together * * @example * const securityGroup = group([cors(), helmet(), rateLimit()]); * app.use('/api', securityGroup); */ declare function group(middlewares: ExpressMiddleware$1[]): ExpressMiddleware$1; /** * ๐Ÿ“ Static Files Types & Interfaces * Core type definitions for NextRush Static Files system */ /** * Static files statistics */ interface StaticStats { totalRequests: number; cacheHits: number; compressionHits: number; bytesServed: number; filesCached: number; cacheSize: number; mounts: number; uptime: number; } /** * ๐Ÿ“ NextRush Static Files Plugin * * Enterprise-grade static file serving with: * - ๐Ÿ—œ๏ธ Smart compression (gzip/brotli) * - ๐Ÿ’พ Intelligent LRU caching * - ๐Ÿ“ก Range requests for streaming * - ๐Ÿ”’ Comprehensive security * - ๐Ÿš€ High-performance optimization * - ๐Ÿ“ฑ SPA support with fallback */ /** * NextRush Static Files Plugin */ declare class StaticFilesPlugin extends BasePlugin { name: string; private cacheManager; private compressionHandler; private mimeTypeHandler; private rangeHandler; private securityHandler; private mounts; private stats; private maintenanceInterval; constructor(registry: PluginRegistry); /** * Install static file serving capabilities */ install(app: Application): void; /** * Start the plugin */ start(): void; /** * Stop the plugin */ stop(): void; /** * Get comprehensive statistics */ getStats(): StaticStats & { cache: any; }; /** * Add static mount */ private addMount; /** * Handle incoming requests */ private handleRequest; /** * Serve file from specific mount */ private serveFromMount; /** * Serve directory with index files */ private serveDirectory; /** * Serve individual file with all optimizations */ private serveFile; /** * Create optimized cache entry */ private createCacheEntry; /** * Handle conditional requests (ETag, If-Modified-Since) */ private handleConditionalRequest; /** * Handle range requests */ private handleRangeRequest; /** * Send file with optimized headers and compression */ private sendFile; /** * Serve SPA fallback */ private serveSpaFallback; /** * Set cache control headers */ private setCacheControl; /** * Utility methods */ private shouldCache; private isPathUnderMount; private normalizePath; private parseMaxAge; /** * Initialize modular components */ private initializeComponents; /** * Start maintenance tasks */ private startMaintenance; /** * Stop maintenance tasks */ private stopMaintenance; } /** * ๐Ÿš€ NextRush Performance-Optimized Plugin System * * Reduces plugin overhead from 12 plugins to 3-5 essential plugins * for maximum performance in production environments. * * Expected Performance Improvement: +25-30% (400-500 RPS) */ /** * Plugin loading strategy based on environment */ declare enum PluginMode { PERFORMANCE = "performance",// 4 plugins - max performance DEVELOPMENT = "development",// 6 plugins - debugging tools FULL_FEATURES = "full" } /** * Create plugins based on mode */ declare function createPlugins(registry: PluginRegistry, mode?: PluginMode): any[]; /** * ๐Ÿš€ NextRush Application - Complete, Type-Safe Framework * * Zero `any` usage, proper overloads, createRoute feature, enterprise-grade typing */ interface ApplicationOptions { router?: Router; routerOptions?: RouterOptions; errorHandler?: ErrorHandler; timeout?: number; maxRequestSize?: number; enableEvents?: boolean; enableWebSocket?: boolean; caseSensitive?: boolean; strict?: boolean; pluginMode?: PluginMode; bodyParser?: { debug?: boolean; maxSize?: number; timeout?: number; enableStreaming?: boolean; autoDetectContentType?: boolean; [key: string]: any; }; } interface StaticOptions { maxAge?: string | number; etag?: boolean; index?: string | string[] | false; dotfiles?: 'allow' | 'deny' | 'ignore'; extensions?: string[] | false; immutable?: boolean; redirect?: boolean; spa?: boolean; compress?: boolean | 'auto'; memoryCache?: boolean; acceptRanges?: boolean; cacheControl?: string; setHeaders?: (res: any, path: string) => void; } interface RouteDefinition { method: HttpMethod; path: Path; handler: RouteHandler$1 | ExpressHandler$1; middleware?: (MiddlewareHandler$1 | ExpressMiddleware$1)[]; name?: string; description?: string; } /** * ๐Ÿ”ฅ NextRush Application - Enterprise-Grade with Proper Typing */ declare class Application extends BaseComponent { private router; private errorHandler; private httpServer?; private appOptions; events?: SimpleEventEmitter; private viewsDirectory?; private pluginRegistry; constructor(applicationOptions?: ApplicationOptions); /** * Install method required by BaseComponent */ install(): void; testMethod(): string; /** * ๐Ÿ”Œ Initialize the plugin system */ private initializePlugins; /** * GET method with comprehensive overloads - Express-style compatibility */ get(path: Path, handler: ExpressHandler$1): Application; get(path: Path, handler: RouteHandler$1): Application; get(path: Path, middleware: ExpressMiddleware$1, handler: ExpressHandler$1): Application; get(path: Path, middleware: ExpressMiddleware$1, handler: RouteHandler$1): Application; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: ExpressHandler$1): Application; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: RouteHandler$1): Application; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: ExpressHandler$1): Application; get(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, middleware3: ExpressMiddleware$1, handler: RouteHandler$1): Application; /** * POST method with comprehensive overloads - Express-style compatibility */ post(path: Path, handler: ExpressHandler$1): Application; post(path: Path, handler: RouteHandler$1): Application; post(path: Path, middleware: ExpressMiddleware$1, handler: ExpressHandler$1): Application; post(path: Path, middleware: ExpressMiddleware$1, handler: RouteHandler$1): Application; post(path: Path, middleware1: ExpressMiddleware$1, middleware2: ExpressMiddleware$1, handler: ExpressHandler$1): Application; post(path: Path,