- Static file path traversal: containment check now uses
root + path.sep. PreviousstartsWith(root)allowed escape into sibling directories whose paths prefix-matchedroot(e.g.root=/app/static→/app/static-backups). No legitimate request path is affected. (src/core/middleware/built-in/static/core.ts) - Template path traversal:
res.render(userInput)now rejects template names that escape the configuredviewsdirectory. (src/core/middleware/built-in/template/core.ts) - JWT algorithm pinning:
safeVerifyJWTnow defaultsalgorithms: ['HS256']to prevent algorithm-confusion attacks. Callers using RS256/ES256 can override via theoptionsargument. (src/core/middleware/built-in/auth/jwt-helpers.ts) - Removed hardcoded session secret default (
'moro-session-secret'). Thesecretoption is now unset by default. (src/core/middleware/built-in/session/core.ts)
- Template engine: variables are now HTML-escaped by default (Mustache/Handlebars convention). Use
{{{var}}}for raw/unescaped output. The previous{{=var}}escape syntax has been removed.- Before:
{{name}}→ raw,{{=name}}→ escaped - After:
{{name}}→ escaped,{{{name}}}→ raw
- Before:
req.get(name)/req.header(name)— header accessorreq.is(type)— content-type matcherreq.accepts(types?)/req.acceptsLanguages(langs?)— content/language negotiation (respectsqquality values)req.hostname,req.protocol,req.secure,req.xhrreq.originalUrl,req.ips(parsedX-Forwarded-For),req.subdomainsres.set/res.get/res.append— unified header helpersres.type(ct)— content-type shorthand ('json','html','text', …)res.sendStatus(code),res.location(url),res.vary(field),res.links({ rel: url })res.attachment(filename?),res.download(path, filename?)res.format({ 'text/html': fn, 'application/json': fn, default: fn })— content negotiation with a 406 fallback
app.head(path, ...)andapp.options(path, ...)route methodsapp.all(path, handler)— registers a handler across all 7 HTTP methodscreateRouter()andMoroRouter— standalone router mountable viaapp.use(prefix, router)orrouter.mount(app, prefix)Routerexported as an alias forcreateRouter(callable withoutnew)json()andurlencoded()body-parser middlewares insrc/core/middleware/built-in/body-parsers/
- 4-arg error middleware support:
(err, req, res, next) => {} next(err)inside a middleware routes forward to the next error middlewareapp.setErrorHandler((err, req, res) => {})— dedicated typed global error handler, integrates with all three request paths (UnifiedRouter fast/slow paths, direct-route wrapper, HTTP-server top-level catch)
req.context: Record<string, any>— per-request typed state bag, fresh per requestres.locals: Record<string, any>— per-response typed state bagapp.onClose(fn)— register shutdown hooks; run in registration order insideapp.close()before Moro tears down its own subsystemsapp.decorate(name, value),app.decorateRequest(name, value),app.decorateReply(name, value)(+decorateResponsealias) — typed extension pattern applied to every request/response
- 20 new integration cases in
tests/integration/compat/express-signatures.test.ts - Full suite: 766 passing, no regressions
Existing MoroJS code is unaffected. Express users migrating to MoroJS now have a near-mechanical path — most diffs reduce to swapping the import source and the express() / express.Router() / express.json() tokens.
-
- Added
applyEarlyLogLevelfunction to set the logging level based onLOG_LEVELorMORO_LOG_LEVELenvironment variables before loading the app configuration. - Integrated early logging setup increateApp,createAppNode,createAppEdge,createAppLambda, andcreateAppWorkerfunctions to ensure consistent logging behavior across different app runtimes. - IntroducedmergeWebSocketConfigfunction to merge WebSocket configurations frommoro.config.tsandcreateApp()options, allowing for flexible configuration management. - Added unit tests formergeWebSocketConfigto validate merging logic and ensure correct behavior in various scenarios.
- Added
- Remove unnecessary whitespace from the WebSocket config merge unit test file for cleaner code formatting.
- feat: enhance security and performance across various components
- test: add unit tests for CompiledRoute integration in defineModule
- refactor: optimize SQL query generation and enhance event bus audit logging
- fix: allow CompiledRoute (defineRoute output) in defineModule routes
- fix: await createApp in all documentation examples for async support
- fix: await createApp in validation scripts and package tests
- feat!: make createApp/createAppNode/Edge/Lambda/Worker async for ESM config file support
- fix: resolve three cascading bugs in job scheduler for long-interval cron schedules
- fix: correct parameter name handling in RadixTree for module routes
- fix: Add CORS origin function support in config and fix MiddlewareInterface warning
- fix: resolve module root route overriding app root route
- fix: Convert Windows absolute paths to file URLs for ESM dynamic imports
- feat: add validation error handler with enhanced error formatting
- fix: production CORS hang and auto-discovery paths
- feat: enhance CORS and middleware config exposure
- fix: register module routes directly in http-server route table
- fix: bodySize middleware now skips multipart/form-data to allow large file uploads
- Patch headersSent warning on certain cors edge cases
- feat: enhance server configuration for file uploads
- feat: enhance multipart file upload handling and add tests for binary data integrity
- fix: TypeScript compilation errors and add integration tests for module middleware
- feat: Add comprehensive CORS preflight handling and module middleware support
- fix: prevent release script from creating releases without meaningful commits
- chore: update husky pre-commit, package versions, and uws version check script
- fix: preserve headers and request properties in module request objects
- feat: enhance DI container with advanced type-safe features
- feat: enhance dependency injection with advanced type-safe container features
- Bug Fixed: Chainable .handler() method was broken for routes with parameters. Root Cause: The radix tree implementation in /src/core/routing/radix-tree.ts had a critical bug in how it parsed paths: It wasn't skipping the leading / in paths like /users/:id The insert() method would try to parse from index 0, hitting the / immediately The searchNode() method would also fail to properly extract segments because it started at the wrong position Changes Made: Fixed radix-tree.ts - insert() method: Added logic to skip the leading slash before parsing segments Added logic to skip additional slashes during traversal Fixed segment extraction to stop at both / and : characters Fixed radix-tree.ts - searchNode() method: Added logic to skip slashes at each recursion level Fixed segment extraction to properly handle path boundaries Added comprehensive test coverage in tests/integration/simple.test.ts: Test name: "should support chainable handler syntax with route parameters" Tests GET, POST, PUT, DELETE with chainable handlers Tests single parameter routes (e.g., /products/:id) Tests multiple parameter routes (e.g., /categories/:category/items/:itemId)
- feat: migrate auth from Auth.js to Better Auth with enhanced features
- BREAKING: Migrated authentication system from Auth.js to Better Auth (v1.3.34)
- Better Auth is the actively maintained successor to Auth.js
- All existing Auth.js APIs remain compatible
- No breaking changes to user code
-
Enhanced OAuth Provider Support
- Added Twitter, Microsoft, Apple, Facebook, LinkedIn to core providers
- All providers now support Better Auth's enhanced features
- Maintained backward compatibility with existing provider configs
-
Modern Passwordless Authentication
providers.magicLink()- Email-based magic link authenticationproviders.otp()- One-time password support (SMS/Email)providers.passkey()- WebAuthn/Passkey support for biometric auth
-
Advanced Authentication Features
twoFactor()- Two-factor authentication with TOTP, backup codes, and trusted devicesorganization()- Multi-tenant and organization/team supportanonymous()- Guest user support with automatic account linkingaccountLinking()- Link multiple OAuth providers to a single accountrateLimit()- Built-in rate limiting for auth endpointsbearerToken()- API token authentication with refresh tokens
- Fixed "mw is not a function" error when MiddlewareInterface objects were incorrectly added to globalMiddleware
- Added defensive checks in all HTTP server implementations (Node.js, HTTP/2, uWebSockets) to prevent MiddlewareInterface objects from reaching middleware execution chains
- MiddlewareInterface objects are now properly handled only by MiddlewareManager
- feat: add standardized response methods with performance optimization
- feat: add gRPC, email, queue systems, HTTP/2, workers, new middleware and performance improvements
- feat: add gRPC, email, queue systems, HTTP/2, workers, new middleware and performance improvements
- feat: add gRPC, email, queue systems, HTTP/2, workers, new middleware and performance improvements
- feat: add gRPC, email, queue systems, HTTP/2, workers, new middleware and performance improvements
- feat: add gRPC, email, queue systems, HTTP/2, workers, new middleware and performance improvements
- Version bump to 1.6.8
- feat: add GraphQL and Job Scheduling systems (experimental)
- refactor: restructure GraphQL system with adapter pattern and lazy loading
- fix: revert GraphQL lazy loading, use peer dependency validation instead
- fix: GraphQL integration test timing and moro initializer
- perf: optimize core modules with NOOP fast-paths and string interning
- uWebSockets Performance Optimizations - Significantly reduced framework overhead
- Implemented pre-cached HTTP status strings for common codes (200, 404, 500, etc.)
- Optimized header writing with fast-paths for 0, 1, and 2 headers (most common cases)
- Eliminated Object.entries() allocation overhead in response methods
- Added header key tracking to avoid repeated Object.keys() calls
- Conditional content-type setting to reduce unnecessary operations
- Result: Framework overhead reduced from ~30-45% to ~5% compared to raw uWebSockets
- Performance: MoroJS now delivers 195k+ req/sec (94.71% of raw uWebSockets' 206k req/sec)
- All optimizations maintain 100% API compatibility with standard HTTP server
- Version bump to 1.6.4
- Built-in Middleware Organization - Restructured all built-in middleware into consistent directory patterns
- Moved all middleware from single files to directories with
core.ts,middleware.ts,hook.ts, andindex.ts - Organized auth-related utilities:
auth-helpers.ts,auth-providers.ts, andjwt-helpers.tsmoved intoauth/directory - Applied consistent structure to simple middleware:
request-logger,performance-monitor, anderror-tracker - Improved code organization and maintainability across 11 complex middleware and 3 simple middleware
- All public APIs remain unchanged - fully backward compatible
- Moved all middleware from single files to directories with
- npm Package Size - Removed unnecessary files from published package
- Removed TypeScript source files (
src/**/*) from npm package - Removed build configuration files (
tsconfig.json,jest.config.mjs) - Package now only includes compiled JavaScript (
dist), README, and LICENSE - Significantly reduced package size for faster installations
- Removed TypeScript source files (
- Critical: Republish with correct build - The 1.6.1 npm package was built from outdated code
- Fixed ES module configuration loading (
createAppoptions now work correctly) - Fixed unified router integration
- Fixed object pooling system
- All recent performance and stability improvements now included
- Fixed ES module configuration loading (
⚠️ This version was published with an incorrect build. Please use 1.6.2 instead.
- feat: enhanced routing system with unified router and object pooling
- NEW: High-Performance uWebSockets.js Integration - Optional ultra-fast HTTP server backend
- 10x+ performance improvement over standard Node.js HTTP server
- Full HTTP/HTTPS support with SSL/TLS configuration
- Complete WebSocket support with uWebSockets.js adapter
- Enable with
server.useUWebSockets: trueconfiguration - Seamless fallback to standard Node.js HTTP when not available
- Production-ready with proper error handling and resource cleanup
- BREAKING: Full ESM Module System - Migrated entire codebase to native ES modules
- Updated
package.jsonwith"type": "module" - All imports/exports use ESM syntax
- Better tree-shaking and bundle optimization
- Native TypeScript ESM support
- Improved compatibility with modern JavaScript ecosystem
- Updated
- uWebSockets.js HTTP Server - New
MoroUWebSocketsServerclass for high-performance HTTP handling - uWebSockets.js WebSocket Adapter - Native WebSocket support with uWebSockets.js
- Package Utilities - Helper functions for optional dependency detection and management
- Comprehensive Documentation - New
UWEBSOCKETS_GUIDE.mdwith setup and usage examples - Validation Scripts - Added
validate-dist.mjsandvalidate-package.mjsfor release quality assurance - Jest Configuration - Converted to ESM-compatible
jest.config.mjs - Benchmark Scripts - Added performance benchmarks for uWebSockets.js comparison
- All Core Modules - Updated all imports to use ESM syntax
- WebSocket System - Enhanced WebSocket adapter interface to support multiple implementations
- Configuration System - Added
useUWebSocketsconfiguration option - Type Definitions - Updated TypeScript types for ESM compatibility
- Build System - Optimized for ESM output with proper module resolution
- Script Import Issues - Resolved ESM import errors in release and validation scripts
- Package Exports - Updated package.json exports for proper ESM resolution
- TypeScript Configuration - Fixed module resolution for ESM compatibility
- Zero Breaking Changes for Users - ESM migration is transparent for existing applications
- Performance Benchmarks - Documented 10x+ performance improvements with uWebSockets.js
- Production Ready - All new features fully tested and production-hardened
- Optional Dependencies - uWebSockets.js is optional, framework works without it
No migration required! This release maintains full backward compatibility.
Optional uWebSockets.js Setup:
import { createApp } from '@morojs/moro';
const app = createApp({
server: {
useUWebSockets: true, // Enable high-performance mode
port: 3000,
},
});ESM Benefits:
- Faster startup times
- Better tree-shaking in bundlers
- Native browser compatibility
- Improved type inference
- Auto-Discovery + Auth Middleware Compatibility: Fixed critical issue where auto-discovery could bypass user middleware (like auth)
- Module routes now properly respect the middleware chain order
- Auth middleware is guaranteed to run before module route handlers
- Comprehensive race condition protection and edge case handling
- Enhanced
initModules()API: Added powerful public API for explicit module loading control- Synchronous interface:
app.initModules()- noawaitrequired - Works with disabled auto-discovery: Forces module loading even when
autoDiscover: false - Custom configuration support:
app.initModules({ paths: ['./my-modules'] }) - Identical behavior: Uses same discovery and loading mechanisms as enabled auto-discovery
- Perfect timing: Ensures modules load before server starts, maintaining middleware order
- Synchronous interface:
- JWT Error Handling: Enhanced JWT error detection and handling to provide elegant user-friendly messages
- Improved error detection to catch JWT errors by message content in addition to error name
- Added support for detecting "jwt expired", "invalid token", and "jwt malformed" error messages
- Consistent error handling across main request handler and middleware execution paths
- Prevents stack traces from being exposed to users for JWT-related authentication errors
- Error Response Consistency: Ensured all JWT error handling paths provide clean, user-friendly error responses
- Security: Better separation of technical error details from user-facing error messages
- HTTP Server Architecture: Removed JWT-specific error handling from HTTP server layer - now properly handled in auth middleware
- Separation of Concerns: HTTP server now focuses purely on HTTP protocol concerns, not application-specific authentication
- Cleaner Error Handling: JWT errors are handled elegantly at the middleware level where they belong
- Robust Module Loading: Two-phase module mounting ensures middleware order is preserved
- Race Condition Protection: Auto-discovery initialization is idempotent and handles concurrent calls safely
- Unified Module Loading: All module loading paths now use identical discovery and loading mechanisms
- Native Node.js Glob Support: Replaced
minimatchdependency with nativefs.globfunctionality for better performance and reduced dependencies - Enhanced Configuration System: Comprehensive environment variable support for all module configurations including auto-discovery
- Improved Config Merging: Enhanced
MoroOptionstoAppConfigmerging with properautoDiscoveroption handling
- Auto-Discovery Configuration: Added support for configuring auto-discovery through
modules.autoDiscoveryas the primary method - Environment Variables: Added complete environment variable support for cache, rate limiting, validation, and auto-discovery configurations
- Legacy Compatibility: Enhanced support for legacy
modulesPathoption with proper mapping toautoDiscovery.paths
- Pattern Matching: Fixed glob pattern matching with proper regex conversion and fallback support for older Node.js versions
- MaxDepth Handling: Fixed
maxDepthconfiguration handling in native glob implementation - Configuration Documentation: Updated documentation to clearly show nested
modules.autoDiscoveryas the primary configuration method
- Removed
minimatchfrom dependencies (zero external dependencies for pattern matching) - Added fallback pattern matching for Node.js versions without native
fs.glob - Enhanced configuration validation and merging logic
- Improved cross-platform compatibility for file path handling
- MAJOR: Enhanced Module Auto-Discovery System - Comprehensive overhaul of module auto-discovery with advanced configuration options
- Advanced Configuration: Rich configuration options including paths, patterns, loading strategies, dependency resolution
- Loading Strategies: Support for eager, lazy, and conditional loading with environment-based rules
- Dependency Resolution: Automatic topological sorting for proper module load order
- File Watching: Hot reloading support for development environments (opt-in)
- Error Handling: Graceful degradation with configurable
failOnErroroption - Comprehensive Testing: 45+ test cases covering unit, integration, and performance scenarios
- Backward Compatibility: Maintains support for legacy
autoDiscoverandmodulesPathoptions - Resource Management: Proper cleanup of file watchers to prevent hanging processes
- File Watcher Cleanup: Fixed npm test hanging by properly cleaning up file system watchers
- TypeScript Errors: Resolved all TypeScript compilation issues in auto-discovery system
- Test Directory Pollution: Fixed tests creating temporary files in main project directory
- Package Lock Sync: Updated package-lock.json for minimatch dependency to fix CI/CD compatibility
- fix: Add direct JWT error handling in middleware execution
- ENHANCED: Direct JWT Error Handling in Middleware Execution - Added JWT error handling directly in executeMiddleware method
- Issue: JWT errors were still being thrown from middleware execution even with main handler error catching
- Root Cause: Middleware execution was rejecting JWT errors before they could be caught by main error handler
- Solution: Added JWT error handling directly in both sync and async middleware execution paths
- Impact: JWT errors are now caught and handled immediately at the middleware level
- Coverage: Handles both synchronous and asynchronous middleware JWT errors
- CRITICAL: HTTP Server JWT Error Handling - Fixed unhandled JWT errors in HTTP server middleware execution
- Issue:
TokenExpiredErrorand other JWT errors were crashing the server instead of returning proper HTTP responses - Root Cause: HTTP server's
executeMiddlewaremethod wasn't catching JWT-specific errors from user middleware - Solution: Added specific JWT error handling in
MoroHttpServer.handleRequest()method - Impact: JWT errors now return proper 401 responses instead of crashing the server
- Error Types: Handles
TokenExpiredError,JsonWebTokenError, andNotBeforeErrorgracefully
- Issue:
- NEW: JWT Error Handling Utilities - Added utilities to help users handle JWT errors gracefully in custom middleware
- safeVerifyJWT(): Safely verify JWT tokens with proper error categorization
- extractJWTFromHeader(): Extract JWT tokens from Authorization headers
- createAuthErrorResponse(): Create standardized error responses for JWT failures
- Documentation: Complete guide for migrating from raw jwt.verify() to safe error handling
- RESOLVED: Custom Middleware JWT Crashes - Users with custom auth middleware can now handle TokenExpiredError gracefully
- Issue: Custom middleware using raw jwt.verify() caused server crashes on expired tokens
- Solution: Provided utilities and documentation for proper JWT error handling
- Migration Guide: Clear examples showing before/after patterns for safe JWT verification
- fix: Replace mock JWT implementation with proper dependency checking
- REMOVED: Mock JWT Implementation - Replaced mock JWT with proper dependency checking
- Issue: JWT verification was using mock implementation instead of real jsonwebtoken library
- Impact: JWT tokens were not properly verified in production
- Fix: Now requires
jsonwebtokenpackage with graceful error handling - Enhancement: Proper secret hierarchy (JWT_SECRET env var → jwt.secret config → secret config)
-
CRITICAL: Fixed Authentication Bypass Vulnerability - Chainable route builder
.auth()method now properly enforces authentication- Issue: Routes using
.auth({ roles: ['admin'] })were completely unprotected due to stub implementation - Impact: Critical security vulnerability allowing unauthorized access to protected routes
- Fix: Implemented complete authentication checking in
ExecutableRoute.executeAuth()method - Verification: Routes with
.auth()now return proper 401/403 responses when authentication fails
- Issue: Routes using
-
FIXED: JWT Token Expiration Error Handling - Enhanced JWT error handling to prevent server crashes
- Issue: Unhandled
TokenExpiredErrorexceptions when JWT tokens expire - Impact: Server crashes and poor user experience with expired tokens
- Fix: Added comprehensive JWT error handling for
TokenExpiredError,JsonWebTokenError, andNotBeforeError - Enhancement: Graceful degradation to unauthenticated state instead of throwing exceptions
- Issue: Unhandled
-
NEW: Complete Route-Level Authentication Enforcement - Chainable routes now have identical security as module routes
- Role-based access control:
.auth({ roles: ['admin'] }) - Permission-based access control:
.auth({ permissions: ['read:users'] }) - Optional authentication:
.auth({ optional: true }) - Comprehensive error responses with proper HTTP status codes (401, 403, 500)
- Role-based access control:
-
NEW: Enhanced JWT Error Handling - Production-ready JWT token validation with proper error categorization
- Specific handling for expired tokens (
TokenExpiredError) - Invalid token format detection (
JsonWebTokenError) - Not-yet-active token handling (
NotBeforeError) - Detailed debug logging for token validation issues
- Production implementation examples with
jsonwebtokenlibrary
- Specific handling for expired tokens (
- NEW: Enhanced Module Middleware and Extensibility System - Complete support for custom middleware configurations in module routes
- NEW: Route Property Extensibility - Module routes now support any additional properties through extensible object spreading
- NEW: Authentication Framework Foundation - Built-in support for authentication configurations in module routes
- Role-based access control:
auth: { roles: ['admin', 'moderator'] } - Permission-based access control:
auth: { permissions: ['read:users', 'write:data'] } - Optional authentication:
auth: { optional: true }
- Role-based access control:
- NEW: Comprehensive Authentication Checking - Framework automatically enforces auth configurations with proper HTTP responses
- NEW: TypeScript Interface Enhancement - Full TypeScript support for authentication and custom middleware properties
- Module Route Definition System -
defineModulenow preserves ALL route properties for maximum extensibility - Framework Request Pipeline - Added authentication middleware checking before route handler execution
- Error Response System - Detailed authentication and authorization error messages with proper HTTP status codes
- Type Safety - Enhanced interfaces with index signatures for future middleware expansions
- Extensible Architecture - Route configurations automatically support future middleware without code changes
- Backward Compatibility - 100% compatible with existing modules and route definitions
- Performance Optimized - Authentication checks run early in request pipeline for maximum efficiency
- Developer Experience - Clear error messages and proper TypeScript intellisense for auth configurations
- None - This release maintains full backward compatibility
- CRITICAL: Fix compression middleware ERR_HTTP_HEADERS_SENT errors by removing redundant res.writeHead() calls
- SECURITY: Add comprehensive header-sent checks across all middleware to prevent header conflicts
- Fix SSE middleware missing res.headersSent check before calling res.writeHead()
- Fix Node runtime adapter cookie/redirect methods lacking header-sent validation
- Fix cache middleware setting Cache-Control headers without checking if headers were already sent
- Fix range middleware method chaining causing potential header conflicts
- Enhanced cookie handling with security-aware error management
- Automatic detection of critical cookies (session, auth, csrf)
- Configurable
criticalandthrowOnLateSetoptions for cookie security - Detailed logging with stack traces for debugging late cookie setting
- New header management utilities for public API
res.hasHeader(name)- Check if header existsres.setBulkHeaders(headers)- Set multiple headers safelyres.appendHeader(name, value)- Append to existing headersres.canSetHeaders()- Check if headers can still be setres.getResponseState()- Get complete response state for debugging
- Enhanced TypeScript interfaces with proper intersection types to avoid conflicts
- Prevent silent cookie failures that could break authentication and CSRF protection
- Add comprehensive header timing validation across all response methods
- Improve error visibility for header-related issues that could cause security vulnerabilities
- feat: Add configurable middleware options for body size, request tracking, and error boundary
- feat: major configuration system refactor
- fix: resolve logger color inconsistency and enhance cluster algorithm
- fix: make changelog generation dynamic based on actual commits
- Major logger performance optimizations
- Object pooling for LogEntry objects
- Aggressive level checking with numeric comparisons
- String builder pattern for efficient concatenation
- Buffered output with micro-batching (1ms intervals)
- Fast path optimization for different complexity levels
- Improved timestamp caching (100ms vs 1000ms)
- Static pre-allocated strings for levels and ANSI codes
- Comprehensive pre-release script for GitHub workflow
- Named loggers for better context (MODULE**, SERVICE**, etc.)
- Replaced all console.log statements with proper logger usage
- Fixed Jest open handle issues with proper cleanup
- Performance improvements: 55% faster simple logs, 107% faster complex logs
- Jest open handle issues preventing clean test exits
- Logger performance bottlenecks
- Inconsistent logging across the codebase
All notable changes to the MoroJS framework will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
- Major logger performance optimizations
- Object pooling for LogEntry objects
- Aggressive level checking with numeric comparisons
- String builder pattern for efficient concatenation
- Buffered output with micro-batching (1ms intervals)
- Fast path optimization for different complexity levels
- Improved timestamp caching (100ms vs 1000ms)
- Static pre-allocated strings for levels and ANSI codes
- Comprehensive pre-release script for GitHub workflow
- Named loggers for better context (MODULE**, SERVICE**, etc.)
- Replaced all console.log statements with proper logger usage
- Performance improvements: 55% faster simple logs, 107% faster complex logs
- Jest open handle issues preventing clean test exits
- Logger performance bottlenecks
- Inconsistent logging across the codebase
- CRITICAL: Fixed clustering configuration isolation issue - Resolved shared configuration object problem where all app instances were modifying the same global config
- Each app instance now gets its own deep copy of the configuration
- Clustering configuration now works correctly with both createApp options and moro.config.js
- Environment variables (CLUSTERING_ENABLED, CLUSTER_WORKERS) work as expected
- Configuration precedence: createApp options > moro.config.js > environment variables > defaults
- Fixed configuration isolation in
Moroconstructor and config loader - Enhanced configuration merging to prevent shared object mutations
- Maintained backward compatibility with existing clustering configurations
- Memory leak fixes and ES2022 optimizations - Fixed memory leak in HTTP server object pooling
- Upgraded TypeScript target to ES2022 for better performance
- Optimized garbage collection with modern JavaScript features
- Added Object.hasOwn() for safer property checks
- Used optional chaining for cleaner GC calls
- Improved buffer acquisition with findIndex()
- Consistent performance across benchmark runs
- Better memory management with modern JavaScript features
- Optimized object pooling system
- All 233 tests passing
- ESLint clean (0 errors)
- Prettier formatted
- Production ready
- NEW: Zero-dependency core framework - Core framework now has zero dependencies
- NEW: Universal validation interface - Single ValidationSchema interface supporting multiple validation libraries
- NEW: Optional peer dependencies - All validation libraries (Zod, Joi, Yup, class-validator) are now optional
- NEW: Dynamic validation loading - Validation libraries loaded only when available
- NEW: Universal error handling - Consistent validation error format across all libraries
- NEW: TypeScript-based configuration - Pure TypeScript interfaces replace Zod schemas in core config
- NEW: Complete validation library choice - Users can choose any validation library or none at all
- NEW: Backward compatibility - All existing code works unchanged
- NEW: Smaller bundle size - Reduced framework size with optional dependencies
- NEW: Faster startup - Improved performance with zero core dependencies
- CHANGED: Core configuration - Replaced Zod schemas with TypeScript interfaces
- CHANGED: Environment variable handling - Enhanced type coercion and validation
- CHANGED: Validation middleware - Updated to use universal ValidationSchema interface
- CHANGED: WebSocket validation - Universal validation across HTTP and WebSocket
- CHANGED: Type organization - Moved configuration types to proper types directory
- CHANGED: Dependency management - All validation libraries moved to peerDependencies
- IMPROVED: Bundle optimization - Smaller production bundles
- IMPROVED: Memory usage - Reduced memory footprint
- IMPROVED: Type safety - Enhanced TypeScript integration
- IMPROVED: Error handling - Universal error normalization
- NONE - This release maintains 100% backward compatibility
- NEW: Multi-library validation adapter system - Support for Zod, Joi, Yup, and class-validator with unified interface
- NEW: Schema interface standardization - Common validation interface across all supported validation libraries
- NEW: Advanced validation adapters - Custom validation function support with seamless integration
- NEW: TypeScript validation configuration - Enhanced TypeScript config loading and validation
- NEW: Validation error normalization - Consistent error handling across different validation libraries
- NEW: Socket.IO adapter - Full Socket.IO integration with room management and event handling
- NEW: Native WebSocket adapter - High-performance native WebSocket support with connection pooling
- NEW: WebSocket adapter interface - Standardized interface for different WebSocket implementations
- NEW: Connection management - Advanced connection lifecycle management with cleanup and monitoring
- NEW: TypeScript configuration loader - Advanced TypeScript config file loading with validation
- NEW: Configuration file validation - Schema-based validation for configuration files
- NEW: Enhanced configuration types - Better TypeScript support for configuration options
- NEW: Schema-to-OpenAPI conversion - Automatic OpenAPI schema generation from validation schemas
- NEW: Enhanced OpenAPI generator - Improved OpenAPI documentation generation with better schema support
- NEW: Zod-to-OpenAPI enhancement - Better Zod schema conversion to OpenAPI specifications
- Improved validation system architecture - Better performance and extensibility
- Enhanced WebSocket management - More robust connection handling and error recovery
- Better configuration merging - Improved configuration precedence and validation
- Enhanced test coverage - New comprehensive tests for validation adapters and WebSocket functionality
- Configuration loading edge cases - Better error handling for malformed configuration files
- WebSocket connection cleanup - Proper resource cleanup on connection termination
- Validation error handling - More consistent error messages across validation libraries
- NEW: Enterprise-grade performance optimizations - Object pooling, string interning, and buffer management for ultra-fast request handling
- NEW: Advanced buffer pooling system - Zero-allocation response handling with pre-allocated buffer pools
- NEW: Request handler optimization - Middleware execution caching and minimal object creation overhead
- NEW: String interning for HTTP methods and headers - Massive memory savings through common value caching
- NEW: Pre-compiled response templates - Ultra-fast error responses with zero-allocation buffers
- NEW: Performance configuration API - Fine-grained control over clustering, compression, and circuit breaker settings
- NEW: HTTP server performance tuning - Configurable keep-alive timeouts, headers timeout, and request timeout settings
- NEW: Runtime-aware optimizations - Performance settings that adapt based on the detected runtime environment
- NEW: Minimal mode support - Ultra-lightweight server mode for edge deployments with compression disabled
- NEW: Improved MoroCore initialization - Better configuration passing and runtime-specific optimizations
- NEW: Enhanced middleware system integration - Improved hook manager integration with HTTP server performance
- NEW: Event bus performance improvements - Optimized enterprise event bus with better memory management
- NEW: Container and dependency injection enhancements - Faster service resolution and improved memory efficiency
- NEW: Flexible listen() method overloads - Support for
listen(),listen(callback),listen(port, callback), andlisten(port, host, callback) - NEW: Enhanced logging configuration - Better framework logger configuration from config files and options
- NEW: Improved error handling - More robust error responses with pre-compiled templates
- NEW: Configuration reference documentation - Comprehensive configuration guide for all performance settings
- Improved HTTP server throughput - Up to 50% performance improvement in high-load scenarios
- Enhanced memory management - Reduced garbage collection pressure through object pooling and buffer reuse
- Optimized middleware execution - Faster middleware chain processing with execution caching
- Better request parsing - Optimized parameter object creation and reuse
- Enhanced performance configuration merging - Better precedence handling for performance settings from config files and options
- Improved configuration validation - Better error handling for invalid performance configuration values
- Enhanced documentation integration - Performance settings now properly documented in configuration reference
- Better edge runtime support - Optimized performance settings for edge deployments
- Enhanced Node.js optimizations - Full performance feature set for Node.js runtime
- Improved multi-runtime handling - Runtime-specific performance optimizations
- Fixed buffer pool memory leaks - Proper buffer return and pool size management
- Resolved middleware execution overhead - Eliminated function creation in request handling loops
- Fixed response template caching - Proper pre-compiled response buffer management
- Fixed performance configuration precedence - Config file settings now properly merge with createApp options
- Resolved logging configuration timing - Framework logger configuration now applies correctly during initialization
- Fixed configuration validation edge cases - Better handling of invalid or missing performance configuration
- Buffer pooling system - Pre-allocated buffers for common response sizes (64B to 16KB)
- String interning optimization - Common HTTP methods and headers cached for memory efficiency
- Middleware execution caching - Function-level caching to avoid repeated middleware compilation
- Object pool management - Reusable parameter objects and request state management
- Performance configuration schema - Full typing and validation for all performance settings
- Runtime-aware defaults - Different default performance settings based on detected runtime
- Configuration precedence system - Environment variables → Config file → createApp options
- No breaking changes - All existing applications continue to work without modification
- Optional performance features - Performance optimizations are enabled by default but can be disabled
- Graceful degradation - Framework falls back to standard performance when optimizations are unavailable
Automatic Performance Improvements - No code changes required. Your existing applications will automatically benefit from the performance improvements.
Optional Performance Tuning - You can now fine-tune performance settings:
// moro.config.js
module.exports = {
performance: {
clustering: {
enabled: true,
workers: 'auto',
},
compression: {
enabled: true,
threshold: 1024,
},
circuitBreaker: {
enabled: true,
timeout: 5000,
},
},
};Enhanced listen() Method - New flexible overloads:
// All these are now supported
app.listen(() => console.log('Started on configured port'));
app.listen(3000, () => console.log('Started on port 3000'));
app.listen(3000, 'localhost', () => console.log('Started on localhost:3000'));- CRITICAL: Fixed logger configuration from config files not being applied - Configuration file logging settings (like
logging.level: 'warn') now properly override the global logger - Fixed child logger level inheritance - Framework loggers created with
createFrameworkLogger()now correctly inherit level changes from the parent logger - Fixed configuration timing issue - Logger configuration from config files is now applied after the configuration system initializes, ensuring proper precedence
- Improved configuration application flow - Added proper sequencing: Environment variables → Config file → createApp options (with correct precedence)
- Enhanced child logger architecture - Child loggers now maintain a reference to their parent for proper level inheritance
- Fixed log level checking - Child loggers now respect the parent logger's level when filtering log messages
- Improved configuration validation - Better error handling and validation for invalid log levels and configuration options
- Fixed initialization sequence in
Moroconstructor to apply config file logging settings after config loading - Enhanced
MoroLogger.child()method to maintain parent reference for level inheritance - Updated log level checking logic to use parent level for child loggers
- Maintained backward compatibility with existing logger API
- No breaking changes - This is a pure bug fix release
- Existing applications using config files for logging will now work as expected
- No code changes required for existing applications
- NEW: Complete Auth.js integration - Full-featured authentication middleware with OAuth, JWT, and session support
- Multiple OAuth providers - GitHub, Google, Discord, Microsoft, LinkedIn with easy configuration
- Enterprise SSO providers - Okta, Auth0, AWS Cognito for enterprise deployment
- Role-Based Access Control (RBAC) - Fine-grained permissions and role-based route protection
- Native Auth.js adapter - Custom
@auth/morojsadapter with zero external dependencies, ready for Auth.js contribution
- NEW:
auth()middleware - Complete Auth.js middleware with provider configuration and security features - NEW:
requireAuth()middleware - Route protection with role and permission-based access control - NEW:
requireRole()andrequireAdmin()helpers - Simplified role-based route protection - NEW:
authUtilsutilities - Manual authentication checks, user data access, and session management - NEW:
authResponseshelpers - Standardized authentication response patterns - NEW: Extended provider factories -
extendedProvidersandenterpriseProviderswith advanced configurations
- Session management - JWT and database session strategies with configurable security settings
- CSRF protection - Built-in Cross-Site Request Forgery protection
- Security audit logging - Track authentication events for compliance and monitoring
- Custom callbacks and events - Extensible authentication flow with business logic integration
- Production security - Secure cookies, host trust, and environment-based configuration
- Request/response transformers - Seamless conversion between MoroJS and Auth.js Web API formats
- Hooks system integration - Native integration with MoroJS middleware and hooks architecture
- Zero dependency design - No reliance on Express or other framework adapters
- Performance optimized - Built specifically for MoroJS request/response patterns
- Improved MiddlewareManager - Better middleware installation and execution with hooks integration
- Enhanced HookManager - Proper integration with HTTP request pipeline for reliable middleware execution
- Response enhancement - Robust error handling with defensive fallbacks for HTTP response methods
- NEW: Authentication Guide - Complete guide covering Auth.js integration, RBAC, and security best practices
- NEW: Native Auth Adapter documentation - Comprehensive guide for the custom Auth.js adapter
- Enhanced README - Added authentication as a core feature with examples and benefits
- Updated API documentation - Complete authentication middleware and helper function documentation
- Working authentication examples - Multiple complete examples demonstrating different authentication patterns
- Advanced enterprise example - RBAC, audit logging, and multi-provider authentication patterns
- Native adapter example - Custom adapter usage with Auth.js callbacks and events
- Comprehensive test coverage - 200+ tests covering authentication middleware and integration patterns
- Resolved "res.status is not a function" errors - Enhanced error handling with proper response object validation
- Improved response enhancement - Defensive programming for HTTP response method availability
- Better error recovery - Graceful fallbacks when response objects are not fully enhanced
- Fixed middleware installation - Proper detection and installation of MiddlewareInterface objects
- Resolved hooks execution - Correct integration of HookManager with HTTP request pipeline
- Session dependency resolution - Auth middleware now self-contained without external session dependencies
- Native Auth.js integration - Direct Auth.js core integration without Express dependencies
- Middleware composition - Helper functions for proper middleware chaining in route handlers
- Type safety enhancements - Full TypeScript support for authentication types and middleware
- Production error handling - Robust error handling patterns for enterprise deployment
- Efficient request processing - Optimized auth object injection and session management
- Memory usage optimization - Reduced overhead for authentication operations
- Error handling performance - Fast-path error responses with minimal overhead
- NEW:
moro.config.jsandmoro.config.tssupport - Load configuration from dedicated config files for better developer experience - Automatic configuration discovery - Place config files in project root for zero-setup configuration
- Environment variable override - Config files provide defaults while environment variables take precedence
- TypeScript configuration support - Full type safety and IDE autocompletion for config files
- Backward compatibility - Existing projects work unchanged without any migration needed
- NEW:
createModuleConfig()function - Create module-specific configuration with environment override support - Improved type coercion - Automatic conversion of environment variable strings to appropriate types (numbers, booleans, JSON)
- Better integration - Module configs now properly merge with global application configuration
- Environment prefix support - Use prefixed environment variables for module-specific settings
- Complete configuration guide - Updated API documentation with extensive configuration examples
- Getting Started configuration section - Step-by-step setup guide for new projects
- Configuration examples document - Real-world examples for development, staging, and production environments
- TypeScript configuration examples - Full typing and validation patterns
- Best practices guide - Security, performance, and maintainability recommendations
- Comprehensive test coverage - Full test suite for configuration file loading and module configuration
- Integration tests - End-to-end testing of configuration priority and merging
- Test isolation improvements - Better test cleanup and state management
Configuration is now loaded in the following priority order:
- Environment Variables (highest priority)
- Configuration File (
moro.config.jsormoro.config.ts) - Schema Defaults (lowest priority)
- Synchronous configuration loading - Improved startup performance and reliability
- Better error handling - Graceful fallback when config files have errors
- Enhanced logging - Detailed configuration loading information for debugging
Basic Configuration:
// moro.config.js
module.exports = {
server: {
port: 3000,
host: 'localhost',
environment: 'development',
},
database: {
type: 'postgresql',
host: 'localhost',
port: 5432,
username: 'myapp',
password: 'development-password',
database: 'myapp_dev',
},
security: {
cors: {
enabled: true,
origin: ['http://localhost:3000'],
},
},
};TypeScript Configuration:
// moro.config.ts
import type { AppConfig } from '@morojs/moro';
const config: Partial<AppConfig> = {
server: {
port: 3000,
environment: 'development',
},
// ... other configuration
};
export default config;Module Configuration:
import { createModuleConfig, z } from '@morojs/moro';
const emailConfig = createModuleConfig(
z.object({
apiKey: z.string(),
timeout: z.number().default(5000),
}),
{ timeout: 3000 },
'EMAIL_' // Environment prefix
);No migration required! This release is fully backward compatible. Existing projects will continue to work exactly as before.
Optional upgrade path:
- Create a
moro.config.jsfile in your project root - Move your environment-based configuration to the config file
- Keep sensitive data (passwords, API keys) in environment variables
- Enjoy improved developer experience with IDE autocompletion
None - This release maintains full backward compatibility.
- Core framework functionality
- Intelligent routing system
- Automatic middleware ordering
- Type-safe validation with Zod
- Multi-runtime support (Node.js, Edge, Lambda, Workers)
- WebSocket support
- Database integration
- Performance optimizations
- Comprehensive testing framework
- Documentation: docs/
- Examples: GitHub Examples Repository
- Issues: GitHub Issues
- Community: Discord Community