@morojs/moro 1.8.12 → 1.8.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/core/cluster/thread-cluster.d.ts +25 -0
- package/dist/core/cluster/thread-cluster.js +95 -3
- package/dist/core/cluster/thread-cluster.js.map +1 -1
- package/dist/core/config/config-validator.js +15 -0
- package/dist/core/config/config-validator.js.map +1 -1
- package/dist/core/config/index.js +19 -2
- package/dist/core/config/index.js.map +1 -1
- package/dist/core/framework.d.ts +26 -0
- package/dist/core/framework.js +195 -6
- package/dist/core/framework.js.map +1 -1
- package/dist/core/http/http-server.d.ts +17 -0
- package/dist/core/http/http-server.js +21 -1
- package/dist/core/http/http-server.js.map +1 -1
- package/dist/core/http/http2-server.d.ts +13 -0
- package/dist/core/http/http2-server.js +11 -0
- package/dist/core/http/http2-server.js.map +1 -1
- package/dist/core/http/moro-engine-server.d.ts +28 -0
- package/dist/core/http/moro-engine-server.js +115 -11
- package/dist/core/http/moro-engine-server.js.map +1 -1
- package/dist/core/http/utils/body-type.d.ts +12 -0
- package/dist/core/http/utils/body-type.js +70 -0
- package/dist/core/http/utils/body-type.js.map +1 -0
- package/dist/core/http/utils/ssl-config.d.ts +11 -0
- package/dist/core/http/utils/ssl-config.js +3 -0
- package/dist/core/http/utils/ssl-config.js.map +1 -1
- package/dist/core/http/utils/uws-worker-clustering.js +5 -4
- package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
- package/dist/core/http/uws-http-server.d.ts +3 -0
- package/dist/core/http/uws-http-server.js +22 -1
- package/dist/core/http/uws-http-server.js.map +1 -1
- package/dist/core/middleware/built-in/body-parsers/index.d.ts +18 -0
- package/dist/core/middleware/built-in/body-parsers/index.js +41 -0
- package/dist/core/middleware/built-in/body-parsers/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.d.ts +32 -8
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js +117 -25
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js.map +1 -1
- package/dist/core/middleware/built-in/compression/core.js +5 -0
- package/dist/core/middleware/built-in/compression/core.js.map +1 -1
- package/dist/core/middleware/built-in/session/core.d.ts +1 -0
- package/dist/core/middleware/built-in/session/core.js.map +1 -1
- package/dist/core/middleware/built-in/static/core.d.ts +18 -0
- package/dist/core/middleware/built-in/static/core.js +128 -7
- package/dist/core/middleware/built-in/static/core.js.map +1 -1
- package/dist/core/networking/adapters/engine-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/engine-adapter.js +40 -1
- package/dist/core/networking/adapters/engine-adapter.js.map +1 -1
- package/dist/core/networking/adapters/socketio-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/socketio-adapter.js +10 -1
- package/dist/core/networking/adapters/socketio-adapter.js.map +1 -1
- package/dist/core/networking/adapters/uws-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/uws-adapter.js +54 -3
- package/dist/core/networking/adapters/uws-adapter.js.map +1 -1
- package/dist/core/networking/adapters/ws-adapter.d.ts +9 -2
- package/dist/core/networking/adapters/ws-adapter.js +97 -12
- package/dist/core/networking/adapters/ws-adapter.js.map +1 -1
- package/dist/core/networking/websocket-adapter.d.ts +19 -1
- package/dist/core/networking/websocket-adapter.js.map +1 -1
- package/dist/core/routing/index.d.ts +12 -8
- package/dist/core/routing/index.js +7 -2
- package/dist/core/routing/index.js.map +1 -1
- package/dist/core/routing/unified-router.d.ts +46 -8
- package/dist/core/routing/unified-router.js +108 -32
- package/dist/core/routing/unified-router.js.map +1 -1
- package/dist/core/utilities/package-utils.d.ts +7 -0
- package/dist/core/utilities/package-utils.js +2 -0
- package/dist/core/utilities/package-utils.js.map +1 -1
- package/dist/core/workers/worker-manager.js +2 -2
- package/dist/core/workers/worker-manager.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/moro.d.ts +12 -1
- package/dist/moro.js +63 -7
- package/dist/moro.js.map +1 -1
- package/dist/types/cache.d.ts +2 -0
- package/dist/types/cache.js.map +1 -1
- package/dist/types/config.d.ts +9 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/http.d.ts +6 -0
- package/dist/types/http.js.map +1 -1
- package/dist/types/session.d.ts +1 -0
- package/dist/types/session.js.map +1 -1
- package/package.json +1 -1
package/dist/moro.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"moro.js","sourceRoot":"","sources":["../src/moro.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,8EAA8E;AAC9E,8DAA8D;AAC9D,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAMvD,OAAO,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAE1F,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAE9E,OAAO,EACL,aAAa,GAEd,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAc,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,8EAA8E;AAC9E,0EAA0E;AAC1E,uCAAuC;AACvC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,cAAc,CAAwC,SAAS,CAAC,CAAC;AAC3F,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,cAAc,CAAkC,gBAAgB,CAAC,CAAC;AACnF,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,EACvB,gBAAgB,EAChB,6BAA6B,GAE9B,MAAM,kCAAkC,CAAC;AAC1C,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AM,CAAC,CAAC;AACzC,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,OAAsC;IAC1E,MAAM,aAAa,GAAG,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,oBAA6B,EAAE,EAAE,CAAC;IACvF,kBAAkB,CAAC,aAAa,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,MAAM,qBAAqB,CAAC,aAAa,CAAC,CAAC;IAC1D,OAAO,IAAI,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// Moro Framework - Modern TypeScript API Framework\n// Built for developers who demand performance, elegance, and zero compromises\n// Event-driven • Modular • Enterprise-ready • Developer-first\nimport { Moro as MoroCore } from './core/framework.js';\nimport { HttpRequest, HttpResponse } from './core/http/index.js';\nimport { ModuleConfig, InternalRouteDefinition } from './types/module.js';\nimport { MoroOptions } from './types/core.js';\nimport { ModuleDefaultsConfig } from './types/config.js';\nimport { MoroEventBus } from './core/events/index.js';\nimport { createFrameworkLogger, applyLoggingConfiguration } from './core/logger/index.js';\nimport { Logger } from './types/logger.js';\nimport { MiddlewareManager, MIDDLEWARE_FACTORY } from './core/middleware/index.js';\nimport { IntelligentRoutingManager } from './core/routing/app-integration.js';\nimport { RouteSchema, StaticBody } from './core/routing/index.js';\nimport {\n UnifiedRouter,\n RouteBuilder as UnifiedRouteBuilder,\n} from './core/routing/unified-router.js';\nimport { PathMatcher } from './core/routing/path-matcher.js';\nimport { AppDocumentationManager, DocsConfig } from './core/docs/index.js';\nimport { EventEmitter } from 'events';\nimport { requireBuiltin } from './core/utilities/builtin.js';\n\n// node:cluster (it drags in child_process, dgram and net) is loaded only when\n// process clustering actually runs; worker_threads only on the clustering\n// path. See core/utilities/builtin.ts.\nconst nodeCluster = () => requireBuiltin<(typeof import('cluster'))['default']>('cluster');\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport {\n ThreadClusterPrimary,\n ThreadClusterWorker,\n computeWorkerCount,\n isUserTunedYoungGen,\n resolveClusterTransport,\n threadWorkerInfo,\n YOUNG_GEN_MB_FOR_SEMI_SPACE_4,\n type ThreadWorkerInfo,\n} from './core/cluster/thread-cluster.js';\nimport { normalizeValidationError } from './core/validation/schema-interface.js';\nimport { buildModuleBasePath } from './core/utilities/module-path.js';\nimport { filePathToImportURL, loadNativeEngine } from './core/utilities/package-utils.js';\n// Configuration System Integration\nimport { initializeConfig, initializeConfigAsync, type AppConfig } from './core/config/index.js';\n// Runtime System Integration\nimport { RuntimeAdapter, RuntimeType, createRuntimeAdapter } from './core/runtime/index.js';\n// Job System Integration\nimport {\n JobScheduler,\n JobSchedulerOptions,\n JobHealthChecker,\n everyInterval,\n cronSchedule,\n} from './core/jobs/index.js';\nimport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n LeaderElectionOptions,\n} from './core/jobs/index.js';\n// Worker Threads Integration (optional - lazy loaded when needed)\nimport { WorkerThreadsFacade, type WorkerTask } from './core/workers/index.js';\n// GraphQL System Integration (lazy loaded)\nimport type { GraphQLOptions } from './core/graphql/types.js';\n// gRPC System Integration (lazy loaded)\nimport type {\n GrpcOptions,\n ServiceImplementation,\n GrpcClient,\n GrpcClientOptions,\n} from './core/grpc/types.js';\n// Built-in middleware integration\n// Mail System Integration (lazy loaded)\nimport type { MailConfig, MailOptions, MailResult } from './core/mail/types.js';\n\n// Lazy imports for GraphQL to avoid crashes when not installed\nlet GraphQLCore: any;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nlet GraphQLSubscriptionManager: any;\nlet setupGraphQLSubscriptions: any;\n\n/**\n * Route group — prefixes all registered paths with a common base path.\n *\n * @example\n * app.group('/api/v1', (group) => {\n * group.get('/users').handler(getUsersHandler);\n * group.post('/users').handler(createUserHandler);\n * group.get('/users/:id').handler(getUserHandler);\n * });\n */\nexport class RouteGroup {\n private prefix: string;\n private app: Moro;\n\n constructor(prefix: string, app: Moro) {\n this.prefix = prefix;\n this.app = app;\n }\n\n private prefixPath(path: string): string {\n if (path === '/' || path === '') return this.prefix;\n return this.prefix + (path.startsWith('/') ? path : `/${path}`);\n }\n\n get(path: string): UnifiedRouteBuilder;\n get(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n get(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('GET', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.get(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n post(path: string): UnifiedRouteBuilder;\n post(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n post(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('POST', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.post(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n put(path: string): UnifiedRouteBuilder;\n put(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n put(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('PUT', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.put(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n delete(path: string): UnifiedRouteBuilder;\n delete(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n delete(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('DELETE', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.delete(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n patch(path: string): UnifiedRouteBuilder;\n patch(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n patch(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('PATCH', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.patch(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n head(path: string): UnifiedRouteBuilder;\n head(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n head(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('HEAD', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.head(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n options(path: string): UnifiedRouteBuilder;\n options(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n options(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('OPTIONS', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.options(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n /** Register a handler for all HTTP methods on the given path (Express-compatible). */\n all(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this {\n this.app.all(this.prefixPath(path), handler, options);\n return this;\n }\n\n group(prefix: string, callback: (group: RouteGroup) => void): this {\n const nested = new RouteGroup(this.prefixPath(prefix), this.app);\n callback(nested);\n return this;\n }\n}\n\nexport class Moro extends EventEmitter {\n private coreFramework!: MoroCore;\n private routes: InternalRouteDefinition[] = [];\n private moduleCounter = 0;\n private loadedModules = new Set<string>();\n private lazyModules = new Map<string, ModuleConfig>();\n private routeHandlers: Record<string, CallableFunction> = {};\n private moduleDiscovery?: any; // Store for cleanup\n private autoDiscoveryOptions: MoroOptions | null = null;\n private autoDiscoveryInitialized = false;\n private autoDiscoveryPromise: Promise<void> | null = null;\n // File-based auto routing state\n private routesLoaded = false;\n private routesLoadedPromise: Promise<void> | null = null;\n // Enterprise event system integration\n private eventBus!: MoroEventBus;\n // Application logger\n private logger!: Logger;\n // Unified routing system (singleton - shared across all routers)\n private unifiedRouter!: UnifiedRouter;\n // Legacy intelligent routing (kept for backward compatibility, now a facade)\n private intelligentRouting!: IntelligentRoutingManager;\n // Documentation system\n private documentation = new AppDocumentationManager();\n // Configuration system\n private config!: AppConfig;\n // Track if user explicitly set logger options (for worker log level handling)\n private userSetLogger = false;\n // Runtime system\n private runtimeAdapter!: RuntimeAdapter;\n private runtimeType!: RuntimeType;\n // Middleware system\n private middlewareManager!: MiddlewareManager;\n // Queued WebSocket registrations (for async adapter detection)\n private queuedWebSocketRegistrations: Array<{\n namespace: string;\n handlers: Record<string, CallableFunction>;\n processed: boolean;\n }> = [];\n // Job scheduling system\n private jobScheduler?: JobScheduler;\n private jobHealthChecker?: JobHealthChecker;\n private jobsStarted = false;\n // GraphQL system\n private graphqlCore?: any; // Use any to avoid import dependency\n private graphqlSubscriptionManager?: any;\n private graphqlInitPromise?: Promise<void>;\n private graphqlConfig?: any; // Store config for lazy initialization\n // gRPC system (lazy loaded)\n private grpcManager?: any; // Use any to avoid import dependency\n private grpcInitPromise?: Promise<void>;\n private grpcStarted = false;\n private grpcConfig?: any; // Store config for lazy initialization\n // Queue system (lazy loaded)\n private queueManager?: any; // Use any to avoid import dependency\n private queueInitialized = false;\n private queueInitPromise?: Promise<void> | undefined; // Track initialization promise\n private queueConfigs: Map<string, any> = new Map(); // Store queue configs for lazy initialization\n // Worker threads system (lazy loaded facade)\n private workerFacade: WorkerThreadsFacade;\n // Mail system (lazy loaded)\n private mailManager?: any; // Use any to avoid import dependency\n private mailInitialized = false;\n private mailConfig?: any; // Store config for lazy initialization\n // User-registered shutdown hooks (run during close())\n private closeHooks: Array<() => any | Promise<any>> = [];\n // User-registered global error handler\n private errorHandler?: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n // Decorations applied to every request/response/app\n private requestDecorations: Record<string, any> = {};\n private responseDecorations: Record<string, any> = {};\n\n constructor(options: MoroOptions = {}, preloadedConfig?: Readonly<AppConfig>) {\n super(); // Call EventEmitter constructor\n\n // Track if user explicitly set logger/logging options\n this.userSetLogger = !!(options.logger || options.logging);\n\n // Apply logging configuration BEFORE config loading to avoid DEBUG spam\n // 1. Environment variables (base level)\n const envLogLevel = process.env.LOG_LEVEL || process.env.MORO_LOG_LEVEL;\n if (envLogLevel) {\n applyLoggingConfiguration({ level: envLogLevel }, undefined);\n }\n\n // 2. createApp logger options (highest precedence)\n if (options.logger !== undefined) {\n applyLoggingConfiguration(undefined, options.logger);\n }\n\n // Create logger AFTER initial configuration\n this.logger = createFrameworkLogger('App');\n\n // Use pre-loaded config (from async createApp factory) when available,\n // otherwise fall back to synchronous loading (env vars + options, no file)\n this.config = preloadedConfig ?? initializeConfig(options);\n\n // Apply final config logging (this includes normalized logger → logging conversion)\n // Always apply this as it's the authoritative merged config\n if (this.config.logging) {\n applyLoggingConfiguration(this.config.logging, undefined);\n // Recreate logger with updated config\n this.logger = createFrameworkLogger('App');\n }\n\n // NOW initialize routing systems AFTER logger is configured\n this.unifiedRouter = UnifiedRouter.getInstance();\n this.intelligentRouting = new IntelligentRoutingManager();\n\n this.logger.info(\n `Configuration system initialized: ${process.env.NODE_ENV || 'development'}:${this.config.server.port}`\n );\n\n // Initialize runtime system\n this.runtimeType = options.runtime?.type || 'node';\n this.runtimeAdapter = options.runtime?.adapter || createRuntimeAdapter(this.runtimeType);\n\n this.logger.info(`Runtime system initialized: ${this.runtimeType}`, 'Runtime');\n\n // Pass configuration from config to framework\n const frameworkOptions: any = {\n ...options,\n logger: this.config.logging,\n // Enable websockets if either config has it enabled OR user passed websocket options\n websocket:\n this.config.websocket.enabled || options.websocket\n ? options.websocket || this.config.websocket || {}\n : false,\n config: this.config,\n };\n\n this.coreFramework = new MoroCore(frameworkOptions);\n\n // Initialize middleware system\n this.middlewareManager = new MiddlewareManager();\n\n // Expose the manager to the core framework so module routes can resolve\n // user-installed middleware by name (middleware: ['myMiddleware'])\n this.coreFramework.getContainer().register('middlewareManager', () => this.middlewareManager);\n\n // Integrate hooks system with HTTP server\n const httpServer = (this.coreFramework as any).httpServer;\n if (httpServer && httpServer.setHookManager) {\n httpServer.setHookManager((this.middlewareManager as any).hooks);\n // The router swallows handler errors (it produces the 500), so it needs\n // the hook manager too for 'error' hooks to observe them.\n this.unifiedRouter.setHookManager((this.middlewareManager as any).hooks);\n }\n\n // Configure HTTP server performance based on config\n if (httpServer && httpServer.configurePerformance) {\n const performanceConfig = this.config.performance;\n httpServer.configurePerformance({\n compression: performanceConfig?.compression || { enabled: true },\n minimal: performanceConfig?.compression?.enabled === false, // Enable minimal mode if compression disabled\n });\n }\n\n // Access enterprise event bus from core framework\n this.eventBus = (this.coreFramework as any).eventBus;\n\n // Initialize job scheduler if enabled in config\n // Default to enabled (true) unless explicitly disabled\n const jobsEnabled = this.config.jobs?.enabled !== false && options.jobs?.enabled !== false;\n if (jobsEnabled) {\n const le = this.config.jobs?.leaderElection;\n const leaderElectionOptions: LeaderElectionOptions | undefined =\n le?.enabled !== false\n ? {\n strategy: (le?.strategy as 'file' | 'redis' | 'none') ?? 'file',\n ...(le?.lockPath !== undefined ? { lockPath: le.lockPath } : {}),\n ...(le?.lockTimeout !== undefined ? { lockTimeout: le.lockTimeout } : {}),\n ...(le?.heartbeatInterval !== undefined\n ? { heartbeatInterval: le.heartbeatInterval }\n : {}),\n }\n : undefined;\n\n const jobs = this.config.jobs;\n const jobSchedulerOptions: JobSchedulerOptions = {\n enableLeaderElection: jobs?.leaderElection?.enabled !== false,\n ...(jobs?.maxConcurrentJobs !== undefined\n ? { maxConcurrentJobs: jobs.maxConcurrentJobs }\n : {}),\n ...(leaderElectionOptions !== undefined ? { leaderElection: leaderElectionOptions } : {}),\n ...(jobs?.executor !== undefined ? { executor: jobs.executor } : {}),\n ...(jobs?.stateManager !== undefined ? { stateManager: jobs.stateManager } : {}),\n ...(jobs?.gracefulShutdownTimeout !== undefined\n ? { gracefulShutdownTimeout: jobs.gracefulShutdownTimeout }\n : {}),\n };\n\n this.jobScheduler = new JobScheduler(createFrameworkLogger('Jobs'), jobSchedulerOptions);\n\n this.jobHealthChecker = new JobHealthChecker(\n this.jobScheduler,\n createFrameworkLogger('JobHealth')\n );\n\n this.logger.info('Job scheduler initialized', 'Jobs', {\n maxConcurrentJobs: jobSchedulerOptions.maxConcurrentJobs,\n leaderElection: jobSchedulerOptions.enableLeaderElection,\n });\n }\n\n // Initialize worker threads facade (optional - lazy loaded)\n this.workerFacade = new WorkerThreadsFacade();\n\n // Eagerly initialize the worker pool when configured via createApp options.\n // Without this option the pool is created lazily on first worker usage.\n if (options.workers && options.workers.enabled !== false) {\n const workerOptions = {\n ...(options.workers.count !== undefined ? { workerCount: options.workers.count } : {}),\n ...(options.workers.maxQueueSize !== undefined\n ? { maxQueueSize: options.workers.maxQueueSize }\n : {}),\n };\n void this.workerFacade.ensureInitialized(workerOptions).then(() => {\n this.logger.info('Worker thread pool initialized', 'Workers', workerOptions);\n });\n }\n\n // Setup default middleware if enabled - use config defaults with options override\n this.setupDefaultMiddleware({\n ...this.getDefaultOptionsFromConfig(),\n ...options,\n });\n\n // Store auto-discovery options for later initialization\n // IMPORTANT: Auto-discovery is deferred to ensure user middleware (like auth)\n // is registered before module middleware that might bypass it\n this.autoDiscoveryOptions = options.autoDiscover !== false ? options : null;\n\n // Emit initialization event through enterprise event bus\n void this.eventBus.emit('framework:initialized', {\n options,\n config: this.config,\n runtime: this.runtimeType,\n });\n }\n\n /**\n * Get configuration object\n */\n getConfig(): AppConfig {\n return this.config;\n }\n\n /**\n * Get runtime adapter\n */\n getRuntime(): RuntimeAdapter {\n return this.runtimeAdapter;\n }\n\n /**\n * Get runtime type\n */\n getRuntimeType(): RuntimeType {\n return this.runtimeType;\n }\n\n /**\n * Extract default options from configuration\n */\n private getDefaultOptionsFromConfig(): Partial<MoroOptions> {\n return {\n cors: this.config.security.cors.enabled,\n compression: this.config.performance.compression.enabled,\n helmet: this.config.security.helmet.enabled,\n };\n }\n\n // Intelligent route methods - chainable with automatic middleware ordering\n // Overloads for better TypeScript inference\n get(path: string): UnifiedRouteBuilder;\n get(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n get(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('GET', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.get(path);\n }\n\n post(path: string): UnifiedRouteBuilder;\n post(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n post(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('POST', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.post(path);\n }\n\n put(path: string): UnifiedRouteBuilder;\n put(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n put(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('PUT', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.put(path);\n }\n\n delete(path: string): UnifiedRouteBuilder;\n delete(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n delete(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('DELETE', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.delete(path);\n }\n\n patch(path: string): UnifiedRouteBuilder;\n patch(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n patch(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('PATCH', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.patch(path);\n }\n\n head(path: string): UnifiedRouteBuilder;\n head(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n head(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n return this.addRoute('HEAD', path, handler, options);\n }\n return this.unifiedRouter.head(path);\n }\n\n options(path: string): UnifiedRouteBuilder;\n options(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n options(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n return this.addRoute('OPTIONS', path, handler, options);\n }\n return this.unifiedRouter.options(path);\n }\n\n /**\n * Register a handler for all HTTP methods on the given path (Express-compatible).\n * Handler is required — unlike the single-method registrations, there's no builder\n * form since `all()` fans out across methods.\n */\n all(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n for (const method of methods) {\n this.addRoute(method, path, handler, options);\n }\n return this;\n }\n\n // Schema-first route method\n route(schema: RouteSchema): void {\n // Use unified router for schema-first registration\n this.unifiedRouter.route(schema);\n }\n\n // Route grouping with common prefix\n group(prefix: string, callback: (group: RouteGroup) => void): this {\n const normalizedPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n const group = new RouteGroup(normalizedPrefix, this);\n callback(group);\n return this;\n }\n\n /**\n * Auto-load route files from a directory.\n *\n * Loads top-level .ts/.js files and index.ts from subdirectories.\n * Other files in subdirectories are ignored — they get pulled in\n * when their index.ts imports them.\n *\n * @example\n * await app.loadRoutes('./src/routes');\n *\n * // routes/\n * // health.ts → loaded\n * // auth/\n * // index.ts → loaded\n * // actions.ts → ignored (imported by index.ts)\n */\n async loadRoutes(dir: string): Promise<void> {\n const { readdirSync, statSync } = await import('fs');\n const { join, extname, resolve } = await import('path');\n const { filePathToImportURL } = await import('./core/utilities/package-utils.js');\n\n const fullPath = resolve(dir);\n const extensions = ['.ts', '.js'];\n\n let items: string[];\n try {\n items = readdirSync(fullPath);\n } catch {\n return;\n }\n\n for (const item of items) {\n const itemPath = join(fullPath, item);\n\n try {\n const stat = statSync(itemPath);\n\n if (stat.isDirectory()) {\n // Subdirectory — only load index.ts or index.js\n for (const ext of extensions) {\n const indexPath = join(itemPath, `index${ext}`);\n try {\n if (statSync(indexPath).isFile()) {\n const importURL = filePathToImportURL(indexPath);\n await import(importURL);\n this.logger.info(`Auto-loaded route: ${item}/index${ext}`, 'RouteLoader');\n break;\n }\n } catch {\n // No index file with this extension, try next\n }\n }\n continue;\n }\n\n // Top-level file\n const ext = extname(item);\n if (!extensions.includes(ext)) continue;\n if (item.includes('.test.') || item.includes('.spec.')) continue;\n\n const importURL = filePathToImportURL(itemPath);\n await import(importURL);\n this.logger.info(`Auto-loaded route: ${item}`, 'RouteLoader');\n } catch (error) {\n this.logger.warn(`Failed to load route file: ${item}`, 'RouteLoader', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n // Enable automatic API documentation\n enableDocs(config: DocsConfig): void {\n this.documentation.enableDocs(config, this.intelligentRouting);\n\n this.logger.info(`API Documentation enabled at ${config.basePath || '/docs'}`, 'Documentation');\n void this.eventBus.emit('docs:enabled', { config });\n }\n\n // Get OpenAPI specification\n getOpenAPISpec() {\n return this.documentation.getOpenAPISpec();\n }\n\n // Get documentation as JSON\n getDocsJSON(): string {\n return this.documentation.getDocsJSON();\n }\n\n // Get documentation as YAML\n getDocsYAML(): string {\n return this.documentation.getDocsYAML();\n }\n\n // Refresh documentation (useful after adding routes dynamically)\n refreshDocs(): void {\n this.documentation.refreshDocs();\n }\n\n // Universal middleware system - seamlessly handles standard and advanced middleware\n async use(middlewareOrFunction: any, config?: any) {\n // `app.use(pathPrefix, router)` — mount a createRouter() instance at the given prefix\n if (\n typeof middlewareOrFunction === 'string' &&\n config &&\n typeof config === 'object' &&\n config._morojsRouter === true &&\n typeof config.mount === 'function'\n ) {\n config.mount(this, middlewareOrFunction);\n return this;\n }\n\n // `app.use(router)` — mount a createRouter() instance at the root\n if (\n middlewareOrFunction &&\n typeof middlewareOrFunction === 'object' &&\n middlewareOrFunction._morojsRouter === true &&\n typeof middlewareOrFunction.mount === 'function'\n ) {\n middlewareOrFunction.mount(this, '');\n return this;\n }\n\n // Built-in factory passed uncalled (app.use(middleware.helmet) instead of\n // app.use(middleware.helmet())). The arity dispatch below would misroute it\n // as an app-plugin and silently discard the result — fail loudly instead.\n if (\n typeof middlewareOrFunction === 'function' &&\n (middlewareOrFunction as any)[MIDDLEWARE_FACTORY]\n ) {\n throw new Error(\n `Built-in middleware factory '${middlewareOrFunction.name || 'unknown'}' was passed uncalled. ` +\n `Call it first: app.use(factory(options)) — e.g. app.use(middleware.helmet()).`\n );\n }\n\n // Standard middleware integration (req, res, next pattern)\n if (typeof middlewareOrFunction === 'function' && middlewareOrFunction.length >= 3) {\n this.coreFramework.addMiddleware(middlewareOrFunction);\n void this.eventBus.emit('middleware:registered', {\n type: 'standard',\n middleware: middlewareOrFunction,\n });\n return this;\n }\n\n // Function-style middleware execution\n if (typeof middlewareOrFunction === 'function' && middlewareOrFunction.length <= 1) {\n await middlewareOrFunction(this);\n void this.eventBus.emit('middleware:executed', {\n type: 'function',\n middleware: middlewareOrFunction,\n });\n return this;\n }\n\n // Advanced middleware pipeline integration - check if it's a MiddlewareInterface\n if (\n middlewareOrFunction &&\n typeof middlewareOrFunction === 'object' &&\n middlewareOrFunction.install &&\n middlewareOrFunction.metadata\n ) {\n // This is a MiddlewareInterface object - install it with the MiddlewareManager\n this.logger.debug(\n `Installing MiddlewareInterface: ${middlewareOrFunction.metadata.name}`,\n 'Middleware'\n );\n this.middlewareManager.install(middlewareOrFunction, config);\n return this;\n }\n\n // Fallback: emit event for unknown middleware types\n void this.eventBus.emit('middleware:advanced', {\n middleware: middlewareOrFunction,\n config,\n });\n this.logger.debug(\n 'Advanced middleware integration - enhanced capabilities loading...',\n 'Middleware'\n );\n return this;\n }\n\n // Plugin compatibility layer - unified middleware interface\n async plugin(middleware: any, options?: any): Promise<this> {\n return this.use(middleware, options);\n }\n\n /**\n * Register a shutdown hook. Hooks run (in registration order) during app.close(),\n * before Moro tears down its own subsystems. Use for closing DB pools, external\n * connections, flushing metrics, etc.\n */\n onClose(fn: () => any | Promise<any>): this {\n this.closeHooks.push(fn);\n return this;\n }\n\n /**\n * Register a global error handler. Invoked when a middleware/handler throws or\n * calls next(err), and no 4-arg error middleware has already handled it. Coexists\n * with Express-style 4-arg error middlewares.\n */\n setErrorHandler(fn: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>): this {\n this.errorHandler = fn;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setErrorHandler) {\n httpServer.setErrorHandler(fn);\n }\n this.unifiedRouter.setErrorHandler(fn as any);\n return this;\n }\n\n /** Internal: retrieve the registered error handler (used by the HTTP server). */\n getErrorHandler():\n ((err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>) | undefined {\n return this.errorHandler;\n }\n\n /**\n * Decorate every request with a property. The value is assigned by reference to\n * each incoming request (use a per-request middleware to set per-request values).\n */\n decorateRequest(name: string, value: any): this {\n this.requestDecorations[name] = value;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setRequestDecorations) {\n httpServer.setRequestDecorations(this.requestDecorations);\n }\n return this;\n }\n\n /** Decorate every response with a property (see decorateRequest). */\n decorateReply(name: string, value: any): this {\n this.responseDecorations[name] = value;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setResponseDecorations) {\n httpServer.setResponseDecorations(this.responseDecorations);\n }\n return this;\n }\n\n /** Alias for decorateReply (Fastify-compatible name). */\n decorateResponse(name: string, value: any): this {\n return this.decorateReply(name, value);\n }\n\n /** Decorate the app instance itself. */\n decorate(name: string, value: any): this {\n (this as any)[name] = value;\n return this;\n }\n\n // Module loading with events\n async loadModule(moduleOrPath: ModuleConfig | string) {\n void this.eventBus.emit('module:loading', {\n moduleId: typeof moduleOrPath === 'string' ? moduleOrPath : moduleOrPath.name,\n });\n\n if (typeof moduleOrPath === 'string') {\n const module = await this.importModule(moduleOrPath);\n await this.coreFramework.loadModule(module);\n this.loadedModules.add(moduleOrPath);\n void this.eventBus.emit('module:loaded', {\n moduleId: module.name,\n version: module.version || '1.0.0',\n });\n } else {\n await this.coreFramework.loadModule(moduleOrPath);\n this.loadedModules.add(moduleOrPath.name);\n void this.eventBus.emit('module:loaded', {\n moduleId: moduleOrPath.name,\n version: moduleOrPath.version || '1.0.0',\n });\n }\n\n // IMPORTANT: If modules are loaded manually after auto-discovery,\n // ensure the final module handler is set up to maintain middleware order\n if (this.autoDiscoveryInitialized) {\n this.coreFramework.setupFinalModuleHandler();\n }\n\n return this;\n }\n\n // Database helper with events\n database(adapter: any) {\n void this.eventBus.emit('database:connected', {\n adapter: adapter.constructor.name,\n config: 'hidden',\n });\n this.coreFramework.registerDatabase(adapter);\n return this;\n }\n\n // WebSocket helper with events\n websocket(namespace: string, handlers: Record<string, CallableFunction>) {\n // Queue the registration to be processed after adapter initialization\n const registration = { namespace, handlers, processed: false };\n this.queuedWebSocketRegistrations.push(registration);\n\n // Try to process immediately if adapter is already ready\n const adapter = this.coreFramework.getWebSocketAdapter();\n if (adapter && !registration.processed) {\n // Adapter is ready, process immediately\n this.processWebSocketRegistration(namespace, handlers, adapter);\n registration.processed = true;\n }\n // Otherwise, it will be processed when the server starts\n\n return this;\n }\n\n private processWebSocketRegistration(\n namespace: string,\n handlers: Record<string, CallableFunction>,\n adapter: any\n ) {\n this.emit('websocket:registering', { namespace, handlers });\n\n const ns = adapter.createNamespace(namespace);\n\n Object.entries(handlers).forEach(([event, handler]) => {\n ns.on('connection', (socket: any) => {\n this.emit('websocket:connection', { namespace, event, socket });\n\n socket.on(event, (data: any, callback: any) => {\n this.emit('websocket:event', { namespace, event, data });\n\n Promise.resolve(handler(socket, data))\n .then((result: any) => {\n this.emit('websocket:response', { namespace, event, result });\n if (callback) callback(result);\n else if (result) socket.emit(`${event}:response`, result);\n })\n .catch((error: any) => {\n this.emit('websocket:error', { namespace, event, error });\n const errorResponse = { success: false, error: error.message };\n if (callback) callback(errorResponse);\n else socket.emit('error', errorResponse);\n });\n });\n });\n });\n\n this.emit('websocket:registered', { namespace, handlers });\n }\n\n private async processQueuedWebSocketRegistrations() {\n // Wait for WebSocket adapter to be ready\n await this.coreFramework.ensureWebSocketReady();\n\n const adapter = this.coreFramework.getWebSocketAdapter();\n\n // Check if any unprocessed registrations exist\n const unprocessedRegistrations = this.queuedWebSocketRegistrations.filter(r => !r.processed);\n\n if (!adapter && unprocessedRegistrations.length > 0) {\n throw new Error(\n 'WebSocket features require a WebSocket adapter.\\n\\n' +\n 'Option 1: Install socket.io (auto-detected):\\n' +\n ' npm install socket.io\\n' +\n ' const app = new Moro({ websocket: {} });\\n\\n' +\n 'Option 2: Configure a specific adapter:\\n' +\n \" import { SocketIOAdapter } from '@morojs/moro';\\n\" +\n ' const app = new Moro({ websocket: { adapter: new SocketIOAdapter() } });\\n\\n' +\n 'Option 3: Enable in config file (moro.config.js):\\n' +\n ' export default { websocket: { enabled: true } };'\n );\n }\n\n if (adapter) {\n // Process all unprocessed registrations\n for (const registration of this.queuedWebSocketRegistrations) {\n if (!registration.processed) {\n this.processWebSocketRegistration(registration.namespace, registration.handlers, adapter);\n registration.processed = true;\n }\n }\n }\n }\n\n // Start server with events (Node.js only)\n listen(callback?: () => void): void;\n listen(port: number, callback?: () => void): void;\n listen(port: number, host: string, callback?: () => void): void;\n listen(\n portOrCallback?: number | (() => void),\n hostOrCallback?: string | (() => void),\n callback?: () => void\n ) {\n // Only available for Node.js runtime\n if (this.runtimeType !== 'node') {\n throw new Error(\n `listen() is only available for Node.js runtime. Current runtime: ${this.runtimeType}. Use getHandler() for other runtimes.`\n );\n }\n\n // Handle overloaded parameters - supports:\n // listen(callback)\n // listen(port, callback)\n // listen(port, host, callback)\n let port: number;\n let host: string | undefined;\n\n if (typeof portOrCallback === 'function') {\n // listen(callback) - use port from config\n callback = portOrCallback;\n port = this.config.server.port;\n host = this.config.server.host;\n } else if (typeof portOrCallback === 'number') {\n // listen(port, ...) variants\n port = portOrCallback;\n if (typeof hostOrCallback === 'function') {\n // listen(port, callback)\n callback = hostOrCallback;\n host = undefined;\n } else {\n // listen(port, host, callback)\n host = hostOrCallback;\n }\n } else {\n // listen() - use config defaults\n port = this.config.server.port;\n host = this.config.server.host;\n }\n\n // Validate that we have a valid port\n if (!port || typeof port !== 'number') {\n throw new Error(\n 'Port not specified and not found in configuration. Please provide a port number or configure it in moro.config.js/ts'\n );\n }\n\n // Check if clustering is enabled for massive performance gains\n if (this.config.performance?.clustering?.enabled) {\n // Worker threads (engine backend, POSIX, engine >= 1.1.6) or node:cluster\n // processes - startWithClustering picks and logs the transport.\n this.startWithClustering(port, host as string, callback);\n return;\n }\n\n // Single-process graceful shutdown: SIGINT/SIGTERM (Ctrl-C) drain in-flight\n // work via close() by default; a second signal force-exits. Opt out with\n // `server.gracefulShutdown: false`. (Cluster mode wires its own handlers.)\n this.registerProcessShutdownHandlers();\n\n void this.eventBus.emit('server:starting', { port, runtime: this.runtimeType });\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n this.coreFramework.addMiddleware(docsMiddleware);\n this.logger.debug('Documentation middleware added', 'Documentation');\n } catch {\n // Documentation not enabled, that's fine\n this.logger.debug('Documentation not enabled', 'Documentation');\n }\n\n // Attach the unified router (handles both chainable and direct routes)\n this.attachUnifiedRouter();\n\n // Register legacy direct routes with the HTTP server (for backward compatibility)\n if (this.routes.length > 0) {\n this.registerDirectRoutes();\n }\n\n const startServer = () => {\n const actualCallback = () => {\n const displayHost = host || 'localhost';\n const serverKind = this.engine;\n this.logger.info('Moro Server Started', 'Server');\n this.logger.info(`Runtime: ${this.runtimeType}`, 'Server');\n this.logger.info(\n `HTTP engine: ${serverKind.server}` +\n (serverKind.enginePackage ? ` (${serverKind.enginePackage})` : ''),\n 'Server'\n );\n this.logger.info(`HTTP API: http://${displayHost}:${port}`, 'Server');\n if (this.config.websocket.enabled) {\n this.logger.info(`WebSocket: ws://${displayHost}:${port}`, 'Server');\n }\n this.logger.info('Learn more at https://morojs.com', 'Server');\n\n // Log unified router stats\n const routeCount = this.unifiedRouter.getRouteCount();\n if (routeCount > 0) {\n this.logger.info(`Unified Router: ${routeCount} routes registered`, 'Server');\n // Log performance stats\n this.unifiedRouter.logPerformanceStats();\n }\n\n void this.eventBus.emit('server:started', {\n port,\n runtime: this.runtimeType,\n engine: serverKind,\n });\n\n // Start job scheduler after server starts\n this.startJobScheduler().catch(err => {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n });\n\n // Initialize GraphQL if configured\n this.ensureGraphQLInitialized().catch(error => {\n this.logger.error(`Failed to initialize GraphQL: ${error}`, 'GraphQL');\n });\n\n // Start gRPC server if initialized\n if (this.grpcManager && !this.grpcStarted) {\n this.startGrpc().catch(error => {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n });\n }\n\n if (callback) callback();\n };\n\n if (host && typeof host === 'string') {\n this.coreFramework.listen(port, host, actualCallback);\n } else {\n this.coreFramework.listen(port, actualCallback);\n }\n };\n\n // Ensure auto-discovery and WebSocket setup is complete before starting server.\n // Routes load after modules so DB/services/middleware set up during discovery\n // are available to route files.\n Promise.all([\n this.ensureAutoDiscoveryComplete().then(() => this.ensureRoutesLoaded()),\n this.processQueuedWebSocketRegistrations(),\n ])\n .then(\n () => startServer(),\n initError => {\n // Initialization (auto-discovery / WebSocket setup) failed — this is\n // NOT the listen() call. Handle it here so a subsequent listen()\n // failure can't be misdiagnosed as an init failure and retried.\n this.logger.error('Initialization failed during server start', 'Framework', {\n error: initError instanceof Error ? initError.message : String(initError),\n });\n // WebSocket-adapter misconfiguration is fatal; propagate it.\n if (\n initError instanceof Error &&\n initError.message.includes('WebSocket features require a WebSocket adapter')\n ) {\n throw initError;\n }\n // A non-fatal init issue (e.g. auto-discovery) — start the server anyway.\n startServer();\n }\n )\n .catch(error => {\n // startServer()/listen() failed — e.g. EADDRINUSE thrown synchronously\n // by the native engine. Retrying would fail identically, so surface it\n // via the 'error' event (Node's server convention) instead of retrying\n // into an unhandled rejection. With no 'error' listener, EventEmitter\n // rethrows — the desired visible crash for a fatal bind failure.\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(`Failed to start server on port ${port}: ${message}`, 'Framework');\n this.emit('error', error);\n });\n }\n\n // Public method to manually initialize auto-discovery\n // Useful for ensuring auth middleware is registered before auto-discovery\n async initializeAutoDiscoveryNow(): Promise<void> {\n return this.ensureAutoDiscoveryComplete();\n }\n\n // Load file-based routes from the configured directories (config.routing).\n // Runs once during listen() after module discovery. Idempotent and safe to\n // call alongside a manual app.loadRoutes() — the ES module cache prevents a\n // file from registering twice even if both resolve to the same path.\n private async ensureRoutesLoaded(): Promise<void> {\n if (this.routesLoaded) return;\n if (this.routesLoadedPromise) return this.routesLoadedPromise;\n\n const routing = this.config.routing;\n const disabled =\n routing === false || (typeof routing === 'object' && routing.enabled === false);\n if (disabled) {\n this.routesLoaded = true;\n return;\n }\n\n this.routesLoadedPromise = (async () => {\n const isProd = process.env.NODE_ENV === 'production';\n const defaultPaths = isProd ? ['./dist/routes', './dist/src/routes'] : ['./src/routes'];\n const paths =\n typeof routing === 'object' && Array.isArray(routing.paths) && routing.paths.length > 0\n ? routing.paths\n : defaultPaths;\n\n for (const dir of paths) {\n try {\n await this.loadRoutes(dir);\n } catch (error) {\n this.logger.warn(`Failed to auto-load routes from ${dir}`, 'RouteLoader', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n })();\n\n try {\n await this.routesLoadedPromise;\n this.routesLoaded = true;\n } finally {\n this.routesLoadedPromise = null;\n }\n }\n\n // Public API: Initialize modules explicitly after middleware setup\n // This provides users with explicit control over module loading timing\n // IMPORTANT: This forces module loading even if autoDiscovery.enabled is false\n // Usage: app.initModules() or app.initModules({ paths: ['./my-modules'] })\n initModules(options?: {\n paths?: string[];\n patterns?: string[];\n recursive?: boolean;\n loadingStrategy?: 'eager' | 'lazy' | 'conditional';\n watchForChanges?: boolean;\n ignorePatterns?: string[];\n loadOrder?: 'alphabetical' | 'dependency' | 'custom';\n failOnError?: boolean;\n maxDepth?: number;\n }): void {\n this.logger.info('User-requested module initialization', 'ModuleSystem');\n\n // If already initialized, do nothing\n if (this.autoDiscoveryInitialized) {\n this.logger.debug('Auto-discovery already completed, skipping', 'ModuleSystem');\n return;\n }\n\n // Store the options and mark that we want to force initialization\n this.autoDiscoveryOptions = {\n autoDiscover: {\n enabled: true, // Force enabled regardless of original config\n paths: options?.paths || ['./modules', './src/modules'],\n patterns: options?.patterns || [\n '**/*.module.{ts,js}',\n '**/index.{ts,js}',\n '**/*.config.{ts,js}',\n ],\n recursive: options?.recursive ?? true,\n loadingStrategy: options?.loadingStrategy || ('eager' as const),\n watchForChanges: options?.watchForChanges ?? false,\n ignorePatterns: options?.ignorePatterns || [\n '**/*.test.{ts,js}',\n '**/*.spec.{ts,js}',\n '**/node_modules/**',\n ],\n loadOrder: options?.loadOrder || ('dependency' as const),\n failOnError: options?.failOnError ?? false,\n maxDepth: options?.maxDepth ?? 5,\n },\n };\n\n this.logger.debug(\n 'Module initialization options stored, will execute on next listen/getHandler call',\n 'ModuleSystem'\n );\n }\n\n // Robust method to ensure auto-discovery is complete, handling race conditions\n private async ensureAutoDiscoveryComplete(): Promise<void> {\n // If already initialized, nothing to do\n if (this.autoDiscoveryInitialized) {\n return;\n }\n\n // If auto-discovery is disabled, mark as initialized\n if (!this.autoDiscoveryOptions) {\n this.autoDiscoveryInitialized = true;\n return;\n }\n\n // If already in progress, wait for it to complete\n if (this.autoDiscoveryPromise) {\n return this.autoDiscoveryPromise;\n }\n\n // Start auto-discovery\n this.autoDiscoveryPromise = this.performAutoDiscovery();\n\n try {\n await this.autoDiscoveryPromise;\n this.autoDiscoveryInitialized = true;\n } catch (error) {\n // Reset promise on error so it can be retried\n this.autoDiscoveryPromise = null;\n throw error;\n } finally {\n this.autoDiscoveryOptions = null; // Clear after attempt\n }\n }\n\n // Perform the actual auto-discovery work\n private async performAutoDiscovery(optionsOverride?: MoroOptions): Promise<void> {\n const optionsToUse = optionsOverride || this.autoDiscoveryOptions;\n if (!optionsToUse) return;\n\n this.logger.debug('Starting auto-discovery initialization', 'AutoDiscovery');\n\n await this.initializeAutoDiscovery(optionsToUse);\n\n this.logger.debug('Auto-discovery initialization completed', 'AutoDiscovery');\n }\n\n // Get handler for non-Node.js runtimes\n getHandler() {\n // Ensure auto-discovery is complete for non-Node.js runtimes\n // This handles the case where users call getHandler() immediately after createApp()\n this.ensureAutoDiscoveryComplete().catch(error => {\n this.logger.error('Auto-discovery initialization failed for runtime handler', 'Framework', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n\n // Create a unified request handler that works with the runtime adapter.\n // Lifecycle hooks run here so serverless runtimes (Lambda, Edge, Workers)\n // have parity with the long-running servers. Unlike those servers,\n // 'response' hooks are awaited before returning — post-return work would\n // be frozen or dropped by the platform.\n const hookManager = this.middlewareManager.getHookManager();\n const handler = async (req: HttpRequest, res: HttpResponse) => {\n try {\n if (hookManager.hasHooks('request')) {\n await hookManager.execute('request', { request: req, response: res });\n if (res.headersSent) return;\n }\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n await docsMiddleware(req, res, () => {});\n if (res.headersSent) return;\n } catch {\n // Documentation not enabled, that's fine\n }\n\n // Try unified router first (handles all routes)\n const handled = await this.unifiedRouter.handleRequest(req, res);\n if (handled) return;\n\n // Handle legacy direct routes (backward compatibility)\n if (this.routes.length > 0) {\n await this.handleDirectRoutes(req, res);\n }\n } catch (error) {\n if (hookManager.hasHooks('error')) {\n try {\n await hookManager.execute('error', { request: req, response: res, error });\n } catch (hookError: any) {\n this.logger.error(`Error hook error: ${hookError?.message || hookError}`, 'Hooks');\n }\n }\n throw error;\n } finally {\n if (hookManager.hasHooks('response')) {\n try {\n await hookManager.execute('response', { request: req, response: res });\n } catch (hookError: any) {\n this.logger.error(`Response hook error: ${hookError?.message || hookError}`, 'Hooks');\n }\n }\n }\n };\n\n // Use the runtime adapter to create the appropriate handler\n return this.runtimeAdapter.createServer(handler);\n }\n\n // Handle direct routes for runtime adapters\n private async handleDirectRoutes(req: HttpRequest, res: HttpResponse) {\n // Find matching route\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const route = this.findMatchingRoute(req.method!, req.path);\n if (!route) {\n (res as any).status(404).json({ success: false, error: 'Not found' });\n return;\n }\n\n try {\n // Extract path parameters\n const matches = req.path.match(route.pattern);\n if (matches) {\n req.params = {};\n route.paramNames.forEach((name: string, index: number) => {\n req.params[name] = matches[index + 1] ?? '';\n });\n }\n\n // Get handler function\n const handler = this.routeHandlers[route.handler];\n if (!handler) {\n (res as any).status(500).json({ success: false, error: 'Handler not found' });\n return;\n }\n\n // Execute validation if present\n if (route.validation) {\n try {\n const validated = route.validation.parse(req.body);\n req.body = validated;\n } catch (error: any) {\n if (error.issues) {\n (res as any).status(400).json({\n success: false,\n error: 'Validation failed',\n details: error.issues.map((issue: any) => ({\n field: issue.path.length > 0 ? issue.path.join('.') : 'body',\n message: issue.message,\n code: issue.code,\n })),\n });\n return;\n }\n throw error;\n }\n }\n\n // Execute rate limiting if present\n if (route.rateLimit) {\n const clientId = req.ip || 'unknown';\n const key = `${route.method}:${route.path}:${clientId}`;\n\n if (!this.checkRateLimit(key, route.rateLimit)) {\n (res as any).status(429).json({\n success: false,\n error: 'Rate limit exceeded',\n retryAfter: Math.ceil(route.rateLimit.window / 1000),\n });\n return;\n }\n }\n\n // Execute the handler\n const result = await handler(req, res);\n if (result && !(res as any).headersSent) {\n (res as any).json(result);\n }\n } catch (error) {\n if (!(res as any).headersSent) {\n (res as any).status(500).json({\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n });\n }\n }\n }\n\n // Advanced route matching with caching and optimization\n private routeCache = new Map<string, { pattern: RegExp; paramNames: string[] }>();\n private staticRouteMap = new Map<string, any>();\n private dynamicRoutesBySegments = new Map<number, any[]>();\n\n private findMatchingRoute(method: string, path: string) {\n // O(1) static route lookup\n const staticKey = `${method}:${path}`;\n const staticRoute = this.staticRouteMap.get(staticKey);\n if (staticRoute) {\n return {\n ...staticRoute,\n pattern: /^.*$/, // Dummy pattern for static routes\n paramNames: [],\n };\n }\n\n // Dynamic route matching by segment count\n const segmentCount = PathMatcher.countSegments(path);\n const candidateRoutes = this.dynamicRoutesBySegments.get(segmentCount) || [];\n\n for (const route of candidateRoutes) {\n if (route.method === method) {\n const cacheKey = `${method}:${route.path}`;\n let pattern = this.routeCache.get(cacheKey);\n\n if (!pattern) {\n pattern = this.pathToRegex(route.path);\n this.routeCache.set(cacheKey, pattern);\n }\n\n if (pattern.pattern.test(path)) {\n return {\n ...route,\n pattern: pattern.pattern,\n paramNames: pattern.paramNames,\n };\n }\n }\n }\n\n return null;\n }\n\n // Convert path to regex (simplified version)\n private pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const regexPath = path.replace(/\\//g, '\\\\/').replace(/:([^/]+)/g, (match, paramName) => {\n paramNames.push(paramName);\n return '([^/]+)';\n });\n\n return {\n pattern: new RegExp(`^${regexPath}$`),\n paramNames,\n };\n }\n\n // Access enterprise event system for advanced integrations\n get events() {\n return this.eventBus;\n }\n\n // The application's live hook manager — the same instance\n // MiddlewareInterface.install() receives. Register request-lifecycle hooks\n // directly: app.hooks.before('request', ctx => {...}),\n // app.hooks.after('response', ctx => {...}).\n get hooks() {\n return this.middlewareManager.getHookManager();\n }\n\n // Access to core framework for advanced usage\n get core() {\n return this.coreFramework;\n }\n\n // Which HTTP server actually booted (engine/node/http2), the package\n // backing a native engine, and the fallback reason when one was requested\n // but the Node server booted instead. Stable surface for logs/tests/benchmarks.\n get engine(): ReturnType<MoroCore['getServerKind']> {\n return this.coreFramework.getServerKind();\n }\n\n getServerKind(): ReturnType<MoroCore['getServerKind']> {\n return this.coreFramework.getServerKind();\n }\n\n // Public API for accessing the DI container\n getContainer() {\n return this.coreFramework.getContainer();\n }\n\n // Force cleanup of pooled objects\n forceCleanup(): void {\n const httpServer = (this.coreFramework as any).httpServer;\n if (httpServer && httpServer.forceCleanup) {\n httpServer.forceCleanup();\n }\n }\n\n // Private methods\n private addRoute(\n method: string,\n path: string,\n handler: ((req: any, res: any) => any | Promise<any>) | string | Buffer,\n options: any = {}\n ) {\n // A literal body - app.get('/', '') - is the same route the builder's\n // .handler('') registers: the unified router turns it into a handler and,\n // with nothing else configured, a reply the native engine answers itself.\n // It never enters the legacy direct-route table, whose wrapper would\n // call it as a function.\n if (typeof handler !== 'function') {\n this.unifiedRouter.registerRoute({\n method: method as any,\n path,\n handler: handler as any,\n validation: options.validation,\n rateLimit: options.rateLimit,\n cache: options.cache,\n middleware: options.middleware,\n });\n return this;\n }\n\n // Register with unified router (primary routing system)\n this.unifiedRouter.addRoute(method as any, path, handler as any, options.middleware || []);\n\n // Also store in legacy routes array for backward compatibility\n const handlerName = `handler_${this.routes.length}`;\n const route = {\n method: method as any,\n path,\n handler: handlerName,\n validation: options.validation,\n rateLimit: options.rateLimit,\n cache: options.cache,\n middleware: options.middleware,\n };\n\n this.routes.push(route);\n\n // Organize routes for optimal lookup (legacy)\n this.organizeRouteForLookup(route);\n\n // Store handler for later module creation (legacy)\n this.routeHandlers[handlerName] = handler;\n\n return this;\n }\n\n private organizeRouteForLookup(route: any): void {\n if (!route.path.includes(':')) {\n // Static route - add to static map for O(1) lookup\n const staticKey = `${route.method}:${route.path}`;\n this.staticRouteMap.set(staticKey, route);\n } else {\n // Dynamic route - organize by segment count\n const segmentCount = PathMatcher.countSegments(route.path);\n\n if (!this.dynamicRoutesBySegments.has(segmentCount)) {\n this.dynamicRoutesBySegments.set(segmentCount, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.dynamicRoutesBySegments.get(segmentCount)!.push(route);\n }\n }\n\n // Attach the unified router to the HTTP server. Servers that support direct\n // dispatch (setRouterHandler) get the router called straight from\n // handleRequest - after global middleware, with no per-request promise\n // wrapper. Older/custom servers fall back to the middleware adapter.\n private attachUnifiedRouter(): void {\n const httpServer = (this.coreFramework as any).httpServer;\n\n if (httpServer && typeof httpServer.setRouterHandler === 'function') {\n const router = this.unifiedRouter;\n httpServer.setRouterHandler((req: HttpRequest, res: HttpResponse) =>\n router.handleRequest(req, res)\n );\n\n // A server that answers fixed replies itself (MoroEngineServer on an\n // engine with capabilities.staticRoutes) gets every route whose handler\n // is a literal body, so those requests never enter JS. The route's\n // handler stays registered: it answers HEAD, and everything on servers\n // without the capability.\n if (typeof httpServer.setStaticRoute === 'function') {\n for (const schema of router.getAllRoutes()) {\n const fixed = schema.static;\n if (fixed) {\n httpServer.setStaticRoute(\n schema.method,\n schema.path,\n fixed.status,\n fixed.headers,\n fixed.body\n );\n }\n }\n }\n\n // Servers with a native router (uWS) additionally get fast-path routes\n // registered directly on it - evaluated at listen so late-loaded routes\n // are included; error handling shares the unified router's semantics\n if (typeof httpServer.setNativeRouteProvider === 'function') {\n httpServer.setNativeRouteProvider(\n () => router.getNativeFastPathRoutes(),\n (req: HttpRequest, res: HttpResponse, err: any) => router.handleRouteError(err, req, res)\n );\n }\n return;\n }\n\n this.coreFramework.addMiddleware(\n async (req: HttpRequest, res: HttpResponse, next: () => void) => {\n // Try unified router first (handles all route types)\n const handled = this.unifiedRouter.handleRequest(req, res);\n\n // Check if it's a promise (async route) or sync (fast-path)\n if (handled && typeof (handled as any).then === 'function') {\n // Async - await the result\n const isHandled = await (handled as Promise<boolean>);\n if (!isHandled) {\n next();\n }\n } else {\n // Sync - check immediately\n if (!(handled as boolean)) {\n next();\n }\n }\n }\n );\n }\n\n private registerDirectRoutes() {\n // Register routes directly with the HTTP server for optimal performance\n // This provides the intuitive developer experience users expect\n for (const route of this.routes) {\n const handler = this.routeHandlers[route.handler];\n if (!handler) continue;\n\n // Get direct access to the HTTP server through the core framework\n const httpServer = (this.coreFramework as any).httpServer;\n\n // Create a wrapper handler that handles validation, rate limiting, and return values\n const wrappedHandler = async (req: any, res: any) => {\n try {\n // Enhance request with events property for direct routes\n req.events = this.eventBus;\n\n // Universal validation middleware (works with any ValidationSchema)\n if (route.validation) {\n try {\n const validated = await route.validation.parseAsync(req.body);\n req.body = validated;\n } catch (error: any) {\n // Handle universal validation errors using the new error handler\n const normalizedError = normalizeValidationError(error);\n const errors = normalizedError.issues.map((issue: any) => ({\n field: issue.path.length > 0 ? issue.path.join('.') : 'body',\n message: issue.message,\n code: issue.code,\n path: issue.path,\n }));\n\n // Get global validation error handler\n let globalHandler;\n try {\n const { getGlobalConfig } = await import('./core/config/index.js');\n const config = getGlobalConfig();\n globalHandler = config.modules.validation.onError;\n } catch {\n globalHandler = undefined;\n }\n\n // Use route-level or global error handler\n const handler = route.onValidationError || globalHandler;\n if (handler) {\n try {\n const errorResponse = handler(errors, {\n request: {\n method: req.method || 'UNKNOWN',\n path: req.path || req.url || '',\n url: req.url || '',\n headers: req.headers || {},\n },\n field: 'body',\n });\n\n if (errorResponse.headers) {\n Object.entries(errorResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.status(errorResponse.status).json(errorResponse.body);\n return;\n } catch {\n // Fallback if handler throws\n res.status(500).json({\n success: false,\n error: 'Internal error while handling validation error',\n requestId: req.requestId,\n });\n return;\n }\n }\n\n // Default error response if no handler\n res.status(400).json({\n success: false,\n error: 'Validation failed',\n details: errors,\n requestId: req.requestId,\n });\n return;\n }\n }\n\n // Rate limiting middleware\n if (route.rateLimit) {\n const clientId = req.ip || req.connection?.remoteAddress || 'unknown';\n const key = `${route.method}:${route.path}:${clientId}`;\n\n if (!this.checkRateLimit(key, route.rateLimit)) {\n res.status(429).json({\n success: false,\n error: 'Rate limit exceeded',\n retryAfter: Math.ceil(route.rateLimit.window / 1000),\n });\n return;\n }\n }\n\n // Execute the actual handler\n const result = await handler(req, res);\n if (result && !res.headersSent) {\n res.json(result);\n }\n } catch (error) {\n // Route through user-registered error handler first, if any.\n if (this.errorHandler && !res.headersSent) {\n try {\n const handlerResult = this.errorHandler(error, req, res);\n if (handlerResult && typeof (handlerResult as any).then === 'function') {\n await handlerResult;\n }\n if (res.headersSent) return;\n } catch (handlerErr) {\n this.logger.error('Error handler itself threw', 'RequestHandler', {\n error: handlerErr instanceof Error ? handlerErr.message : String(handlerErr),\n });\n }\n }\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n });\n }\n }\n };\n\n // Register with the appropriate HTTP method\n const method = route.method.toLowerCase();\n if (httpServer && httpServer[method]) {\n httpServer[method](route.path, wrappedHandler);\n }\n }\n }\n\n // Simple rate limiting for direct routes\n private rateLimitStore = new Map<string, { count: number; resetTime: number }>();\n\n private checkRateLimit(key: string, config: { requests: number; window: number }): boolean {\n const now = Date.now();\n const bucket = this.rateLimitStore.get(key);\n\n if (!bucket || now > bucket.resetTime) {\n // Create new bucket or reset expired bucket\n this.rateLimitStore.set(key, {\n count: 1,\n resetTime: now + config.window,\n });\n return true;\n }\n\n if (bucket.count >= config.requests) {\n return false; // Rate limit exceeded\n }\n\n bucket.count++;\n return true;\n }\n\n private setupDefaultMiddleware(_options: MoroOptions) {\n // cors/helmet/compression/bodySize are installed once by MoroCore.setupCore()\n // (config-driven, with the configured bodySizeLimit). Registering them here\n // again made every request run each of them twice.\n }\n\n // Enhanced auto-discovery initialization\n private async initializeAutoDiscovery(options: MoroOptions): Promise<void> {\n const { ModuleDiscovery } = await import('./core/modules/auto-discovery.js');\n\n // Merge auto-discovery configuration\n const autoDiscoveryConfig = this.mergeAutoDiscoveryConfig(options);\n\n if (!autoDiscoveryConfig.enabled) {\n return;\n }\n\n this.moduleDiscovery = new ModuleDiscovery(process.cwd());\n\n try {\n // Discover modules based on configuration\n const modules = await this.moduleDiscovery.discoverModulesAdvanced(autoDiscoveryConfig);\n\n // Load modules based on strategy\n await this.loadDiscoveredModules(modules, autoDiscoveryConfig);\n\n // Setup final module handler to run after user middleware (like auth)\n this.coreFramework.setupFinalModuleHandler();\n\n // Setup file watching if enabled\n if (autoDiscoveryConfig.watchForChanges) {\n this.moduleDiscovery.watchModulesAdvanced(\n autoDiscoveryConfig,\n async (updatedModules: ModuleConfig[]) => {\n await this.handleModuleChanges(updatedModules);\n }\n );\n }\n\n this.logger.info(\n `Auto-discovery completed: ${modules.length} modules loaded`,\n 'ModuleDiscovery'\n );\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n if (autoDiscoveryConfig.failOnError) {\n throw new Error(`Module auto-discovery failed: ${errorMsg}`);\n } else {\n this.logger.warn(`Module auto-discovery failed: ${errorMsg}`, 'ModuleDiscovery');\n }\n }\n }\n\n // Merge auto-discovery configuration from multiple sources\n private mergeAutoDiscoveryConfig(options: MoroOptions) {\n const defaultConfig = this.config.modules.autoDiscovery;\n\n // Handle legacy modulesPath option\n if (options.modulesPath && !options.autoDiscover) {\n return {\n ...defaultConfig,\n paths: [options.modulesPath],\n };\n }\n\n // Handle boolean autoDiscover option\n if (typeof options.autoDiscover === 'boolean') {\n return {\n ...defaultConfig,\n enabled: options.autoDiscover,\n };\n }\n\n // Handle object autoDiscover option\n if (typeof options.autoDiscover === 'object') {\n return {\n ...defaultConfig,\n ...options.autoDiscover,\n };\n }\n\n return defaultConfig;\n }\n\n // Load discovered modules based on strategy\n private async loadDiscoveredModules(\n modules: ModuleConfig[],\n config: ModuleDefaultsConfig['autoDiscovery']\n ): Promise<void> {\n switch (config.loadingStrategy) {\n case 'eager':\n // Load all modules immediately\n for (const module of modules) {\n await this.loadModule(module);\n }\n break;\n\n case 'lazy':\n // Register modules for lazy loading\n this.registerLazyModules(modules);\n break;\n\n case 'conditional':\n // Load modules based on conditions\n await this.loadConditionalModules(modules);\n break;\n\n default:\n // Default to eager loading\n for (const module of modules) {\n await this.loadModule(module);\n }\n }\n }\n\n // Register modules for lazy loading\n private registerLazyModules(modules: ModuleConfig[]): void {\n modules.forEach(module => {\n // Store module for lazy loading when first route is accessed\n this.lazyModules.set(module.name, module);\n\n // Register placeholder routes that trigger lazy loading\n if (module.routes) {\n module.routes.forEach(route => {\n const basePath = buildModuleBasePath(\n this.config.modules?.apiPrefix,\n module.version,\n module.name\n );\n // Handle root path within module: '/' should map to basePath, not basePath + '/'\n const routePath = route.path === '/' ? '' : route.path;\n const fullPath = `${basePath}${routePath}`;\n\n // Note: Lazy loading will be implemented when route is accessed\n // For now, we'll store the module for later loading\n this.logger.debug(\n `Registered lazy route: ${route.method} ${fullPath}`,\n 'ModuleDiscovery'\n );\n });\n }\n });\n\n this.logger.info(`Registered ${modules.length} modules for lazy loading`, 'ModuleDiscovery');\n }\n\n // Load modules conditionally based on environment or configuration\n private async loadConditionalModules(modules: ModuleConfig[]): Promise<void> {\n for (const module of modules) {\n const shouldLoad = this.shouldLoadModule(module);\n\n if (shouldLoad) {\n await this.loadModule(module);\n } else {\n this.logger.debug(`Skipping module ${module.name} due to conditions`, 'ModuleDiscovery');\n }\n }\n }\n\n // Determine if a module should be loaded based on conditions\n private shouldLoadModule(module: ModuleConfig): boolean {\n const moduleConfig = module.config as any;\n\n // Check environment conditions\n if (moduleConfig?.conditions?.environment) {\n const requiredEnv = moduleConfig.conditions.environment;\n const currentEnv = process.env.NODE_ENV || 'development';\n\n if (Array.isArray(requiredEnv)) {\n if (!requiredEnv.includes(currentEnv)) {\n return false;\n }\n } else if (requiredEnv !== currentEnv) {\n return false;\n }\n }\n\n // Check feature flags\n if (moduleConfig?.conditions?.features) {\n const requiredFeatures = moduleConfig.conditions.features;\n\n for (const feature of requiredFeatures) {\n if (!process.env[`FEATURE_${feature.toUpperCase()}`]) {\n return false;\n }\n }\n }\n\n // Check custom conditions\n if (moduleConfig?.conditions?.custom) {\n const customCondition = moduleConfig.conditions.custom;\n\n if (typeof customCondition === 'function') {\n return customCondition();\n }\n }\n\n return true;\n }\n\n // Handle module changes during development\n private async handleModuleChanges(modules: ModuleConfig[]): Promise<void> {\n this.logger.info('Module changes detected, reloading...', 'ModuleDiscovery');\n\n // Unload existing modules (if supported)\n // For now, just log the change\n void this.eventBus.emit('modules:changed', {\n modules: modules.map(m => ({ name: m.name, version: m.version })),\n timestamp: new Date(),\n });\n }\n\n // Legacy method for backward compatibility\n private autoDiscoverModules(modulesPath: string) {\n // Redirect to new system (legacy sync shim over the async discovery path).\n void this.initializeAutoDiscovery({\n autoDiscover: {\n enabled: true,\n paths: [modulesPath],\n },\n }).catch(err => this.logger.error(`Auto-discovery failed: ${String(err)}`, 'ModuleDiscovery'));\n }\n\n private async importModule(modulePath: string): Promise<ModuleConfig> {\n // Convert file path to proper file URL for Windows compatibility\n const importURL = filePathToImportURL(modulePath);\n const module = await import(importURL);\n return module.default || module;\n }\n\n /**\n * Node.js Clustering Implementation\n * This clustering algorithm is based on published research and Node.js best practices.\n *\n * IPC (Inter-Process Communication) Considerations:\n * - Excessive workers create IPC bottlenecks (Source: BetterStack Node.js Guide)\n * - Round-robin scheduling provides better load distribution (Node.js Documentation)\n * - Message passing overhead increases significantly with worker count\n *\n * Memory Management:\n * - ~2GB per worker prevents memory pressure and GC overhead\n * - Conservative heap limits reduce memory fragmentation\n *\n * References:\n * - Node.js Cluster Documentation: https://nodejs.org/api/cluster.html\n * - BetterStack Node.js Clustering: https://betterstack.com/community/guides/scaling-nodejs/node-clustering/\n */\n private clusterWorkers = new Map<number, any>();\n\n private threadCluster: ThreadClusterPrimary | undefined = undefined;\n\n // Entry point for performance.clustering: decides whether THIS instance is\n // a worker (thread or process) or the primary, and which transport the\n // primary uses. Config keys are unchanged; the transport is automatic.\n private startWithClustering(port: number, host?: string, callback?: () => void): void {\n const { count: workerCount, detail } = computeWorkerCount(this.config.performance?.clustering);\n const tinfo = threadWorkerInfo();\n if (tinfo) {\n this.startClusterWorker({ kind: 'thread', info: tinfo }, port, host);\n return;\n }\n if (nodeCluster().isWorker) {\n this.startClusterWorker({ kind: 'process' }, port, host);\n return;\n }\n this.logger.info(detail, 'Cluster');\n const engineKind = this.engine;\n const transport = resolveClusterTransport({\n platform: process.platform,\n isMainThread: wt().isMainThread,\n argv1: process.argv[1],\n engineServer: engineKind.server,\n enginePackage: engineKind.enginePackage,\n workerThreadsCapable: loadNativeEngine()?.capabilities?.workerThreads === true,\n });\n if (transport.kind === 'threads') {\n this.startThreadPrimary(transport.entry, workerCount, port, host, callback);\n return;\n }\n this.logger.info(\n `Clustering: ${workerCount} worker processes (node:cluster; ${transport.reason})`,\n 'Cluster'\n );\n this.startProcessPrimary(workerCount, port, host, callback);\n }\n\n // Services that must run exactly ONCE per cluster, in the primary: the job\n // scheduler (leader election already treats the main thread of a\n // non-cluster-worker process as a participant) and the gRPC server (its own\n // port). GraphQL registers HTTP/WS routes, so it initialises in every\n // worker instead. Before 1.9.0 none of these started under clustering.\n private startPrimaryServices(): void {\n this.startJobScheduler().catch(err => {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n });\n if (this.grpcManager && !this.grpcStarted) {\n this.startGrpc().catch(error => {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n });\n }\n }\n\n private startThreadPrimary(\n entry: string,\n workerCount: number,\n port: number,\n host: string | undefined,\n callback?: () => void\n ): void {\n // The libuv threadpool is process-wide and sized once at first use;\n // the process path set this per worker process. Only if the operator\n // did not choose a size.\n if (!process.env.UV_THREADPOOL_SIZE) process.env.UV_THREADPOOL_SIZE = '64';\n // Same young-generation bound the process path applies through execArgv\n // (see YOUNG_GEN_MB_FOR_SEMI_SPACE_4), unless the operator tuned GC.\n const resourceLimits = isUserTunedYoungGen()\n ? undefined\n : { maxYoungGenerationSizeMb: YOUNG_GEN_MB_FOR_SEMI_SPACE_4 };\n\n const engineKind = this.engine;\n this.logger.info(\n `Clustering: ${workerCount} worker threads (worker_threads + SO_REUSEPORT, ` +\n `${engineKind.enginePackage}${engineKind.engineVersion ? ` v${engineKind.engineVersion}` : ''})`,\n 'Cluster'\n );\n\n let fellBack = false;\n const fallBackToProcesses = (why: string) => {\n if (fellBack) return;\n fellBack = true;\n this.logger.warn(\n `Worker threads unavailable (${why}); falling back to worker processes`,\n 'Cluster'\n );\n const primary = this.threadCluster;\n this.threadCluster = undefined;\n void primary?.shutdown(1000).finally(() => {\n this.startProcessPrimary(workerCount, port, host, callback);\n });\n };\n\n const primary = new ThreadClusterPrimary({\n entry,\n argv: process.argv.slice(2),\n workerCount,\n logger: this.logger,\n ...(resourceLimits ? { resourceLimits } : {}),\n onReady: () => {\n this.startPrimaryServices();\n if (callback) callback();\n },\n onFatal: (error, kind) => {\n if (kind === 'bind') {\n // Processes would fail identically: surface it like the single-process\n // path does (Node's server convention; rethrows without a listener).\n this.emit('error', error);\n return;\n }\n fallBackToProcesses(error.message);\n },\n });\n this.threadCluster = primary;\n try {\n primary.start();\n } catch (error) {\n fallBackToProcesses(error instanceof Error ? error.message : String(error));\n return;\n }\n\n // Graceful shutdown: drain every worker thread (each closes its server),\n // then the primary's own services; a second signal exits at once.\n let shuttingDown = false;\n const gracefulShutdown = (code: number) => {\n if (shuttingDown) {\n process.exit(code);\n return;\n }\n shuttingDown = true;\n this.logger.info('Gracefully shutting down cluster...', 'Cluster');\n this.close()\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n };\n process.on('SIGINT', () => gracefulShutdown(0));\n process.on('SIGTERM', () => gracefulShutdown(0));\n }\n\n private startProcessPrimary(\n workerCount: number,\n port: number,\n host: string | undefined,\n callback?: () => void\n ): void {\n void port;\n void host;\n this.logger.info(`Starting ${workerCount} workers`, 'Cluster');\n\n // Optimize cluster scheduling for high concurrency\n // Round-robin is the default on all platforms except Windows (Node.js docs)\n // Provides better load distribution than shared socket approach\n nodeCluster().schedulingPolicy = nodeCluster().SCHED_RR;\n\n // Workers inherit the primary's execArgv; additionally bound each\n // worker's V8 young generation unless the user tuned it themselves.\n // On big machines V8 sizes the nursery from total RAM and grows it\n // under sustained load (~10-34 MB extra RSS per process, measured on a\n // 64 GB box) - and in cluster mode that cost multiplies by the worker\n // count. A/B-benched 2026-08-01: identical throughput at 4 MB semi-space\n // in both the realistic profile (~92k vs ~90k req/s) and the pipelined\n // x10 microbenchmark (~560k both ways), while sustained-load RSS drops\n // ~30 MB per worker (115 -> 81 MB on the 25-route POST soak).\n const userTunedGC = isUserTunedYoungGen();\n\n // Set cluster settings for better performance\n nodeCluster().setupMaster({\n exec: process.argv[1] || process.execPath,\n args: process.argv.slice(2),\n silent: false,\n ...(userTunedGC ? {} : { execArgv: [...process.execArgv, '--max-semi-space-size=4'] }),\n });\n\n // IPC Optimization: Reduce communication overhead between master and workers\n // Research shows excessive IPC can create bottlenecks in clustered applications\n // (Source: BetterStack - Node.js Clustering Guide)\n process.env.NODE_CLUSTER_SCHED_POLICY = 'rr'; // Ensure round-robin\n process.env.NODE_DISABLE_COLORS = '1'; // Reduce IPC message size by disabling color codes\n\n // Graceful shutdown: SIGTERM every worker (each stops accepting, drains\n // its in-flight responses, then exits), wait for their exits up to a\n // bounded deadline, and only then exit. Exiting right after the kill\n // used to close the cluster IPC channel, and a node:cluster worker whose\n // primary disappears exits immediately - cutting the very responses the\n // worker was draining. A second signal while draining exits at once.\n let shuttingDown = false;\n const gracefulShutdown = () => {\n if (shuttingDown) process.exit(0);\n shuttingDown = true;\n this.logger.info('Gracefully shutting down cluster...', 'Cluster');\n\n if (this.clusterWorkers.size === 0) {\n nodeCluster().removeAllListeners();\n process.exit(0);\n }\n const pending = new Set<number>(this.clusterWorkers.keys());\n const timer = setTimeout(() => {\n this.logger.warn(\n `Shutdown deadline reached; terminating ${pending.size} worker process(es)`,\n 'Cluster'\n );\n for (const pid of pending) this.clusterWorkers.get(pid)?.kill('SIGKILL');\n finish();\n }, 3000);\n const finish = () => {\n clearTimeout(timer);\n nodeCluster().removeAllListeners();\n process.exit(0);\n };\n for (const [pid, worker] of this.clusterWorkers) {\n worker.removeAllListeners(); // no restart on these exits\n worker.once('exit', () => {\n pending.delete(pid);\n if (pending.size === 0) finish();\n });\n worker.kill('SIGTERM');\n }\n };\n\n // Handle process signals for graceful shutdown\n process.on('SIGINT', gracefulShutdown);\n process.on('SIGTERM', gracefulShutdown);\n\n // Fork workers with basic tracking\n for (let i = 0; i < workerCount; i++) {\n const worker = nodeCluster().fork();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.clusterWorkers.set(worker.process.pid!, worker);\n this.logger.info(`Worker ${worker.process.pid} started`, 'Cluster');\n\n // Handle individual worker messages\n worker.on('message', this.handleWorkerMessage.bind(this));\n }\n\n // Primary-only services start once the first worker is serving.\n let servicesStarted = false;\n nodeCluster().on('listening', () => {\n if (servicesStarted) return;\n servicesStarted = true;\n this.startPrimaryServices();\n });\n\n // Simple worker exit handling\n nodeCluster().on('exit', (worker: any, code: number, signal: string) => {\n const pid = worker.process.pid;\n this.clusterWorkers.delete(pid);\n\n if (code !== 0 && !worker.exitedAfterDisconnect) {\n this.logger.warn(\n `Worker ${pid} died unexpectedly (${signal || code}). Restarting...`,\n 'Cluster'\n );\n\n // Simple restart\n const newWorker = nodeCluster().fork();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.clusterWorkers.set(newWorker.process.pid!, newWorker);\n this.logger.info(`Worker ${newWorker.process.pid} restarted`, 'Cluster');\n }\n });\n\n // Master process callback\n if (callback) callback();\n }\n\n // One worker, either a worker_threads thread or a node:cluster process:\n // boot the app exactly like the single-process path (auto-discovery,\n // file-based routes, WebSocket registrations, GraphQL) and listen with\n // SO_REUSEPORT. Signals/exit are the differences: a thread gets 'shutdown'\n // from the primary over parentPort and never calls process.exit().\n private startClusterWorker(\n mode: { kind: 'thread'; info: ThreadWorkerInfo } | { kind: 'process' },\n port: number,\n host?: string\n ): void {\n const label =\n mode.kind === 'thread' ? `Worker thread ${wt().threadId}` : `Worker ${process.pid}`;\n const workerRef = mode.kind === 'thread' ? wt().threadId : process.pid;\n this.logger.info(`${label} initializing`, 'Worker');\n\n if (mode.kind === 'process') {\n // Worker-specific optimizations for high concurrency (a thread shares\n // the primary's pool, sized before it was spawned)\n process.env.UV_THREADPOOL_SIZE = '64';\n }\n\n // Reduce logging contention in workers (major bottleneck)\n // Multiple workers writing to same log files creates I/O contention\n // ONLY reduce log level if user didn't explicitly set one\n if (!this.userSetLogger) {\n // Workers log less frequently to reduce I/O contention (only if not explicitly configured)\n applyLoggingConfiguration(undefined, { level: 'warn' }); // Only warnings and errors\n }\n\n // Optimize garbage collection for workers\n // eslint-disable-next-line no-undef\n if ((global as any).gc) {\n setInterval(() => {\n // eslint-disable-next-line no-undef\n if ((global as any).gc) (global as any).gc();\n }, 60000); // GC every 60 seconds (less frequent)\n }\n\n let tcw: ThreadClusterWorker | null = null;\n if (mode.kind === 'thread') {\n tcw = new ThreadClusterWorker(this.logger);\n // 'shutdown' from the primary: drain and close; the thread then exits\n // on its own once the engine's handles are gone.\n tcw.onShutdown(async () => {\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n await this.close();\n });\n } else {\n // Graceful shutdown for worker\n const workerShutdown = () => {\n this.logger.info(`${label} shutting down gracefully...`, 'Worker');\n\n // Clean up event listeners\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n\n // Close server gracefully\n if (this.coreFramework) {\n const server = (this.coreFramework as any).server;\n if (server) {\n server.close(() => {\n process.exit(0);\n });\n }\n }\n };\n\n // Handle worker shutdown signals\n process.on('SIGTERM', workerShutdown);\n process.on('SIGINT', workerShutdown);\n }\n\n const fatal = (code: string, message: string) => {\n this.logger.error(`${label} ${message}`, 'Worker');\n if (tcw) {\n tcw.fatal(code, message);\n void this.close().finally(() => tcw?.close());\n } else {\n process.exit(1);\n }\n };\n\n // Continue with normal server startup for this worker\n void this.eventBus.emit('server:starting', {\n port,\n runtime: this.runtimeType,\n worker: workerRef,\n });\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n this.coreFramework.addMiddleware(docsMiddleware);\n } catch {\n // Documentation not enabled, that's fine\n }\n\n // Attach the unified router (handles both chainable and direct routes)\n this.attachUnifiedRouter();\n\n // Register legacy direct routes with the HTTP server (for backward compatibility)\n if (this.routes.length > 0) {\n this.registerDirectRoutes();\n }\n\n const workerCallback = () => {\n const displayHost = host || 'localhost';\n this.logger.info(`${label} ready on ${displayHost}:${port}`, 'Worker');\n void this.eventBus.emit('server:started', {\n port,\n runtime: this.runtimeType,\n worker: workerRef,\n engine: this.engine,\n });\n // GraphQL registers HTTP/WS routes on this app: every worker.\n this.ensureGraphQLInitialized().catch(error => {\n this.logger.error(`Failed to initialize GraphQL: ${error}`, 'GraphQL');\n });\n tcw?.ready(port);\n };\n\n const startWorkerListening = () => {\n if (host) {\n this.coreFramework.listen(port, host, workerCallback);\n } else {\n this.coreFramework.listen(port, workerCallback);\n }\n };\n // Same init as the single-process path: auto-discovery, file-based\n // routes, queued WebSocket registrations - before 1.9.0 workers skipped\n // discovery/route loading entirely.\n Promise.all([\n this.ensureAutoDiscoveryComplete().then(() => this.ensureRoutesLoaded()),\n this.processQueuedWebSocketRegistrations(),\n ])\n .then(startWorkerListening)\n .catch(error => {\n const message = error instanceof Error ? error.message : String(error);\n const code = (error as any)?.code;\n // listen() itself failed (EADDRINUSE etc.): retrying is guaranteed to\n // fail again and would surface as an unhandled rejection crash-loop.\n // Report fatally so the primary sees a clean death.\n if (\n code === 'EADDRINUSE' ||\n code === 'EACCES' ||\n /EADDRINUSE|failed to bind/i.test(message)\n ) {\n fatal(\n code === 'EACCES' ? 'EACCES' : 'EADDRINUSE',\n `could not bind port ${port}: ${message}`\n );\n return;\n }\n this.logger.error('Initialization failed in worker', 'Worker', { error: message });\n // For WebSocket failures with queued registrations, error will propagate\n if (\n error instanceof Error &&\n error.message.includes('WebSocket features require a WebSocket adapter')\n ) {\n throw error;\n }\n // Init failed but the HTTP server can still serve: start anyway, and\n // surface (not swallow) a listen failure from this path.\n try {\n startWorkerListening();\n } catch (listenError) {\n const lm = listenError instanceof Error ? listenError.message : String(listenError);\n fatal(\n (listenError as any)?.code === 'EACCES' ? 'EACCES' : 'EADDRINUSE',\n `failed to start: ${lm}`\n );\n }\n });\n }\n\n // Simple worker message handler\n private handleWorkerMessage(message: any): void {\n // Handle inter-worker communication if needed\n if (message.type === 'health-check') {\n // Worker health check response\n return;\n }\n\n // Log other worker messages\n this.logger.debug(`Worker message: ${JSON.stringify(message)}`, 'Cluster');\n }\n\n /**\n * Gracefully close the application and clean up resources\n * This should be called in tests and during shutdown\n */\n private shutdownHandlersRegistered = false;\n private isShuttingDown = false;\n // Per-instance opt-in uncaught-error listeners (removed by close()).\n private processListeners: Array<[string, (...args: any[]) => void]> = [];\n\n // Graceful shutdown is driven by ONE process-level SIGINT/SIGTERM handler\n // shared across every Moro instance (installed once), so creating many apps\n // never accumulates process listeners. Instances register here on listen()\n // and deregister on close().\n private static activeInstances = new Set<Moro>();\n private static globalSignalsInstalled = false;\n private static globalShuttingDown = false;\n\n private static installGlobalShutdownSignals(): void {\n if (Moro.globalSignalsInstalled) return;\n Moro.globalSignalsInstalled = true;\n\n const handle = (signal: string, code: number) => {\n // A second signal while already draining forces an immediate exit, so a\n // stuck shutdown can never make the process unkillable via Ctrl-C.\n if (Moro.globalShuttingDown) {\n process.exit(code);\n return;\n }\n Moro.globalShuttingDown = true;\n const instances = Array.from(Moro.activeInstances);\n instances[0]?.logger.info(`Received ${signal}, shutting down gracefully...`, 'Server');\n Promise.allSettled(instances.map(inst => inst.close()))\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n };\n\n process.on('SIGINT', () => handle('SIGINT', 0));\n process.on('SIGTERM', () => handle('SIGTERM', 0));\n }\n\n /**\n * Enable graceful shutdown for this instance. SIGINT/SIGTERM (Ctrl-C) drain\n * in-flight work via close() by default; a second signal force-exits. Opt out\n * with `server.gracefulShutdown: false` (e.g. when the host app owns signals).\n * Uncaught-error draining is separate and opt-in (`server.handleUncaught`).\n */\n private registerProcessShutdownHandlers(): void {\n if (this.shutdownHandlersRegistered) return;\n const serverCfg = this.config.server as any;\n if (serverCfg?.gracefulShutdown === false) return; // default ON; opt out here\n this.shutdownHandlersRegistered = true;\n\n Moro.activeInstances.add(this);\n Moro.installGlobalShutdownSignals();\n\n // Opt-in uncaught-error draining (per instance, removed on close()).\n if (serverCfg?.handleUncaught === true) {\n const add = (event: string, handler: (...args: any[]) => void) => {\n process.on(event as any, handler);\n this.processListeners.push([event, handler]);\n };\n add('unhandledRejection', reason => {\n this.logger.error(`Unhandled promise rejection: ${String(reason)}`, 'Server');\n this.drainAndExit(1);\n });\n add('uncaughtException', err => {\n this.logger.error(\n `Uncaught exception: ${err instanceof Error ? err.stack || err.message : String(err)}`,\n 'Server'\n );\n this.drainAndExit(1);\n });\n }\n }\n\n private drainAndExit(code: number): void {\n if (this.isShuttingDown) {\n process.exit(code);\n return;\n }\n this.isShuttingDown = true;\n this.close()\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n }\n\n /** Deregister this instance from process shutdown handling (called by close()). */\n private removeProcessShutdownHandlers(): void {\n Moro.activeInstances.delete(this);\n for (const [event, handler] of this.processListeners) {\n process.removeListener(event as any, handler);\n }\n this.processListeners = [];\n this.shutdownHandlersRegistered = false;\n }\n\n async close(): Promise<void> {\n this.logger.debug('Closing Moro application...');\n\n // Detach our process signal listeners so repeated create/close cycles\n // (tests, or a host that spins up many apps) don't leak process listeners.\n this.removeProcessShutdownHandlers();\n\n // Run user-registered onClose hooks first, while subsystems are still alive.\n // Failures in one hook don't prevent subsequent hooks or Moro's own teardown.\n if (this.closeHooks.length > 0) {\n for (const hook of this.closeHooks) {\n try {\n await hook();\n } catch (err) {\n this.logger.error(`onClose hook failed: ${String(err)}`);\n }\n }\n }\n\n // Cluster worker threads first: each drains its server via its own\n // close(); the primary's services below stop after the traffic did.\n if (this.threadCluster) {\n const primary = this.threadCluster;\n this.threadCluster = undefined;\n try {\n await primary.shutdown();\n } catch (err) {\n this.logger.error(`Error shutting down cluster worker threads: ${String(err)}`);\n }\n }\n\n // Shutdown worker threads first (fastest)\n try {\n this.logger.info('Shutting down worker threads...');\n await this.workerFacade.shutdown();\n } catch {\n // Workers might not be initialized or available\n this.logger.debug('Worker threads not available for shutdown');\n }\n\n // Shutdown job scheduler\n if (this.jobScheduler) {\n try {\n this.logger.info('Shutting down job scheduler...');\n await this.jobScheduler.shutdown();\n this.jobsStarted = false;\n } catch (err) {\n this.logger.error(`Error shutting down job scheduler: ${String(err)}`);\n }\n }\n\n // Shutdown gRPC server\n if (this.grpcManager && this.grpcStarted) {\n try {\n this.logger.info('Shutting down gRPC server...');\n await this.stopGrpc();\n } catch (err) {\n this.logger.error(`Error shutting down gRPC server: ${String(err)}`);\n }\n }\n\n // Cleanup GraphQL adapter resources\n if (this.graphqlCore) {\n try {\n await this.graphqlCore.cleanup();\n } catch (err) {\n this.logger.error(`Error cleaning up GraphQL: ${String(err)}`);\n }\n }\n\n // Flush logger buffer before shutdown\n try {\n // Use flushBuffer for immediate synchronous flush\n this.logger.flushBuffer();\n } catch {\n // Ignore flush errors during shutdown\n }\n\n // Close the core framework with timeout\n if (this.coreFramework && (this.coreFramework as any).httpServer) {\n try {\n const httpServer = (this.coreFramework as any).httpServer;\n const server = httpServer.getServer?.() || httpServer.getApp?.();\n\n // Only wait for close if the server is actually listening\n const isListening = server?.listening || server?.address?.() !== null;\n\n if (isListening) {\n // Stop accepting new connections and let in-flight requests finish,\n // but don't hang on idle keep-alive / WebSocket connections: close\n // idle sockets right away, then force-close whatever remains at the\n // deadline so this promise reflects a real close instead of only the\n // timer firing. (closeIdle/closeAllConnections exist on the Node http\n // server; the uWS/engine backends ignore the optional calls.)\n server?.closeIdleConnections?.();\n await Promise.race([\n new Promise<void>(resolve => {\n httpServer.close(() => {\n resolve();\n });\n }),\n new Promise<void>(resolve => {\n const timer = setTimeout(() => {\n try {\n server?.closeAllConnections?.();\n } catch {\n // best-effort force-close\n }\n resolve();\n }, 2000); // 2 second grace period\n timer.unref(); // Don't keep process alive\n }),\n ]);\n } else {\n // Server was never started, just skip close\n this.logger.debug('HTTP server was never started, skipping close');\n }\n } catch {\n // Force close if graceful close fails\n this.logger.warn('Force closing HTTP server due to timeout');\n }\n }\n\n // Clean up module discovery watchers\n if (this.moduleDiscovery && typeof this.moduleDiscovery.cleanup === 'function') {\n try {\n this.moduleDiscovery.cleanup();\n } catch {\n // Ignore cleanup errors\n }\n }\n\n // Shutdown queue manager\n if (this.queueManager) {\n try {\n await this.queueManager.shutdown();\n this.logger.debug('Queue system shutdown complete');\n } catch (error) {\n this.logger.warn(`Error shutting down queue system: ${error}`);\n }\n }\n // Clear queue state on close\n this.queueConfigs.clear();\n this.queueInitialized = false;\n this.queueInitPromise = undefined;\n this.queueManager = undefined;\n\n // Shutdown mail system\n if (this.mailManager) {\n try {\n await this.mailManager.close();\n this.logger.debug('Mail system shutdown complete');\n } catch (error) {\n this.logger.warn(`Error shutting down mail system: ${error}`);\n }\n }\n\n // Clean up event listeners\n try {\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n } catch {\n // Ignore cleanup errors\n }\n\n this.logger.debug('Moro application closed successfully');\n }\n\n // ========================================\n // Job Scheduling API\n // ========================================\n\n /**\n * Register a background job with cron or interval schedule\n * @param name - Job name (used for identification)\n * @param schedule - Cron expression, interval string ('5m', '1h'), or schedule object\n * @param handler - Job function to execute\n * @param options - Job configuration options\n * @returns Job ID for management\n *\n * @example\n * // Cron schedule\n * app.job('cleanup', '0 2 * * *', async () => {\n * await cleanupOldData();\n * });\n *\n * // Interval schedule\n * app.job('health-check', '5m', async (ctx) => {\n * console.log('Health check', ctx.executionId);\n * });\n *\n * // Advanced options\n * app.job('report', '@daily', generateReport, {\n * timeout: 60000,\n * maxRetries: 3,\n * onError: (ctx, error) => console.error('Job failed', error)\n * });\n */\n job(\n name: string,\n schedule: string | JobSchedule,\n handler: JobFunction,\n options: SimpleJobOptions = {}\n ): string {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled. Set config.jobs.enabled = true');\n }\n\n let jobSchedule: JobSchedule;\n\n // Parse schedule input\n if (typeof schedule === 'string') {\n // Check if it's a cron expression or interval\n if (schedule.match(/^(\\d+[smhd]|\\d+\\s*(seconds?|minutes?|hours?|days?))$/i)) {\n // Interval format\n jobSchedule = everyInterval(schedule);\n } else {\n // Cron format\n jobSchedule = cronSchedule(schedule, options.timezone);\n }\n } else {\n jobSchedule = schedule;\n }\n\n const jobOptions: Partial<JobOptions> = {\n name: options.name || name,\n ...(options.enabled !== undefined ? { enabled: options.enabled } : {}),\n ...(options.priority !== undefined ? { priority: options.priority } : {}),\n ...(options.timezone !== undefined ? { timezone: options.timezone } : {}),\n ...(options.maxConcurrent !== undefined ? { maxConcurrent: options.maxConcurrent } : {}),\n ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),\n ...(options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n ...(options.retryDelay !== undefined ? { retryDelay: options.retryDelay } : {}),\n ...(options.retryBackoff !== undefined ? { retryBackoff: options.retryBackoff } : {}),\n ...(options.enableCircuitBreaker !== undefined\n ? { enableCircuitBreaker: options.enableCircuitBreaker }\n : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n ...(options.onStart !== undefined ? { onStart: options.onStart } : {}),\n ...(options.onComplete !== undefined ? { onComplete: options.onComplete } : {}),\n ...(options.onError !== undefined ? { onError: options.onError } : {}),\n };\n\n const jobId = this.jobScheduler.registerJob(name, jobSchedule, handler, jobOptions);\n\n this.logger.info(`Job registered: ${name} (${jobId})`);\n\n return jobId;\n }\n\n /**\n * Enable or disable a registered job\n */\n setJobEnabled(jobId: string, enabled: boolean): boolean {\n if (!this.jobScheduler) {\n return false;\n }\n\n return this.jobScheduler.setJobEnabled(jobId, enabled);\n }\n\n /**\n * Manually trigger a job execution\n */\n async triggerJob(jobId: string, metadata?: Record<string, any>): Promise<any> {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled');\n }\n\n return this.jobScheduler.triggerJob(jobId, metadata);\n }\n\n /**\n * Unregister a job\n */\n unregisterJob(jobId: string): boolean {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled');\n }\n\n return this.jobScheduler.unregisterJob(jobId);\n }\n\n /**\n * Get job metrics\n */\n getJobMetrics(jobId: string): JobMetrics | null {\n if (!this.jobScheduler) {\n return null;\n }\n\n return this.jobScheduler.getJobMetrics(jobId);\n }\n\n /**\n * Get job health status\n */\n getJobHealth(jobId?: string): JobHealth | JobHealth[] {\n if (!this.jobHealthChecker) {\n if (jobId) {\n return {\n jobId,\n name: 'Unknown',\n status: 'unknown',\n enabled: false,\n consecutiveFailures: 0,\n message: 'Job scheduler not enabled',\n };\n }\n return [];\n }\n\n if (jobId) {\n return this.jobHealthChecker.checkJobHealth(jobId);\n }\n\n return this.jobHealthChecker.checkAllJobs();\n }\n\n /**\n * Get scheduler statistics\n */\n getJobStats(): SchedulerStats | null {\n if (!this.jobScheduler) {\n return null;\n }\n\n return this.jobScheduler.getStats();\n }\n\n /**\n * Get overall scheduler health\n */\n getSchedulerHealth() {\n if (!this.jobHealthChecker) {\n return {\n status: 'unknown' as const,\n message: 'Job scheduler not enabled',\n stats: null,\n jobs: [],\n unhealthyJobCount: 0,\n };\n }\n\n return this.jobHealthChecker.getSchedulerHealth();\n }\n\n /**\n * Start the job scheduler (called automatically on listen)\n */\n private async startJobScheduler(): Promise<void> {\n if (!this.jobScheduler || this.jobsStarted) {\n return;\n }\n\n try {\n await this.jobScheduler.start();\n this.jobsStarted = true;\n this.logger.info('Job scheduler started');\n } catch (err) {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n }\n }\n\n // ========================================\n // GraphQL API\n // ========================================\n\n /**\n * Configure GraphQL endpoint (synchronous, lazy initialization)\n *\n * @param options - GraphQL configuration options\n *\n * @example\n * ```ts\n * // Using type definitions and resolvers\n * app.graphqlInit({\n * typeDefs: `\n * type Query {\n * hello: String\n * users: [User]\n * }\n * type User {\n * id: ID!\n * name: String!\n * }\n * `,\n * resolvers: {\n * Query: {\n * hello: () => 'Hello World!',\n * users: () => [{ id: '1', name: 'Alice' }]\n * }\n * }\n * });\n *\n * // Using Pothos schema builder\n * import SchemaBuilder from '@pothos/core';\n *\n * const builder = new SchemaBuilder();\n * builder.queryType({\n * fields: (t) => ({\n * hello: t.string({ resolve: () => 'Hello World!' })\n * })\n * });\n *\n * app.graphqlInit({\n * pothosSchema: builder\n * });\n * ```\n */\n graphqlInit(options: GraphQLOptions): this {\n if (this.graphqlCore || this.graphqlInitPromise) {\n throw new Error('GraphQL has already been configured. Call graphqlInit() only once.');\n }\n\n // Check if graphql package is available\n if (!this.isGraphQLAvailable()) {\n throw new Error(\n 'GraphQL support requires the graphql package to be installed.\\n' +\n 'Install it with: npm install graphql\\n' +\n 'For TypeScript-first GraphQL, also consider: npm install @pothos/core\\n' +\n 'For performance boost: npm install graphql-jit'\n );\n }\n\n this.logger.info('Configuring GraphQL (will initialize on server start)', 'GraphQL', {\n path: options.path || '/graphql',\n jit: options.enableJIT !== false,\n playground: options.enablePlayground !== false,\n });\n\n // Store config and trigger initialization immediately\n this.graphqlConfig = options;\n this.graphqlInitPromise = this.initializeGraphQL(options);\n void this.eventBus.emit('graphql:configured', { options });\n\n return this;\n }\n\n /**\n * Lazy initialize GraphQL system\n */\n private async ensureGraphQLInitialized(): Promise<void> {\n if (this.graphqlCore || this.graphqlInitPromise) {\n await this.graphqlInitPromise;\n return;\n }\n\n if (!this.graphqlConfig) {\n return; // GraphQL not configured, skip\n }\n\n this.graphqlInitPromise = this.initializeGraphQL(this.graphqlConfig);\n await this.graphqlInitPromise;\n }\n\n /**\n * Initialize GraphQL system asynchronously\n */\n private async initializeGraphQL(options: GraphQLOptions): Promise<void> {\n try {\n // Lazy load GraphQL modules\n await this.loadGraphQLModules();\n\n // Create GraphQL core\n this.graphqlCore = new GraphQLCore(options);\n\n // Initialize GraphQL\n await this.graphqlCore.initialize();\n\n this.logger.info('GraphQL initialized successfully', 'GraphQL');\n\n // Setup subscriptions if enabled\n if (options.enableSubscriptions !== false && this.config.websocket.enabled) {\n this.setupGraphQLSubscriptions(options);\n }\n } catch (error) {\n this.logger.error('Failed to initialize GraphQL', 'GraphQL', { error });\n throw error;\n }\n }\n\n /**\n * Check if GraphQL package is available\n */\n private isGraphQLAvailable(): boolean {\n try {\n require.resolve('graphql');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Lazy load GraphQL modules\n */\n private async loadGraphQLModules(): Promise<void> {\n if (GraphQLCore) {\n return; // Already loaded\n }\n\n try {\n // GraphQL core now uses adapters with no static imports from 'graphql'\n const coreModule = await import('./core/graphql/core.js');\n GraphQLCore = coreModule.GraphQLCore;\n\n const subsModule = await import('./core/middleware/built-in/graphql/subscriptions.js');\n GraphQLSubscriptionManager = subsModule.GraphQLSubscriptionManager;\n setupGraphQLSubscriptions = subsModule.setupGraphQLSubscriptions;\n } catch (error) {\n this.logger.error('Failed to load GraphQL modules', 'GraphQL', { error });\n throw new Error('Failed to load GraphQL modules. Please ensure graphql is installed.');\n }\n }\n\n /**\n * Setup GraphQL subscriptions\n */\n private setupGraphQLSubscriptions(options: GraphQLOptions): void {\n const websocketAdapter = this.coreFramework.getWebSocketAdapter();\n\n if (!websocketAdapter) {\n this.logger.warn('GraphQL subscriptions require WebSocket to be enabled', 'GraphQL');\n return;\n }\n\n if (!this.graphqlCore) {\n return;\n }\n\n const schema = this.graphqlCore.getSchema();\n\n this.graphqlSubscriptionManager = setupGraphQLSubscriptions(websocketAdapter, schema, {\n path: options.path ? `${options.path}/subscriptions` : '/graphql/subscriptions',\n contextFactory: options.context,\n });\n\n this.logger.info('GraphQL subscriptions enabled', 'GraphQL', {\n path: options.path ? `${options.path}/subscriptions` : '/graphql/subscriptions',\n });\n }\n\n /**\n * Get GraphQL schema (if configured)\n */\n async getGraphQLSchema(): Promise<any | undefined> {\n await this.ensureGraphQLInitialized();\n return this.graphqlCore?.getSchema();\n }\n\n // ========================================\n // Worker Threads API\n // ========================================\n\n /**\n * Execute a task on worker threads (CPU-intensive operations)\n * @param task - Task to execute\n * @returns Promise resolving to task result\n *\n * @example\n * ```ts\n * // JWT verification (CPU-intensive)\n * const payload = await app.executeOnWorker({\n * id: 'jwt-verify-123',\n * type: 'jwt:verify',\n * data: { token, secret }\n * });\n *\n * // Heavy computation\n * const result = await app.executeOnWorker({\n * id: 'compute-456',\n * type: 'computation:heavy',\n * data: { iterations: 1000000 }\n * });\n * ```\n */\n async executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n return this.workerFacade.executeTask<T>(task);\n }\n\n /**\n * Get worker manager instance for advanced usage\n */\n async getWorkerManager() {\n await this.workerFacade.ensureInitialized?.(); // Trigger initialization if needed\n return this.workerFacade;\n }\n\n /**\n * Get worker thread statistics\n */\n async getWorkerStats() {\n return this.workerFacade.getStats();\n }\n\n /**\n * JWT operations using worker threads (prevents event loop blocking)\n */\n async getJwtWorker() {\n return this.workerFacade.getJwtWorker();\n }\n\n /**\n * Crypto operations using worker threads\n */\n async getCryptoWorker() {\n return this.workerFacade.getCryptoWorker();\n }\n\n /**\n * Heavy computation operations using worker threads\n */\n async getComputeWorker() {\n return this.workerFacade.getComputeWorker();\n }\n\n /**\n * Get GraphQL stats\n */\n async getGraphQLStats() {\n await this.ensureGraphQLInitialized();\n\n if (!this.graphqlCore) {\n return null;\n }\n\n return {\n ...this.graphqlCore.getStats(),\n subscriptions: this.graphqlSubscriptionManager?.getSubscriptionCount() || 0,\n };\n }\n\n // =====================\n // gRPC Methods\n // =====================\n\n /**\n * Configure gRPC server (synchronous, lazy initialization)\n *\n * @example\n * ```typescript\n * app.grpcInit({\n * port: 50051,\n * host: '0.0.0.0',\n * adapter: 'grpc-js',\n * enableHealthCheck: true,\n * enableReflection: true\n * });\n * ```\n */\n grpcInit(options: GrpcOptions = {}): this {\n if (this.grpcInitPromise) {\n this.logger.warn('gRPC already configured', 'GRPC');\n return this;\n }\n\n this.logger.info('Configuring gRPC (will initialize on server start)', 'GRPC');\n\n // Store config for lazy initialization\n this.grpcConfig = {\n port: 50051,\n host: '0.0.0.0',\n adapter: 'grpc-js',\n enableHealthCheck: true,\n enableReflection: false,\n ...options,\n };\n\n return this;\n }\n\n /**\n * Lazy initialize gRPC system\n */\n private async ensureGrpcInitialized(): Promise<void> {\n if (this.grpcManager || this.grpcInitPromise) {\n await this.grpcInitPromise;\n return;\n }\n\n if (!this.grpcConfig) {\n return; // gRPC not configured, skip\n }\n\n this.grpcInitPromise = (async () => {\n try {\n this.logger.info('Initializing gRPC system', 'GRPC');\n\n // Lazy load gRPC manager\n const { GrpcManager } = await import('./core/grpc/grpc-manager.js');\n\n // Create gRPC manager\n this.grpcManager = new GrpcManager(this.grpcConfig);\n\n // Initialize gRPC\n await this.grpcManager.initialize();\n\n this.logger.info('gRPC system initialized', 'GRPC');\n } catch (error) {\n this.logger.error(`Failed to initialize gRPC: ${error}`, 'GRPC');\n throw error;\n }\n })();\n\n await this.grpcInitPromise;\n }\n\n /**\n * Register a gRPC service from a proto file\n *\n * @example\n * ```typescript\n * app.grpcService('./proto/users.proto', 'UserService', {\n * getUser: async (call, callback) => {\n * const user = await db.users.findById(call.request.id);\n * callback(null, user);\n * },\n * listUsers: async (call) => {\n * for (const user of users) {\n * call.write(user);\n * }\n * call.end();\n * }\n * });\n * ```\n */\n async grpcService(\n protoPath: string,\n serviceName: string,\n implementation: ServiceImplementation,\n packageName?: string\n ): Promise<void> {\n if (!this.grpcConfig && !this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n // Lazy initialize gRPC if not already done\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n try {\n await this.grpcManager.registerService(protoPath, serviceName, implementation, packageName);\n\n this.logger.info(`gRPC service registered: ${serviceName}`, 'GRPC');\n } catch (error) {\n this.logger.error(`Failed to register gRPC service ${serviceName}: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Start gRPC server\n * Called automatically by listen() if gRPC is configured\n */\n async startGrpc(): Promise<void> {\n // Lazy initialize if needed\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n return;\n }\n\n if (this.grpcStarted) {\n this.logger.warn('gRPC server already started', 'GRPC');\n return;\n }\n\n try {\n await this.grpcManager.start();\n this.grpcStarted = true;\n\n const stats = this.grpcManager.getStats();\n if (stats) {\n this.logger.info('gRPC server started successfully', 'GRPC');\n }\n } catch (error) {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Stop gRPC server gracefully\n */\n async stopGrpc(): Promise<void> {\n if (!this.grpcManager || !this.grpcStarted) {\n return;\n }\n\n try {\n await this.grpcManager.stop();\n this.grpcStarted = false;\n this.logger.info('gRPC server stopped', 'GRPC');\n } catch (error) {\n this.logger.error(`Error stopping gRPC server: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Create a gRPC client for calling remote services\n *\n * @example\n * ```typescript\n * const client = await app.createGrpcClient(\n * './proto/users.proto',\n * 'UserService',\n * 'localhost:50051'\n * );\n *\n * const user = await client.getUser({ id: '123' });\n * ```\n */\n async createGrpcClient(\n protoPath: string,\n serviceName: string,\n address: string,\n options?: Partial<GrpcClientOptions>\n ): Promise<GrpcClient> {\n if (!this.grpcConfig && !this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n // Lazy initialize gRPC if not already done\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n try {\n const client = await this.grpcManager.createClient(protoPath, serviceName, address, options);\n\n this.logger.info(`gRPC client created for ${serviceName} at ${address}`, 'GRPC');\n\n return client;\n } catch (error) {\n this.logger.error(`Failed to create gRPC client: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Get gRPC statistics\n */\n getGrpcStats() {\n if (!this.grpcManager) {\n return null;\n }\n\n return this.grpcManager.getStats();\n }\n\n /**\n * Get list of registered gRPC services\n */\n getGrpcServices() {\n if (!this.grpcManager) {\n return [];\n }\n\n return this.grpcManager.getServices();\n }\n\n /**\n * Initialize queue system (synchronous for first queue, subsequent queues added immediately)\n *\n * @example\n * ```typescript\n * app.queueInit('emails', {\n * adapter: 'bull',\n * connection: {\n * host: 'localhost',\n * port: 6379\n * },\n * concurrency: 5\n * });\n * ```\n */\n queueInit(name: string, options: any): this {\n // Initialize queue manager on first call\n if (!this.queueInitialized && !this.queueInitPromise) {\n this.queueInitPromise = (async () => {\n try {\n this.logger.info('Initializing queue system', 'QUEUE');\n const { QueueManager } = await import('./core/queue/index.js');\n this.queueManager = new QueueManager(this.eventBus as any);\n this.queueInitialized = true;\n this.logger.info('Queue system initialized', 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to initialize queue system: ${error}`, 'QUEUE');\n throw error;\n }\n })();\n }\n\n // Store config to register after initialization\n this.queueConfigs.set(name, options);\n this.logger.debug(`Queue \"${name}\" configured`, 'QUEUE');\n\n // Register queue async (manager will be ready)\n if (this.queueInitPromise) {\n this.queueInitPromise\n .then(async () => {\n if (this.queueManager) {\n await this.queueManager.registerQueue(name, options);\n this.logger.info(`Queue \"${name}\" registered with ${options.adapter} adapter`, 'QUEUE');\n }\n })\n .catch(error => {\n this.logger.error(`Failed to register queue \"${name}\": ${error}`, 'QUEUE');\n });\n }\n\n return this;\n }\n\n /**\n * Ensure queue system is initialized\n */\n private async ensureQueueInitialized(): Promise<void> {\n if (this.queueInitPromise) {\n await this.queueInitPromise;\n }\n }\n\n /**\n * @deprecated Use queueInit() instead\n */\n async queue(name: string, options: any): Promise<void> {\n if (!this.queueInitialized) {\n try {\n this.logger.info('Initializing queue system', 'QUEUE');\n const { QueueManager } = await import('./core/queue/index.js');\n this.queueManager = new QueueManager(this.eventBus as any);\n this.queueInitialized = true;\n this.logger.info('Queue system initialized', 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to initialize queue system: ${error}`, 'QUEUE');\n throw error;\n }\n }\n\n try {\n await this.queueManager.registerQueue(name, options);\n this.logger.info(`Queue \"${name}\" registered with ${options.adapter} adapter`, 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to register queue \"${name}\": ${error}`, 'QUEUE');\n throw error;\n }\n }\n\n /**\n * Add a job to a queue\n *\n * @example\n * ```typescript\n * await app.addToQueue('emails', {\n * to: 'user@example.com',\n * subject: 'Welcome'\n * }, {\n * priority: 10,\n * delay: 5000\n * });\n * ```\n */\n async addToQueue<T = any>(queueName: string, data: T, options?: any): Promise<any> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queueInit('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.addToQueue(queueName, data, options);\n }\n\n /**\n * Add multiple jobs to a queue in bulk\n *\n * @example\n * ```typescript\n * await app.addBulkToQueue('emails', [\n * { data: { to: 'user1@example.com' }, options: { priority: 1 } },\n * { data: { to: 'user2@example.com' }, options: { priority: 2 } }\n * ]);\n * ```\n */\n async addBulkToQueue<T = any>(\n queueName: string,\n jobs: Array<{ data: T; options?: any }>\n ): Promise<any[]> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queue('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.addBulkToQueue(queueName, jobs);\n }\n\n /**\n * Register a processor for a queue\n *\n * @example\n * ```typescript\n * // Simple processor\n * app.processQueue('emails', async (job) => {\n * await sendEmail(job.data);\n * });\n *\n * // With concurrency\n * app.processQueue('images', 3, async (job) => {\n * await processImage(job.data);\n * });\n * ```\n */\n async processQueue<R = any>(\n queueName: string,\n concurrencyOrHandler: number | ((job: any) => Promise<R>),\n handler?: (job: any) => Promise<R>\n ): Promise<void> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queueInit('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.processQueue(queueName, concurrencyOrHandler, handler);\n }\n\n /**\n * Get queue status\n */\n async getQueueStatus(queueName: string): Promise<any> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getQueueStatus(queueName);\n }\n\n /**\n * Get a specific job from a queue\n */\n async getJob(queueName: string, jobId: string): Promise<any> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getJob(queueName, jobId);\n }\n\n /**\n * Get jobs from a queue by status\n */\n async getJobs(\n queueName: string,\n status?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'paused',\n start: number = 0,\n end: number = -1\n ): Promise<any[]> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getJobs(queueName, status, start, end);\n }\n\n /**\n * Remove a job from a queue\n */\n async removeJob(queueName: string, jobId: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.removeJob(queueName, jobId);\n }\n\n /**\n * Retry a failed job\n */\n async retryJob(queueName: string, jobId: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.retryJob(queueName, jobId);\n }\n\n /**\n * Pause a queue\n */\n async pauseQueue(queueName: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.pauseQueue(queueName);\n }\n\n /**\n * Resume a paused queue\n */\n async resumeQueue(queueName: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.resumeQueue(queueName);\n }\n\n /**\n * Clean old jobs from a queue\n */\n async cleanQueue(\n queueName: string,\n gracePeriod: number,\n status?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'paused'\n ): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.cleanQueue(queueName, gracePeriod, status);\n }\n\n /**\n * Get all registered queue names\n */\n getQueueNames(): string[] {\n // Return configured queues (includes both initialized and pending)\n const configuredQueues = Array.from(this.queueConfigs.keys());\n\n if (!this.queueManager) {\n return configuredQueues;\n }\n\n // Merge with manager's queues (in case some were added directly)\n const managerQueues = this.queueManager.getQueueNames();\n const allQueues = new Set([...configuredQueues, ...managerQueues]);\n return Array.from(allQueues);\n }\n\n /**\n * Check if a queue is registered\n */\n hasQueue(queueName: string): boolean {\n // Check if it's configured (includes both initialized and pending)\n if (this.queueConfigs.has(queueName)) {\n return true;\n }\n\n if (!this.queueManager) {\n return false;\n }\n\n return this.queueManager.hasQueue(queueName);\n }\n\n // =====================\n // Mail System Methods\n // =====================\n\n /**\n * Configure mail system (synchronous, lazy initialization)\n *\n * @example\n * ```typescript\n * // Using Nodemailer (SMTP) - chainable, no await needed!\n * app.mailInit({\n * adapter: 'nodemailer',\n * from: { name: 'My App', email: 'noreply@myapp.com' },\n * connection: {\n * host: 'smtp.gmail.com',\n * port: 587,\n * secure: false,\n * auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASSWORD }\n * },\n * templates: { path: './emails', engine: 'moro', cache: true }\n * });\n *\n * // Using SendGrid\n * app.mailInit({\n * adapter: 'sendgrid',\n * from: 'noreply@myapp.com',\n * connection: { apiKey: process.env.SENDGRID_API_KEY }\n * });\n * ```\n */\n mailInit(config: MailConfig): this {\n if (this.mailInitialized) {\n this.logger.warn('Mail system already configured', 'Mail');\n return this;\n }\n\n // Store config for lazy initialization\n this.mailConfig = config;\n this.logger.debug('Mail system configured (will initialize on first use)', 'Mail');\n void this.eventBus.emit('mail:configured', { config });\n\n return this;\n }\n\n /**\n * Lazy initialize mail system on first use\n */\n private async ensureMailInitialized(): Promise<void> {\n if (this.mailInitialized) {\n return;\n }\n\n if (!this.mailConfig) {\n throw new Error(\n 'Mail system not configured. Call app.mailInit(config) first.\\n' +\n \"Example: app.mailInit({ adapter: 'console', from: 'noreply@myapp.com' });\"\n );\n }\n\n try {\n this.logger.info('Initializing mail system', 'Mail');\n\n const { MailManager } = await import('./core/mail/index.js');\n this.mailManager = new MailManager(this.mailConfig);\n\n await this.mailManager.initialize();\n\n if (this.mailConfig.queue?.enabled && this.queueManager) {\n this.mailManager.setQueueManager(this.queueManager);\n\n const queueName = this.mailConfig.queue.name || 'emails';\n\n if (!this.queueManager.hasQueue(queueName)) {\n this.queueConfigs.set(queueName, {\n adapter: 'memory',\n concurrency: this.mailConfig.queue.attempts || 3,\n });\n await this.ensureQueueInitialized();\n\n await this.processQueue(queueName, async (job: any) => {\n if (this.mailManager) {\n // deliver() bypasses the queue check; send() would re-enqueue the\n // job forever and never actually transmit the email.\n return await this.mailManager.deliver(job.data);\n }\n throw new Error('Mail manager not initialized');\n });\n }\n\n this.logger.info(`Mail queue \"${queueName}\" configured`, 'Mail');\n }\n\n this.mailInitialized = true;\n this.logger.info('Mail system initialized successfully', 'Mail');\n } catch (error) {\n this.logger.error(`Failed to initialize mail system: ${error}`, 'Mail');\n throw error;\n }\n }\n\n /**\n * Send an email\n *\n * @example\n * ```typescript\n * // Simple email\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Welcome',\n * text: 'Welcome to our app!'\n * });\n *\n * // With template\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Password Reset',\n * template: 'password-reset',\n * data: { name: 'John', resetUrl: 'https://myapp.com/reset/token123' }\n * });\n *\n * // With attachments\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Invoice',\n * template: 'invoice',\n * data: { invoice },\n * attachments: [{ filename: 'invoice.pdf', content: pdfBuffer }]\n * });\n * ```\n */\n async sendMail(options: MailOptions): Promise<MailResult> {\n // Lazy initialize on first use\n await this.ensureMailInitialized();\n\n void this.eventBus.emit('mail:sending', { options });\n\n try {\n const result = await this.mailManager.send(options);\n\n if (result.success) {\n void this.eventBus.emit('mail:sent', { result, options });\n } else {\n void this.eventBus.emit('mail:failed', { error: new Error(result.error), options });\n }\n\n return result;\n } catch (error) {\n void this.eventBus.emit('mail:failed', { error, options });\n throw error;\n }\n }\n\n /**\n * Send multiple emails in bulk\n *\n * @example\n * ```typescript\n * await app.sendBulkMail([\n * { to: 'user1@example.com', subject: 'Hello', text: 'Hi!' },\n * { to: 'user2@example.com', subject: 'Hello', text: 'Hi!' }\n * ]);\n * ```\n */\n async sendBulkMail(options: MailOptions[]): Promise<MailResult[]> {\n // Lazy initialize on first use\n await this.ensureMailInitialized();\n\n return await this.mailManager.sendBulk(options);\n }\n\n /**\n * Verify mail adapter connection\n */\n async verifyMail(): Promise<boolean> {\n // Lazy initialize on first use\n try {\n await this.ensureMailInitialized();\n return await this.mailManager.verify();\n } catch {\n return false;\n }\n }\n\n /**\n * Get mail template engine for advanced usage\n */\n getMailTemplateEngine(): any {\n if (!this.mailManager) {\n return undefined;\n }\n\n return this.mailManager.getTemplateEngine();\n }\n\n /**\n * Check if mail system is configured\n */\n hasMailSystem(): boolean {\n return !!this.mailConfig || this.mailInitialized;\n }\n}\n\nlet currentApp: Moro | null = null;\n\n/**\n * Get the current Moro application instance.\n *\n * Returns the app created by the most recent createApp() call.\n * Use this in standalone route files so they can register routes\n * without needing the app to be passed in.\n *\n * @example\n * // routes/health.routes.ts\n * import { getApp } from '@morojs/moro';\n * const app = getApp();\n *\n * app.get('/health', (req, res) => {\n * res.json({ status: 'healthy' });\n * });\n */\nexport function getApp(): Moro {\n if (!currentApp) {\n throw new Error('No app instance available. Call createApp() before getApp().');\n }\n return currentApp;\n}\n\n/**\n * Create and fully initialise a Moro application.\n *\n * Must be awaited — the async step loads moro.config.js/ts via dynamic\n * import() so ESM config files (projects with \"type\":\"module\") work correctly,\n * exactly the same way all other modules are loaded.\n *\n * @example\n * const app = await createApp({ server: { port: 3000 } });\n * app.listen();\n */\n/**\n * Apply LOG_LEVEL / MORO_LOG_LEVEL env var and options.logger to the global logger\n * before config loading runs, so config-system debug logs respect the user's level.\n */\nfunction applyEarlyLogLevel(options?: MoroOptions): void {\n const envLevel = process.env.LOG_LEVEL || process.env.MORO_LOG_LEVEL;\n if (envLevel) {\n applyLoggingConfiguration({ level: envLevel }, undefined);\n }\n if (options?.logger !== undefined) {\n applyLoggingConfiguration(undefined, options.logger);\n }\n}\n\nexport async function createApp(options?: MoroOptions): Promise<Moro> {\n applyEarlyLogLevel(options);\n const config = await initializeConfigAsync(options);\n const app = new Moro(options, config);\n currentApp = app;\n return app;\n}\n\n/**\n * Create a Node.js-targeted Moro application. Must be awaited.\n * @example const app = await createAppNode();\n */\nexport async function createAppNode(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'node' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create a Vercel Edge-targeted Moro application. Must be awaited.\n * @example const app = await createAppEdge();\n */\nexport async function createAppEdge(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'vercel-edge' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create an AWS Lambda-targeted Moro application. Must be awaited.\n * @example const app = await createAppLambda();\n */\nexport async function createAppLambda(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'aws-lambda' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create a Cloudflare Workers-targeted Moro application. Must be awaited.\n * @example const app = await createAppWorker();\n */\nexport async function createAppWorker(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'cloudflare-workers' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"moro.js","sourceRoot":"","sources":["../src/moro.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,8EAA8E;AAC9E,8DAA8D;AAC9D,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAQvD,OAAO,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAE1F,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAE9E,OAAO,EACL,aAAa,GAEd,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAc,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,8EAA8E;AAC9E,0EAA0E;AAC1E,uCAAuC;AACvC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,cAAc,CAAwC,SAAS,CAAC,CAAC;AAC3F,MAAM,EAAE,GAAG,G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AAE,MAAM,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// Moro Framework - Modern TypeScript API Framework\n// Built for developers who demand performance, elegance, and zero compromises\n// Event-driven • Modular • Enterprise-ready • Developer-first\nimport { Moro as MoroCore } from './core/framework.js';\nimport type { WebSocketNamespaceOptions } from './core/networking/websocket-adapter.js';\nimport type { SSLConfigInput } from './core/http/utils/ssl-config.js';\nimport { HttpRequest, HttpResponse } from './core/http/index.js';\nimport { ModuleConfig, InternalRouteDefinition } from './types/module.js';\nimport { MoroOptions } from './types/core.js';\nimport { ModuleDefaultsConfig } from './types/config.js';\nimport { MoroEventBus } from './core/events/index.js';\nimport { createFrameworkLogger, applyLoggingConfiguration } from './core/logger/index.js';\nimport { Logger } from './types/logger.js';\nimport { MiddlewareManager, MIDDLEWARE_FACTORY } from './core/middleware/index.js';\nimport { IntelligentRoutingManager } from './core/routing/app-integration.js';\nimport { RouteSchema, StaticBody } from './core/routing/index.js';\nimport {\n UnifiedRouter,\n RouteBuilder as UnifiedRouteBuilder,\n} from './core/routing/unified-router.js';\nimport { PathMatcher } from './core/routing/path-matcher.js';\nimport { AppDocumentationManager, DocsConfig } from './core/docs/index.js';\nimport { EventEmitter } from 'events';\nimport { requireBuiltin } from './core/utilities/builtin.js';\n\n// node:cluster (it drags in child_process, dgram and net) is loaded only when\n// process clustering actually runs; worker_threads only on the clustering\n// path. See core/utilities/builtin.ts.\nconst nodeCluster = () => requireBuiltin<(typeof import('cluster'))['default']>('cluster');\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport {\n ThreadClusterPrimary,\n ThreadClusterWorker,\n computeWorkerCount,\n isUserTunedYoungGen,\n resolveClusterTransport,\n threadWorkerInfo,\n YOUNG_GEN_MB_FOR_SEMI_SPACE_4,\n type ThreadWorkerInfo,\n} from './core/cluster/thread-cluster.js';\nimport { normalizeValidationError } from './core/validation/schema-interface.js';\nimport { buildModuleBasePath } from './core/utilities/module-path.js';\nimport { filePathToImportURL, loadNativeEngine } from './core/utilities/package-utils.js';\n// Configuration System Integration\nimport { initializeConfig, initializeConfigAsync, type AppConfig } from './core/config/index.js';\n// Runtime System Integration\nimport { RuntimeAdapter, RuntimeType, createRuntimeAdapter } from './core/runtime/index.js';\n// Job System Integration\nimport {\n JobScheduler,\n JobSchedulerOptions,\n JobHealthChecker,\n everyInterval,\n cronSchedule,\n} from './core/jobs/index.js';\nimport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n LeaderElectionOptions,\n} from './core/jobs/index.js';\n// Worker Threads Integration (optional - lazy loaded when needed)\nimport { WorkerThreadsFacade, type WorkerTask } from './core/workers/index.js';\n// GraphQL System Integration (lazy loaded)\nimport type { GraphQLOptions } from './core/graphql/types.js';\n// gRPC System Integration (lazy loaded)\nimport type {\n GrpcOptions,\n ServiceImplementation,\n GrpcClient,\n GrpcClientOptions,\n} from './core/grpc/types.js';\n// Built-in middleware integration\n// Mail System Integration (lazy loaded)\nimport type { MailConfig, MailOptions, MailResult } from './core/mail/types.js';\n\n// Lazy imports for GraphQL to avoid crashes when not installed\nlet GraphQLCore: any;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nlet GraphQLSubscriptionManager: any;\nlet setupGraphQLSubscriptions: any;\n\n/**\n * Route group — prefixes all registered paths with a common base path.\n *\n * @example\n * app.group('/api/v1', (group) => {\n * group.get('/users').handler(getUsersHandler);\n * group.post('/users').handler(createUserHandler);\n * group.get('/users/:id').handler(getUserHandler);\n * });\n */\nexport class RouteGroup {\n private prefix: string;\n private app: Moro;\n\n constructor(prefix: string, app: Moro) {\n this.prefix = prefix;\n this.app = app;\n }\n\n private prefixPath(path: string): string {\n if (path === '/' || path === '') return this.prefix;\n return this.prefix + (path.startsWith('/') ? path : `/${path}`);\n }\n\n get(path: string): UnifiedRouteBuilder;\n get(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n get(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('GET', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.get(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n post(path: string): UnifiedRouteBuilder;\n post(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n post(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('POST', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.post(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n put(path: string): UnifiedRouteBuilder;\n put(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n put(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('PUT', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.put(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n delete(path: string): UnifiedRouteBuilder;\n delete(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n delete(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('DELETE', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.delete(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n patch(path: string): UnifiedRouteBuilder;\n patch(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n patch(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('PATCH', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.patch(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n head(path: string): UnifiedRouteBuilder;\n head(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n head(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('HEAD', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.head(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n options(path: string): UnifiedRouteBuilder;\n options(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n options(path: string, ...args: any[]): UnifiedRouteBuilder | this {\n if (args.length > 0) {\n (this.app as any).addRoute('OPTIONS', this.prefixPath(path), args[0], args[1]);\n return this;\n }\n return this.app.options(this.prefixPath(path)) as UnifiedRouteBuilder;\n }\n\n /** Register a handler for all HTTP methods on the given path (Express-compatible). */\n all(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this {\n this.app.all(this.prefixPath(path), handler, options);\n return this;\n }\n\n group(prefix: string, callback: (group: RouteGroup) => void): this {\n const nested = new RouteGroup(this.prefixPath(prefix), this.app);\n callback(nested);\n return this;\n }\n}\n\nexport class Moro extends EventEmitter {\n private coreFramework!: MoroCore;\n private routes: InternalRouteDefinition[] = [];\n private moduleCounter = 0;\n private loadedModules = new Set<string>();\n private lazyModules = new Map<string, ModuleConfig>();\n private routeHandlers: Record<string, CallableFunction> = {};\n private moduleDiscovery?: any; // Store for cleanup\n private autoDiscoveryOptions: MoroOptions | null = null;\n private autoDiscoveryInitialized = false;\n private autoDiscoveryPromise: Promise<void> | null = null;\n // File-based auto routing state\n private routesLoaded = false;\n private routesLoadedPromise: Promise<void> | null = null;\n // Enterprise event system integration\n private eventBus!: MoroEventBus;\n // Application logger\n private logger!: Logger;\n // Unified routing system (singleton - shared across all routers)\n private unifiedRouter!: UnifiedRouter;\n // Legacy intelligent routing (kept for backward compatibility, now a facade)\n private intelligentRouting!: IntelligentRoutingManager;\n // Documentation system\n private documentation = new AppDocumentationManager();\n // Configuration system\n private config!: AppConfig;\n // Track if user explicitly set logger options (for worker log level handling)\n private userSetLogger = false;\n // Runtime system\n private runtimeAdapter!: RuntimeAdapter;\n private runtimeType!: RuntimeType;\n // Middleware system\n private middlewareManager!: MiddlewareManager;\n // Queued WebSocket registrations (for async adapter detection)\n private queuedWebSocketRegistrations: Array<{\n namespace: string;\n handlers: Record<string, CallableFunction>;\n options?: WebSocketNamespaceOptions;\n processed: boolean;\n }> = [];\n // Job scheduling system\n private jobScheduler?: JobScheduler;\n private jobHealthChecker?: JobHealthChecker;\n private jobsStarted = false;\n // GraphQL system\n private graphqlCore?: any; // Use any to avoid import dependency\n private graphqlSubscriptionManager?: any;\n private graphqlInitPromise?: Promise<void>;\n private graphqlConfig?: any; // Store config for lazy initialization\n // gRPC system (lazy loaded)\n private grpcManager?: any; // Use any to avoid import dependency\n private grpcInitPromise?: Promise<void>;\n private grpcStarted = false;\n private grpcConfig?: any; // Store config for lazy initialization\n // Queue system (lazy loaded)\n private queueManager?: any; // Use any to avoid import dependency\n private queueInitialized = false;\n private queueInitPromise?: Promise<void> | undefined; // Track initialization promise\n private queueConfigs: Map<string, any> = new Map(); // Store queue configs for lazy initialization\n // Worker threads system (lazy loaded facade)\n private workerFacade: WorkerThreadsFacade;\n // Mail system (lazy loaded)\n private mailManager?: any; // Use any to avoid import dependency\n private mailInitialized = false;\n private mailConfig?: any; // Store config for lazy initialization\n // User-registered shutdown hooks (run during close())\n private closeHooks: Array<() => any | Promise<any>> = [];\n // User-registered global error handler\n private errorHandler?: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n // Decorations applied to every request/response/app\n private requestDecorations: Record<string, any> = {};\n private responseDecorations: Record<string, any> = {};\n\n constructor(options: MoroOptions = {}, preloadedConfig?: Readonly<AppConfig>) {\n super(); // Call EventEmitter constructor\n\n // Track if user explicitly set logger/logging options\n this.userSetLogger = !!(options.logger || options.logging);\n\n // Apply logging configuration BEFORE config loading to avoid DEBUG spam\n // 1. Environment variables (base level)\n const envLogLevel = process.env.LOG_LEVEL || process.env.MORO_LOG_LEVEL;\n if (envLogLevel) {\n applyLoggingConfiguration({ level: envLogLevel }, undefined);\n }\n\n // 2. createApp logger options (highest precedence)\n if (options.logger !== undefined) {\n applyLoggingConfiguration(undefined, options.logger);\n }\n\n // Create logger AFTER initial configuration\n this.logger = createFrameworkLogger('App');\n\n // Use pre-loaded config (from async createApp factory) when available,\n // otherwise fall back to synchronous loading (env vars + options, no file)\n this.config = preloadedConfig ?? initializeConfig(options);\n\n // Apply final config logging (this includes normalized logger → logging conversion)\n // Always apply this as it's the authoritative merged config\n if (this.config.logging) {\n applyLoggingConfiguration(this.config.logging, undefined);\n // Recreate logger with updated config\n this.logger = createFrameworkLogger('App');\n }\n\n // NOW initialize routing systems AFTER logger is configured\n this.unifiedRouter = UnifiedRouter.getInstance();\n this.intelligentRouting = new IntelligentRoutingManager();\n\n this.logger.info(\n `Configuration system initialized: ${process.env.NODE_ENV || 'development'}:${this.config.server.port}`\n );\n\n // Initialize runtime system\n this.runtimeType = options.runtime?.type || 'node';\n this.runtimeAdapter = options.runtime?.adapter || createRuntimeAdapter(this.runtimeType);\n\n this.logger.info(`Runtime system initialized: ${this.runtimeType}`, 'Runtime');\n\n // Pass configuration from config to framework\n const frameworkOptions: any = {\n ...options,\n logger: this.config.logging,\n // Enable websockets if either config has it enabled OR user passed websocket options\n websocket:\n this.config.websocket.enabled || options.websocket\n ? options.websocket || this.config.websocket || {}\n : false,\n config: this.config,\n };\n\n this.coreFramework = new MoroCore(frameworkOptions);\n\n // Initialize middleware system\n this.middlewareManager = new MiddlewareManager();\n\n // Expose the manager to the core framework so module routes can resolve\n // user-installed middleware by name (middleware: ['myMiddleware'])\n this.coreFramework.getContainer().register('middlewareManager', () => this.middlewareManager);\n\n // Integrate hooks system with HTTP server\n const httpServer = (this.coreFramework as any).httpServer;\n if (httpServer && httpServer.setHookManager) {\n httpServer.setHookManager((this.middlewareManager as any).hooks);\n // The router swallows handler errors (it produces the 500), so it needs\n // the hook manager too for 'error' hooks to observe them.\n this.unifiedRouter.setHookManager((this.middlewareManager as any).hooks);\n }\n\n // Configure HTTP server performance based on config\n if (httpServer && httpServer.configurePerformance) {\n const performanceConfig = this.config.performance;\n httpServer.configurePerformance({\n compression: performanceConfig?.compression || { enabled: true },\n minimal: performanceConfig?.compression?.enabled === false, // Enable minimal mode if compression disabled\n });\n }\n\n // Access enterprise event bus from core framework\n this.eventBus = (this.coreFramework as any).eventBus;\n\n // Initialize job scheduler if enabled in config\n // Default to enabled (true) unless explicitly disabled\n const jobsEnabled = this.config.jobs?.enabled !== false && options.jobs?.enabled !== false;\n if (jobsEnabled) {\n const le = this.config.jobs?.leaderElection;\n const leaderElectionOptions: LeaderElectionOptions | undefined =\n le?.enabled !== false\n ? {\n strategy: (le?.strategy as 'file' | 'redis' | 'none') ?? 'file',\n ...(le?.lockPath !== undefined ? { lockPath: le.lockPath } : {}),\n ...(le?.lockTimeout !== undefined ? { lockTimeout: le.lockTimeout } : {}),\n ...(le?.heartbeatInterval !== undefined\n ? { heartbeatInterval: le.heartbeatInterval }\n : {}),\n }\n : undefined;\n\n const jobs = this.config.jobs;\n const jobSchedulerOptions: JobSchedulerOptions = {\n enableLeaderElection: jobs?.leaderElection?.enabled !== false,\n ...(jobs?.maxConcurrentJobs !== undefined\n ? { maxConcurrentJobs: jobs.maxConcurrentJobs }\n : {}),\n ...(leaderElectionOptions !== undefined ? { leaderElection: leaderElectionOptions } : {}),\n ...(jobs?.executor !== undefined ? { executor: jobs.executor } : {}),\n ...(jobs?.stateManager !== undefined ? { stateManager: jobs.stateManager } : {}),\n ...(jobs?.gracefulShutdownTimeout !== undefined\n ? { gracefulShutdownTimeout: jobs.gracefulShutdownTimeout }\n : {}),\n };\n\n this.jobScheduler = new JobScheduler(createFrameworkLogger('Jobs'), jobSchedulerOptions);\n\n this.jobHealthChecker = new JobHealthChecker(\n this.jobScheduler,\n createFrameworkLogger('JobHealth')\n );\n\n this.logger.info('Job scheduler initialized', 'Jobs', {\n maxConcurrentJobs: jobSchedulerOptions.maxConcurrentJobs,\n leaderElection: jobSchedulerOptions.enableLeaderElection,\n });\n }\n\n // Initialize worker threads facade (optional - lazy loaded)\n this.workerFacade = new WorkerThreadsFacade();\n\n // Eagerly initialize the worker pool when configured via createApp options.\n // Without this option the pool is created lazily on first worker usage.\n if (options.workers && options.workers.enabled !== false) {\n const workerOptions = {\n ...(options.workers.count !== undefined ? { workerCount: options.workers.count } : {}),\n ...(options.workers.maxQueueSize !== undefined\n ? { maxQueueSize: options.workers.maxQueueSize }\n : {}),\n };\n void this.workerFacade.ensureInitialized(workerOptions).then(() => {\n this.logger.info('Worker thread pool initialized', 'Workers', workerOptions);\n });\n }\n\n // Setup default middleware if enabled - use config defaults with options override\n this.setupDefaultMiddleware({\n ...this.getDefaultOptionsFromConfig(),\n ...options,\n });\n\n // Store auto-discovery options for later initialization\n // IMPORTANT: Auto-discovery is deferred to ensure user middleware (like auth)\n // is registered before module middleware that might bypass it\n this.autoDiscoveryOptions = options.autoDiscover !== false ? options : null;\n\n // Emit initialization event through enterprise event bus\n void this.eventBus.emit('framework:initialized', {\n options,\n config: this.config,\n runtime: this.runtimeType,\n });\n }\n\n /**\n * Get configuration object\n */\n getConfig(): AppConfig {\n return this.config;\n }\n\n /**\n * Get runtime adapter\n */\n getRuntime(): RuntimeAdapter {\n return this.runtimeAdapter;\n }\n\n /**\n * Get runtime type\n */\n getRuntimeType(): RuntimeType {\n return this.runtimeType;\n }\n\n /**\n * Extract default options from configuration\n */\n private getDefaultOptionsFromConfig(): Partial<MoroOptions> {\n return {\n cors: this.config.security.cors.enabled,\n compression: this.config.performance.compression.enabled,\n helmet: this.config.security.helmet.enabled,\n };\n }\n\n // Intelligent route methods - chainable with automatic middleware ordering\n // Overloads for better TypeScript inference\n get(path: string): UnifiedRouteBuilder;\n get(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n get(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('GET', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.get(path);\n }\n\n post(path: string): UnifiedRouteBuilder;\n post(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n post(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('POST', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.post(path);\n }\n\n put(path: string): UnifiedRouteBuilder;\n put(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n put(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('PUT', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.put(path);\n }\n\n delete(path: string): UnifiedRouteBuilder;\n delete(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n delete(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('DELETE', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.delete(path);\n }\n\n patch(path: string): UnifiedRouteBuilder;\n patch(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n patch(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n // Direct route registration\n return this.addRoute('PATCH', path, handler, options);\n }\n // Use unified router for chainable API\n return this.unifiedRouter.patch(path);\n }\n\n head(path: string): UnifiedRouteBuilder;\n head(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n head(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n return this.addRoute('HEAD', path, handler, options);\n }\n return this.unifiedRouter.head(path);\n }\n\n options(path: string): UnifiedRouteBuilder;\n options(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this;\n options(\n path: string,\n handler?: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): UnifiedRouteBuilder | this {\n if (handler !== undefined) {\n return this.addRoute('OPTIONS', path, handler, options);\n }\n return this.unifiedRouter.options(path);\n }\n\n /**\n * Register a handler for all HTTP methods on the given path (Express-compatible).\n * Handler is required — unlike the single-method registrations, there's no builder\n * form since `all()` fans out across methods.\n */\n all(\n path: string,\n handler: ((req: HttpRequest, res: HttpResponse) => any) | StaticBody,\n options?: any\n ): this {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n for (const method of methods) {\n this.addRoute(method, path, handler, options);\n }\n return this;\n }\n\n // Schema-first route method\n route(schema: RouteSchema): void {\n // Use unified router for schema-first registration\n this.unifiedRouter.route(schema);\n }\n\n // Route grouping with common prefix\n group(prefix: string, callback: (group: RouteGroup) => void): this {\n const normalizedPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n const group = new RouteGroup(normalizedPrefix, this);\n callback(group);\n return this;\n }\n\n /**\n * Auto-load route files from a directory.\n *\n * Loads top-level .ts/.js files and index.ts from subdirectories.\n * Other files in subdirectories are ignored — they get pulled in\n * when their index.ts imports them.\n *\n * @example\n * await app.loadRoutes('./src/routes');\n *\n * // routes/\n * // health.ts → loaded\n * // auth/\n * // index.ts → loaded\n * // actions.ts → ignored (imported by index.ts)\n */\n async loadRoutes(dir: string): Promise<void> {\n const { readdirSync, statSync } = await import('fs');\n const { join, extname, resolve } = await import('path');\n const { filePathToImportURL } = await import('./core/utilities/package-utils.js');\n\n const fullPath = resolve(dir);\n const extensions = ['.ts', '.js'];\n\n let items: string[];\n try {\n items = readdirSync(fullPath);\n } catch {\n return;\n }\n\n for (const item of items) {\n const itemPath = join(fullPath, item);\n\n try {\n const stat = statSync(itemPath);\n\n if (stat.isDirectory()) {\n // Subdirectory — only load index.ts or index.js\n for (const ext of extensions) {\n const indexPath = join(itemPath, `index${ext}`);\n try {\n if (statSync(indexPath).isFile()) {\n const importURL = filePathToImportURL(indexPath);\n await import(importURL);\n this.logger.info(`Auto-loaded route: ${item}/index${ext}`, 'RouteLoader');\n break;\n }\n } catch {\n // No index file with this extension, try next\n }\n }\n continue;\n }\n\n // Top-level file\n const ext = extname(item);\n if (!extensions.includes(ext)) continue;\n if (item.includes('.test.') || item.includes('.spec.')) continue;\n\n const importURL = filePathToImportURL(itemPath);\n await import(importURL);\n this.logger.info(`Auto-loaded route: ${item}`, 'RouteLoader');\n } catch (error) {\n this.logger.warn(`Failed to load route file: ${item}`, 'RouteLoader', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n // Enable automatic API documentation\n enableDocs(config: DocsConfig): void {\n this.documentation.enableDocs(config, this.intelligentRouting);\n\n this.logger.info(`API Documentation enabled at ${config.basePath || '/docs'}`, 'Documentation');\n void this.eventBus.emit('docs:enabled', { config });\n }\n\n // Get OpenAPI specification\n getOpenAPISpec() {\n return this.documentation.getOpenAPISpec();\n }\n\n // Get documentation as JSON\n getDocsJSON(): string {\n return this.documentation.getDocsJSON();\n }\n\n // Get documentation as YAML\n getDocsYAML(): string {\n return this.documentation.getDocsYAML();\n }\n\n // Refresh documentation (useful after adding routes dynamically)\n refreshDocs(): void {\n this.documentation.refreshDocs();\n }\n\n // Universal middleware system - seamlessly handles standard and advanced middleware\n async use(middlewareOrFunction: any, config?: any) {\n // `app.use(pathPrefix, router)` — mount a createRouter() instance at the given prefix\n if (\n typeof middlewareOrFunction === 'string' &&\n config &&\n typeof config === 'object' &&\n config._morojsRouter === true &&\n typeof config.mount === 'function'\n ) {\n config.mount(this, middlewareOrFunction);\n return this;\n }\n\n // `app.use(router)` — mount a createRouter() instance at the root\n if (\n middlewareOrFunction &&\n typeof middlewareOrFunction === 'object' &&\n middlewareOrFunction._morojsRouter === true &&\n typeof middlewareOrFunction.mount === 'function'\n ) {\n middlewareOrFunction.mount(this, '');\n return this;\n }\n\n // Built-in factory passed uncalled (app.use(middleware.helmet) instead of\n // app.use(middleware.helmet())). The arity dispatch below would misroute it\n // as an app-plugin and silently discard the result — fail loudly instead.\n if (\n typeof middlewareOrFunction === 'function' &&\n (middlewareOrFunction as any)[MIDDLEWARE_FACTORY]\n ) {\n throw new Error(\n `Built-in middleware factory '${middlewareOrFunction.name || 'unknown'}' was passed uncalled. ` +\n `Call it first: app.use(factory(options)) — e.g. app.use(middleware.helmet()).`\n );\n }\n\n // Standard middleware integration (req, res, next pattern)\n if (typeof middlewareOrFunction === 'function' && middlewareOrFunction.length >= 3) {\n this.coreFramework.addMiddleware(middlewareOrFunction);\n void this.eventBus.emit('middleware:registered', {\n type: 'standard',\n middleware: middlewareOrFunction,\n });\n return this;\n }\n\n // Function-style middleware execution\n if (typeof middlewareOrFunction === 'function' && middlewareOrFunction.length <= 1) {\n await middlewareOrFunction(this);\n void this.eventBus.emit('middleware:executed', {\n type: 'function',\n middleware: middlewareOrFunction,\n });\n return this;\n }\n\n // Advanced middleware pipeline integration - check if it's a MiddlewareInterface\n if (\n middlewareOrFunction &&\n typeof middlewareOrFunction === 'object' &&\n middlewareOrFunction.install &&\n middlewareOrFunction.metadata\n ) {\n // This is a MiddlewareInterface object - install it with the MiddlewareManager\n this.logger.debug(\n `Installing MiddlewareInterface: ${middlewareOrFunction.metadata.name}`,\n 'Middleware'\n );\n this.middlewareManager.install(middlewareOrFunction, config);\n return this;\n }\n\n // Fallback: emit event for unknown middleware types\n void this.eventBus.emit('middleware:advanced', {\n middleware: middlewareOrFunction,\n config,\n });\n this.logger.debug(\n 'Advanced middleware integration - enhanced capabilities loading...',\n 'Middleware'\n );\n return this;\n }\n\n // Plugin compatibility layer - unified middleware interface\n async plugin(middleware: any, options?: any): Promise<this> {\n return this.use(middleware, options);\n }\n\n /**\n * Register a shutdown hook. Hooks run (in registration order) during app.close(),\n * before Moro tears down its own subsystems. Use for closing DB pools, external\n * connections, flushing metrics, etc.\n */\n onClose(fn: () => any | Promise<any>): this {\n this.closeHooks.push(fn);\n return this;\n }\n\n /**\n * Register a global error handler. Invoked when a middleware/handler throws or\n * calls next(err), and no 4-arg error middleware has already handled it. Coexists\n * with Express-style 4-arg error middlewares.\n */\n setErrorHandler(fn: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>): this {\n this.errorHandler = fn;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setErrorHandler) {\n httpServer.setErrorHandler(fn);\n }\n this.unifiedRouter.setErrorHandler(fn as any);\n return this;\n }\n\n /** Internal: retrieve the registered error handler (used by the HTTP server). */\n getErrorHandler():\n ((err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>) | undefined {\n return this.errorHandler;\n }\n\n /**\n * Decorate every request with a property. The value is assigned by reference to\n * each incoming request (use a per-request middleware to set per-request values).\n */\n decorateRequest(name: string, value: any): this {\n this.requestDecorations[name] = value;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setRequestDecorations) {\n httpServer.setRequestDecorations(this.requestDecorations);\n }\n return this;\n }\n\n /** Decorate every response with a property (see decorateRequest). */\n decorateReply(name: string, value: any): this {\n this.responseDecorations[name] = value;\n const httpServer = (this.coreFramework as any)?.httpServer;\n if (httpServer?.setResponseDecorations) {\n httpServer.setResponseDecorations(this.responseDecorations);\n }\n return this;\n }\n\n /** Alias for decorateReply (Fastify-compatible name). */\n decorateResponse(name: string, value: any): this {\n return this.decorateReply(name, value);\n }\n\n /** Decorate the app instance itself. */\n decorate(name: string, value: any): this {\n (this as any)[name] = value;\n return this;\n }\n\n // Module loading with events\n async loadModule(moduleOrPath: ModuleConfig | string) {\n void this.eventBus.emit('module:loading', {\n moduleId: typeof moduleOrPath === 'string' ? moduleOrPath : moduleOrPath.name,\n });\n\n if (typeof moduleOrPath === 'string') {\n const module = await this.importModule(moduleOrPath);\n await this.coreFramework.loadModule(module);\n this.loadedModules.add(moduleOrPath);\n void this.eventBus.emit('module:loaded', {\n moduleId: module.name,\n version: module.version || '1.0.0',\n });\n } else {\n await this.coreFramework.loadModule(moduleOrPath);\n this.loadedModules.add(moduleOrPath.name);\n void this.eventBus.emit('module:loaded', {\n moduleId: moduleOrPath.name,\n version: moduleOrPath.version || '1.0.0',\n });\n }\n\n // IMPORTANT: If modules are loaded manually after auto-discovery,\n // ensure the final module handler is set up to maintain middleware order\n if (this.autoDiscoveryInitialized) {\n this.coreFramework.setupFinalModuleHandler();\n }\n\n return this;\n }\n\n // Database helper with events\n database(adapter: any) {\n void this.eventBus.emit('database:connected', {\n adapter: adapter.constructor.name,\n config: 'hidden',\n });\n this.coreFramework.registerDatabase(adapter);\n return this;\n }\n\n // WebSocket helper with events.\n //\n // Default framing: every frame is a JSON `{ event, data }` envelope and each\n // handler key is an event name. With `{ raw: true }` frames are delivered\n // as-is: `message` gets each text frame as a string, `binary` each binary\n // frame as a Buffer, and a string/Buffer returned from the handler (or\n // `socket.send()`) is the reply frame - what a plain-WebSocket client\n // (browsers, load testers, non-Moro peers) speaks.\n websocket(\n namespace: string,\n handlers: Record<string, CallableFunction>,\n options: WebSocketNamespaceOptions = {}\n ) {\n // Queue the registration to be processed after adapter initialization\n const registration = { namespace, handlers, options, processed: false };\n this.queuedWebSocketRegistrations.push(registration);\n\n // Try to process immediately if adapter is already ready\n const adapter = this.coreFramework.getWebSocketAdapter();\n if (adapter && !registration.processed) {\n // Adapter is ready, process immediately\n this.processWebSocketRegistration(namespace, handlers, adapter, options);\n registration.processed = true;\n }\n // Otherwise, it will be processed when the server starts\n\n return this;\n }\n\n private processWebSocketRegistration(\n namespace: string,\n handlers: Record<string, CallableFunction>,\n adapter: any,\n options: WebSocketNamespaceOptions = {}\n ) {\n this.emit('websocket:registering', { namespace, handlers });\n\n const ns = adapter.createNamespace(namespace, options);\n const raw = options.raw === true;\n const isFrame = (v: unknown): v is string | Buffer | ArrayBuffer | Uint8Array =>\n typeof v === 'string' ||\n Buffer.isBuffer(v) ||\n v instanceof ArrayBuffer ||\n ArrayBuffer.isView(v);\n\n Object.entries(handlers).forEach(([event, handler]) => {\n ns.on('connection', (socket: any) => {\n this.emit('websocket:connection', { namespace, event, socket });\n\n if (event === 'connection') {\n // The documented `connection: socket => ...` hook runs once per\n // socket at open (it is not a client-sendable event name).\n Promise.resolve()\n .then(() => handler(socket))\n .catch((error: any) => this.emit('websocket:error', { namespace, event, error }));\n return;\n }\n\n socket.on(event, (data: any, callback: any) => {\n this.emit('websocket:event', { namespace, event, data });\n\n Promise.resolve(handler(socket, data))\n .then((result: any) => {\n this.emit('websocket:response', { namespace, event, result });\n if (raw) {\n // Raw framing: the return value IS the reply frame\n if (isFrame(result)) socket.send?.(result);\n else if (result !== undefined && result !== null) {\n socket.send?.(JSON.stringify(result));\n }\n return;\n }\n if (callback) callback(result);\n else if (result) socket.emit(`${event}:response`, result);\n })\n .catch((error: any) => {\n this.emit('websocket:error', { namespace, event, error });\n // A raw peer has no envelope to carry an error object; the\n // failure is surfaced through the websocket:error event only.\n if (raw) return;\n const errorResponse = { success: false, error: error.message };\n if (callback) callback(errorResponse);\n else socket.emit('error', errorResponse);\n });\n });\n });\n });\n\n this.emit('websocket:registered', { namespace, handlers });\n }\n\n private async processQueuedWebSocketRegistrations() {\n // Wait for WebSocket adapter to be ready\n await this.coreFramework.ensureWebSocketReady();\n\n const adapter = this.coreFramework.getWebSocketAdapter();\n\n // Check if any unprocessed registrations exist\n const unprocessedRegistrations = this.queuedWebSocketRegistrations.filter(r => !r.processed);\n\n if (!adapter && unprocessedRegistrations.length > 0) {\n throw new Error(\n 'WebSocket features require a WebSocket adapter.\\n\\n' +\n 'Option 1: Install socket.io (auto-detected):\\n' +\n ' npm install socket.io\\n' +\n ' const app = new Moro({ websocket: {} });\\n\\n' +\n 'Option 2: Configure a specific adapter:\\n' +\n \" import { SocketIOAdapter } from '@morojs/moro';\\n\" +\n ' const app = new Moro({ websocket: { adapter: new SocketIOAdapter() } });\\n\\n' +\n 'Option 3: Enable in config file (moro.config.js):\\n' +\n ' export default { websocket: { enabled: true } };'\n );\n }\n\n if (adapter) {\n // Process all unprocessed registrations\n for (const registration of this.queuedWebSocketRegistrations) {\n if (!registration.processed) {\n this.processWebSocketRegistration(\n registration.namespace,\n registration.handlers,\n adapter,\n registration.options\n );\n registration.processed = true;\n }\n }\n }\n }\n\n // Start server with events (Node.js only)\n listen(callback?: () => void): void;\n listen(port: number, callback?: () => void): void;\n listen(port: number, host: string, callback?: () => void): void;\n listen(\n portOrCallback?: number | (() => void),\n hostOrCallback?: string | (() => void),\n callback?: () => void\n ) {\n // Only available for Node.js runtime\n if (this.runtimeType !== 'node') {\n throw new Error(\n `listen() is only available for Node.js runtime. Current runtime: ${this.runtimeType}. Use getHandler() for other runtimes.`\n );\n }\n\n // Handle overloaded parameters - supports:\n // listen(callback)\n // listen(port, callback)\n // listen(port, host, callback)\n let port: number;\n let host: string | undefined;\n\n if (typeof portOrCallback === 'function') {\n // listen(callback) - use port from config\n callback = portOrCallback;\n port = this.config.server.port;\n host = this.config.server.host;\n } else if (typeof portOrCallback === 'number') {\n // listen(port, ...) variants\n port = portOrCallback;\n if (typeof hostOrCallback === 'function') {\n // listen(port, callback)\n callback = hostOrCallback;\n host = undefined;\n } else {\n // listen(port, host, callback)\n host = hostOrCallback;\n }\n } else {\n // listen() - use config defaults\n port = this.config.server.port;\n host = this.config.server.host;\n }\n\n // Validate that we have a valid port\n if (!port || typeof port !== 'number') {\n throw new Error(\n 'Port not specified and not found in configuration. Please provide a port number or configure it in moro.config.js/ts'\n );\n }\n\n // Check if clustering is enabled for massive performance gains\n if (this.config.performance?.clustering?.enabled) {\n // Worker threads (engine backend, POSIX, engine >= 1.1.6) or node:cluster\n // processes - startWithClustering picks and logs the transport.\n this.startWithClustering(port, host as string, callback);\n return;\n }\n\n // Single-process graceful shutdown: SIGINT/SIGTERM (Ctrl-C) drain in-flight\n // work via close() by default; a second signal force-exits. Opt out with\n // `server.gracefulShutdown: false`. (Cluster mode wires its own handlers.)\n this.registerProcessShutdownHandlers();\n\n void this.eventBus.emit('server:starting', { port, runtime: this.runtimeType });\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n this.coreFramework.addMiddleware(docsMiddleware);\n this.logger.debug('Documentation middleware added', 'Documentation');\n } catch {\n // Documentation not enabled, that's fine\n this.logger.debug('Documentation not enabled', 'Documentation');\n }\n\n // Attach the unified router (handles both chainable and direct routes)\n this.attachUnifiedRouter();\n\n // Register legacy direct routes with the HTTP server (for backward compatibility)\n if (this.routes.length > 0) {\n this.registerDirectRoutes();\n }\n\n const startServer = () => {\n const actualCallback = () => {\n const displayHost = host || 'localhost';\n const serverKind = this.engine;\n this.logger.info('Moro Server Started', 'Server');\n this.logger.info(`Runtime: ${this.runtimeType}`, 'Server');\n this.logger.info(\n `HTTP engine: ${serverKind.server}` +\n (serverKind.enginePackage ? ` (${serverKind.enginePackage})` : ''),\n 'Server'\n );\n this.logger.info(`HTTP API: http://${displayHost}:${port}`, 'Server');\n if (this.config.websocket.enabled) {\n this.logger.info(`WebSocket: ws://${displayHost}:${port}`, 'Server');\n }\n this.logger.info('Learn more at https://morojs.com', 'Server');\n\n // Log unified router stats\n const routeCount = this.unifiedRouter.getRouteCount();\n if (routeCount > 0) {\n this.logger.info(`Unified Router: ${routeCount} routes registered`, 'Server');\n // Log performance stats\n this.unifiedRouter.logPerformanceStats();\n }\n\n void this.eventBus.emit('server:started', {\n port,\n runtime: this.runtimeType,\n engine: serverKind,\n });\n\n // Start job scheduler after server starts\n this.startJobScheduler().catch(err => {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n });\n\n // Initialize GraphQL if configured\n this.ensureGraphQLInitialized().catch(error => {\n this.logger.error(`Failed to initialize GraphQL: ${error}`, 'GraphQL');\n });\n\n // Start gRPC server if initialized\n if (this.grpcManager && !this.grpcStarted) {\n this.startGrpc().catch(error => {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n });\n }\n\n if (callback) callback();\n };\n\n if (host && typeof host === 'string') {\n this.coreFramework.listen(port, host, actualCallback);\n } else {\n this.coreFramework.listen(port, actualCallback);\n }\n };\n\n // Ensure auto-discovery and WebSocket setup is complete before starting server.\n // Routes load after modules so DB/services/middleware set up during discovery\n // are available to route files.\n Promise.all([\n this.ensureAutoDiscoveryComplete().then(() => this.ensureRoutesLoaded()),\n this.processQueuedWebSocketRegistrations(),\n ])\n .then(\n () => startServer(),\n initError => {\n // Initialization (auto-discovery / WebSocket setup) failed — this is\n // NOT the listen() call. Handle it here so a subsequent listen()\n // failure can't be misdiagnosed as an init failure and retried.\n this.logger.error('Initialization failed during server start', 'Framework', {\n error: initError instanceof Error ? initError.message : String(initError),\n });\n // WebSocket-adapter misconfiguration is fatal; propagate it.\n if (\n initError instanceof Error &&\n initError.message.includes('WebSocket features require a WebSocket adapter')\n ) {\n throw initError;\n }\n // A non-fatal init issue (e.g. auto-discovery) — start the server anyway.\n startServer();\n }\n )\n .catch(error => {\n // startServer()/listen() failed — e.g. EADDRINUSE thrown synchronously\n // by the native engine. Retrying would fail identically, so surface it\n // via the 'error' event (Node's server convention) instead of retrying\n // into an unhandled rejection. With no 'error' listener, EventEmitter\n // rethrows — the desired visible crash for a fatal bind failure.\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(`Failed to start server on port ${port}: ${message}`, 'Framework');\n this.emit('error', error);\n });\n }\n\n // Public method to manually initialize auto-discovery\n // Useful for ensuring auth middleware is registered before auto-discovery\n async initializeAutoDiscoveryNow(): Promise<void> {\n return this.ensureAutoDiscoveryComplete();\n }\n\n // Load file-based routes from the configured directories (config.routing).\n // Runs once during listen() after module discovery. Idempotent and safe to\n // call alongside a manual app.loadRoutes() — the ES module cache prevents a\n // file from registering twice even if both resolve to the same path.\n private async ensureRoutesLoaded(): Promise<void> {\n if (this.routesLoaded) return;\n if (this.routesLoadedPromise) return this.routesLoadedPromise;\n\n const routing = this.config.routing;\n const disabled =\n routing === false || (typeof routing === 'object' && routing.enabled === false);\n if (disabled) {\n this.routesLoaded = true;\n return;\n }\n\n this.routesLoadedPromise = (async () => {\n const isProd = process.env.NODE_ENV === 'production';\n const defaultPaths = isProd ? ['./dist/routes', './dist/src/routes'] : ['./src/routes'];\n const paths =\n typeof routing === 'object' && Array.isArray(routing.paths) && routing.paths.length > 0\n ? routing.paths\n : defaultPaths;\n\n for (const dir of paths) {\n try {\n await this.loadRoutes(dir);\n } catch (error) {\n this.logger.warn(`Failed to auto-load routes from ${dir}`, 'RouteLoader', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n })();\n\n try {\n await this.routesLoadedPromise;\n this.routesLoaded = true;\n } finally {\n this.routesLoadedPromise = null;\n }\n }\n\n // Public API: Initialize modules explicitly after middleware setup\n // This provides users with explicit control over module loading timing\n // IMPORTANT: This forces module loading even if autoDiscovery.enabled is false\n // Usage: app.initModules() or app.initModules({ paths: ['./my-modules'] })\n initModules(options?: {\n paths?: string[];\n patterns?: string[];\n recursive?: boolean;\n loadingStrategy?: 'eager' | 'lazy' | 'conditional';\n watchForChanges?: boolean;\n ignorePatterns?: string[];\n loadOrder?: 'alphabetical' | 'dependency' | 'custom';\n failOnError?: boolean;\n maxDepth?: number;\n }): void {\n this.logger.info('User-requested module initialization', 'ModuleSystem');\n\n // If already initialized, do nothing\n if (this.autoDiscoveryInitialized) {\n this.logger.debug('Auto-discovery already completed, skipping', 'ModuleSystem');\n return;\n }\n\n // Store the options and mark that we want to force initialization\n this.autoDiscoveryOptions = {\n autoDiscover: {\n enabled: true, // Force enabled regardless of original config\n paths: options?.paths || ['./modules', './src/modules'],\n patterns: options?.patterns || [\n '**/*.module.{ts,js}',\n '**/index.{ts,js}',\n '**/*.config.{ts,js}',\n ],\n recursive: options?.recursive ?? true,\n loadingStrategy: options?.loadingStrategy || ('eager' as const),\n watchForChanges: options?.watchForChanges ?? false,\n ignorePatterns: options?.ignorePatterns || [\n '**/*.test.{ts,js}',\n '**/*.spec.{ts,js}',\n '**/node_modules/**',\n ],\n loadOrder: options?.loadOrder || ('dependency' as const),\n failOnError: options?.failOnError ?? false,\n maxDepth: options?.maxDepth ?? 5,\n },\n };\n\n this.logger.debug(\n 'Module initialization options stored, will execute on next listen/getHandler call',\n 'ModuleSystem'\n );\n }\n\n // Robust method to ensure auto-discovery is complete, handling race conditions\n private async ensureAutoDiscoveryComplete(): Promise<void> {\n // If already initialized, nothing to do\n if (this.autoDiscoveryInitialized) {\n return;\n }\n\n // If auto-discovery is disabled, mark as initialized\n if (!this.autoDiscoveryOptions) {\n this.autoDiscoveryInitialized = true;\n return;\n }\n\n // If already in progress, wait for it to complete\n if (this.autoDiscoveryPromise) {\n return this.autoDiscoveryPromise;\n }\n\n // Start auto-discovery\n this.autoDiscoveryPromise = this.performAutoDiscovery();\n\n try {\n await this.autoDiscoveryPromise;\n this.autoDiscoveryInitialized = true;\n } catch (error) {\n // Reset promise on error so it can be retried\n this.autoDiscoveryPromise = null;\n throw error;\n } finally {\n this.autoDiscoveryOptions = null; // Clear after attempt\n }\n }\n\n // Perform the actual auto-discovery work\n private async performAutoDiscovery(optionsOverride?: MoroOptions): Promise<void> {\n const optionsToUse = optionsOverride || this.autoDiscoveryOptions;\n if (!optionsToUse) return;\n\n this.logger.debug('Starting auto-discovery initialization', 'AutoDiscovery');\n\n await this.initializeAutoDiscovery(optionsToUse);\n\n this.logger.debug('Auto-discovery initialization completed', 'AutoDiscovery');\n }\n\n // Get handler for non-Node.js runtimes\n getHandler() {\n // Ensure auto-discovery is complete for non-Node.js runtimes\n // This handles the case where users call getHandler() immediately after createApp()\n this.ensureAutoDiscoveryComplete().catch(error => {\n this.logger.error('Auto-discovery initialization failed for runtime handler', 'Framework', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n\n // Create a unified request handler that works with the runtime adapter.\n // Lifecycle hooks run here so serverless runtimes (Lambda, Edge, Workers)\n // have parity with the long-running servers. Unlike those servers,\n // 'response' hooks are awaited before returning — post-return work would\n // be frozen or dropped by the platform.\n const hookManager = this.middlewareManager.getHookManager();\n const handler = async (req: HttpRequest, res: HttpResponse) => {\n try {\n if (hookManager.hasHooks('request')) {\n await hookManager.execute('request', { request: req, response: res });\n if (res.headersSent) return;\n }\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n await docsMiddleware(req, res, () => {});\n if (res.headersSent) return;\n } catch {\n // Documentation not enabled, that's fine\n }\n\n // Try unified router first (handles all routes)\n const handled = await this.unifiedRouter.handleRequest(req, res);\n if (handled) return;\n\n // Handle legacy direct routes (backward compatibility)\n if (this.routes.length > 0) {\n await this.handleDirectRoutes(req, res);\n }\n } catch (error) {\n if (hookManager.hasHooks('error')) {\n try {\n await hookManager.execute('error', { request: req, response: res, error });\n } catch (hookError: any) {\n this.logger.error(`Error hook error: ${hookError?.message || hookError}`, 'Hooks');\n }\n }\n throw error;\n } finally {\n if (hookManager.hasHooks('response')) {\n try {\n await hookManager.execute('response', { request: req, response: res });\n } catch (hookError: any) {\n this.logger.error(`Response hook error: ${hookError?.message || hookError}`, 'Hooks');\n }\n }\n }\n };\n\n // Use the runtime adapter to create the appropriate handler\n return this.runtimeAdapter.createServer(handler);\n }\n\n // Handle direct routes for runtime adapters\n private async handleDirectRoutes(req: HttpRequest, res: HttpResponse) {\n // Find matching route\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const route = this.findMatchingRoute(req.method!, req.path);\n if (!route) {\n (res as any).status(404).json({ success: false, error: 'Not found' });\n return;\n }\n\n try {\n // Extract path parameters\n const matches = req.path.match(route.pattern);\n if (matches) {\n req.params = {};\n route.paramNames.forEach((name: string, index: number) => {\n req.params[name] = matches[index + 1] ?? '';\n });\n }\n\n // Get handler function\n const handler = this.routeHandlers[route.handler];\n if (!handler) {\n (res as any).status(500).json({ success: false, error: 'Handler not found' });\n return;\n }\n\n // Execute validation if present\n if (route.validation) {\n try {\n const validated = route.validation.parse(req.body);\n req.body = validated;\n } catch (error: any) {\n if (error.issues) {\n (res as any).status(400).json({\n success: false,\n error: 'Validation failed',\n details: error.issues.map((issue: any) => ({\n field: issue.path.length > 0 ? issue.path.join('.') : 'body',\n message: issue.message,\n code: issue.code,\n })),\n });\n return;\n }\n throw error;\n }\n }\n\n // Execute rate limiting if present\n if (route.rateLimit) {\n const clientId = req.ip || 'unknown';\n const key = `${route.method}:${route.path}:${clientId}`;\n\n if (!this.checkRateLimit(key, route.rateLimit)) {\n (res as any).status(429).json({\n success: false,\n error: 'Rate limit exceeded',\n retryAfter: Math.ceil(route.rateLimit.window / 1000),\n });\n return;\n }\n }\n\n // Execute the handler\n const result = await handler(req, res);\n if (result && !(res as any).headersSent) {\n (res as any).json(result);\n }\n } catch (error) {\n if (!(res as any).headersSent) {\n (res as any).status(500).json({\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n });\n }\n }\n }\n\n // Advanced route matching with caching and optimization\n private routeCache = new Map<string, { pattern: RegExp; paramNames: string[] }>();\n private staticRouteMap = new Map<string, any>();\n private dynamicRoutesBySegments = new Map<number, any[]>();\n\n private findMatchingRoute(method: string, path: string) {\n // O(1) static route lookup\n const staticKey = `${method}:${path}`;\n const staticRoute = this.staticRouteMap.get(staticKey);\n if (staticRoute) {\n return {\n ...staticRoute,\n pattern: /^.*$/, // Dummy pattern for static routes\n paramNames: [],\n };\n }\n\n // Dynamic route matching by segment count\n const segmentCount = PathMatcher.countSegments(path);\n const candidateRoutes = this.dynamicRoutesBySegments.get(segmentCount) || [];\n\n for (const route of candidateRoutes) {\n if (route.method === method) {\n const cacheKey = `${method}:${route.path}`;\n let pattern = this.routeCache.get(cacheKey);\n\n if (!pattern) {\n pattern = this.pathToRegex(route.path);\n this.routeCache.set(cacheKey, pattern);\n }\n\n if (pattern.pattern.test(path)) {\n return {\n ...route,\n pattern: pattern.pattern,\n paramNames: pattern.paramNames,\n };\n }\n }\n }\n\n return null;\n }\n\n // Convert path to regex (simplified version)\n private pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const regexPath = path.replace(/\\//g, '\\\\/').replace(/:([^/]+)/g, (match, paramName) => {\n paramNames.push(paramName);\n return '([^/]+)';\n });\n\n return {\n pattern: new RegExp(`^${regexPath}$`),\n paramNames,\n };\n }\n\n // Access enterprise event system for advanced integrations\n get events() {\n return this.eventBus;\n }\n\n // The application's live hook manager — the same instance\n // MiddlewareInterface.install() receives. Register request-lifecycle hooks\n // directly: app.hooks.before('request', ctx => {...}),\n // app.hooks.after('response', ctx => {...}).\n get hooks() {\n return this.middlewareManager.getHookManager();\n }\n\n // Access to core framework for advanced usage\n get core() {\n return this.coreFramework;\n }\n\n // Which HTTP server actually booted (engine/node/http2), the package\n // backing a native engine, and the fallback reason when one was requested\n // but the Node server booted instead. Stable surface for logs/tests/benchmarks.\n get engine(): ReturnType<MoroCore['getServerKind']> {\n return this.coreFramework.getServerKind();\n }\n\n /**\n * Rotate the TLS certificate/key on the running listener without a restart.\n * With no argument the key/cert files from `server.ssl` are re-read; with\n * one, the given material (either ssl shape) replaces them. The new pair is\n * validated first, so a bad file leaves the current certificate serving and\n * rejects. Connections already established are untouched. `server.ssl.watch`\n * calls this automatically when the files change.\n */\n async reloadTLS(ssl?: SSLConfigInput): Promise<void> {\n await this.coreFramework.reloadTLS(ssl);\n this.emit('tls:reloaded', { source: ssl ? 'argument' : 'files' });\n }\n\n getServerKind(): ReturnType<MoroCore['getServerKind']> {\n return this.coreFramework.getServerKind();\n }\n\n // Public API for accessing the DI container\n getContainer() {\n return this.coreFramework.getContainer();\n }\n\n // Force cleanup of pooled objects\n forceCleanup(): void {\n const httpServer = (this.coreFramework as any).httpServer;\n if (httpServer && httpServer.forceCleanup) {\n httpServer.forceCleanup();\n }\n }\n\n // Private methods\n private addRoute(\n method: string,\n path: string,\n handler: ((req: any, res: any) => any | Promise<any>) | string | Buffer,\n options: any = {}\n ) {\n // A literal body - app.get('/', '') - is the same route the builder's\n // .handler('') registers: the unified router turns it into a handler and,\n // with nothing else configured, a reply the native engine answers itself.\n // It never enters the legacy direct-route table, whose wrapper would\n // call it as a function.\n if (typeof handler !== 'function') {\n this.unifiedRouter.registerRoute({\n method: method as any,\n path,\n handler: handler as any,\n validation: options.validation,\n rateLimit: options.rateLimit,\n cache: options.cache,\n middleware: options.middleware,\n });\n return this;\n }\n\n // Register with unified router (primary routing system)\n this.unifiedRouter.addRoute(method as any, path, handler as any, options.middleware || []);\n\n // Also store in legacy routes array for backward compatibility\n const handlerName = `handler_${this.routes.length}`;\n const route = {\n method: method as any,\n path,\n handler: handlerName,\n validation: options.validation,\n rateLimit: options.rateLimit,\n cache: options.cache,\n middleware: options.middleware,\n };\n\n this.routes.push(route);\n\n // Organize routes for optimal lookup (legacy)\n this.organizeRouteForLookup(route);\n\n // Store handler for later module creation (legacy)\n this.routeHandlers[handlerName] = handler;\n\n return this;\n }\n\n private organizeRouteForLookup(route: any): void {\n if (!route.path.includes(':')) {\n // Static route - add to static map for O(1) lookup\n const staticKey = `${route.method}:${route.path}`;\n this.staticRouteMap.set(staticKey, route);\n } else {\n // Dynamic route - organize by segment count\n const segmentCount = PathMatcher.countSegments(route.path);\n\n if (!this.dynamicRoutesBySegments.has(segmentCount)) {\n this.dynamicRoutesBySegments.set(segmentCount, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.dynamicRoutesBySegments.get(segmentCount)!.push(route);\n }\n }\n\n // Attach the unified router to the HTTP server. Servers that support direct\n // dispatch (setRouterHandler) get the router called straight from\n // handleRequest - after global middleware, with no per-request promise\n // wrapper. Older/custom servers fall back to the middleware adapter.\n private attachUnifiedRouter(): void {\n const httpServer = (this.coreFramework as any).httpServer;\n\n if (httpServer && typeof httpServer.setRouterHandler === 'function') {\n const router = this.unifiedRouter;\n httpServer.setRouterHandler((req: HttpRequest, res: HttpResponse) =>\n router.handleRequest(req, res)\n );\n\n // A server that answers fixed replies itself (MoroEngineServer on an\n // engine with capabilities.staticRoutes) gets every route whose handler\n // is a literal body, so those requests never enter JS. The route's\n // handler stays registered: it answers HEAD, and everything on servers\n // without the capability.\n if (typeof httpServer.setStaticRoute === 'function') {\n for (const schema of router.getAllRoutes()) {\n const fixed = schema.static;\n if (fixed) {\n httpServer.setStaticRoute(\n schema.method,\n schema.path,\n fixed.status,\n fixed.headers,\n fixed.body\n );\n }\n }\n }\n // Same for param(name) handlers on bare single-parameter routes: the\n // engine echoes the segment itself (engine >= 1.1.9).\n if (typeof httpServer.setParamRoute === 'function') {\n for (const schema of router.getAllRoutes()) {\n const echo = schema.paramEcho;\n if (echo) {\n httpServer.setParamRoute(\n schema.method,\n echo.prefix,\n echo.suffix,\n echo.status,\n echo.headers\n );\n }\n }\n }\n\n // Servers with a native router (uWS) additionally get fast-path routes\n // registered directly on it - evaluated at listen so late-loaded routes\n // are included; error handling shares the unified router's semantics\n if (typeof httpServer.setNativeRouteProvider === 'function') {\n httpServer.setNativeRouteProvider(\n () => router.getNativeFastPathRoutes(),\n (req: HttpRequest, res: HttpResponse, err: any) => router.handleRouteError(err, req, res)\n );\n }\n return;\n }\n\n this.coreFramework.addMiddleware(\n async (req: HttpRequest, res: HttpResponse, next: () => void) => {\n // Try unified router first (handles all route types)\n const handled = this.unifiedRouter.handleRequest(req, res);\n\n // Check if it's a promise (async route) or sync (fast-path)\n if (handled && typeof (handled as any).then === 'function') {\n // Async - await the result\n const isHandled = await (handled as Promise<boolean>);\n if (!isHandled) {\n next();\n }\n } else {\n // Sync - check immediately\n if (!(handled as boolean)) {\n next();\n }\n }\n }\n );\n }\n\n private registerDirectRoutes() {\n // Register routes directly with the HTTP server for optimal performance\n // This provides the intuitive developer experience users expect\n for (const route of this.routes) {\n const handler = this.routeHandlers[route.handler];\n if (!handler) continue;\n\n // Get direct access to the HTTP server through the core framework\n const httpServer = (this.coreFramework as any).httpServer;\n\n // Create a wrapper handler that handles validation, rate limiting, and return values\n const wrappedHandler = async (req: any, res: any) => {\n try {\n // Enhance request with events property for direct routes\n req.events = this.eventBus;\n\n // Universal validation middleware (works with any ValidationSchema)\n if (route.validation) {\n try {\n const validated = await route.validation.parseAsync(req.body);\n req.body = validated;\n } catch (error: any) {\n // Handle universal validation errors using the new error handler\n const normalizedError = normalizeValidationError(error);\n const errors = normalizedError.issues.map((issue: any) => ({\n field: issue.path.length > 0 ? issue.path.join('.') : 'body',\n message: issue.message,\n code: issue.code,\n path: issue.path,\n }));\n\n // Get global validation error handler\n let globalHandler;\n try {\n const { getGlobalConfig } = await import('./core/config/index.js');\n const config = getGlobalConfig();\n globalHandler = config.modules.validation.onError;\n } catch {\n globalHandler = undefined;\n }\n\n // Use route-level or global error handler\n const handler = route.onValidationError || globalHandler;\n if (handler) {\n try {\n const errorResponse = handler(errors, {\n request: {\n method: req.method || 'UNKNOWN',\n path: req.path || req.url || '',\n url: req.url || '',\n headers: req.headers || {},\n },\n field: 'body',\n });\n\n if (errorResponse.headers) {\n Object.entries(errorResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.status(errorResponse.status).json(errorResponse.body);\n return;\n } catch {\n // Fallback if handler throws\n res.status(500).json({\n success: false,\n error: 'Internal error while handling validation error',\n requestId: req.requestId,\n });\n return;\n }\n }\n\n // Default error response if no handler\n res.status(400).json({\n success: false,\n error: 'Validation failed',\n details: errors,\n requestId: req.requestId,\n });\n return;\n }\n }\n\n // Rate limiting middleware\n if (route.rateLimit) {\n const clientId = req.ip || req.connection?.remoteAddress || 'unknown';\n const key = `${route.method}:${route.path}:${clientId}`;\n\n if (!this.checkRateLimit(key, route.rateLimit)) {\n res.status(429).json({\n success: false,\n error: 'Rate limit exceeded',\n retryAfter: Math.ceil(route.rateLimit.window / 1000),\n });\n return;\n }\n }\n\n // Execute the actual handler\n const result = await handler(req, res);\n if (result && !res.headersSent) {\n res.json(result);\n }\n } catch (error) {\n // Route through user-registered error handler first, if any.\n if (this.errorHandler && !res.headersSent) {\n try {\n const handlerResult = this.errorHandler(error, req, res);\n if (handlerResult && typeof (handlerResult as any).then === 'function') {\n await handlerResult;\n }\n if (res.headersSent) return;\n } catch (handlerErr) {\n this.logger.error('Error handler itself threw', 'RequestHandler', {\n error: handlerErr instanceof Error ? handlerErr.message : String(handlerErr),\n });\n }\n }\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n });\n }\n }\n };\n\n // Register with the appropriate HTTP method\n const method = route.method.toLowerCase();\n if (httpServer && httpServer[method]) {\n httpServer[method](route.path, wrappedHandler);\n }\n }\n }\n\n // Simple rate limiting for direct routes\n private rateLimitStore = new Map<string, { count: number; resetTime: number }>();\n\n private checkRateLimit(key: string, config: { requests: number; window: number }): boolean {\n const now = Date.now();\n const bucket = this.rateLimitStore.get(key);\n\n if (!bucket || now > bucket.resetTime) {\n // Create new bucket or reset expired bucket\n this.rateLimitStore.set(key, {\n count: 1,\n resetTime: now + config.window,\n });\n return true;\n }\n\n if (bucket.count >= config.requests) {\n return false; // Rate limit exceeded\n }\n\n bucket.count++;\n return true;\n }\n\n private setupDefaultMiddleware(_options: MoroOptions) {\n // cors/helmet/compression/bodySize are installed once by MoroCore.setupCore()\n // (config-driven, with the configured bodySizeLimit). Registering them here\n // again made every request run each of them twice.\n }\n\n // Enhanced auto-discovery initialization\n private async initializeAutoDiscovery(options: MoroOptions): Promise<void> {\n const { ModuleDiscovery } = await import('./core/modules/auto-discovery.js');\n\n // Merge auto-discovery configuration\n const autoDiscoveryConfig = this.mergeAutoDiscoveryConfig(options);\n\n if (!autoDiscoveryConfig.enabled) {\n return;\n }\n\n this.moduleDiscovery = new ModuleDiscovery(process.cwd());\n\n try {\n // Discover modules based on configuration\n const modules = await this.moduleDiscovery.discoverModulesAdvanced(autoDiscoveryConfig);\n\n // Load modules based on strategy\n await this.loadDiscoveredModules(modules, autoDiscoveryConfig);\n\n // Setup final module handler to run after user middleware (like auth)\n this.coreFramework.setupFinalModuleHandler();\n\n // Setup file watching if enabled\n if (autoDiscoveryConfig.watchForChanges) {\n this.moduleDiscovery.watchModulesAdvanced(\n autoDiscoveryConfig,\n async (updatedModules: ModuleConfig[]) => {\n await this.handleModuleChanges(updatedModules);\n }\n );\n }\n\n this.logger.info(\n `Auto-discovery completed: ${modules.length} modules loaded`,\n 'ModuleDiscovery'\n );\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n if (autoDiscoveryConfig.failOnError) {\n throw new Error(`Module auto-discovery failed: ${errorMsg}`);\n } else {\n this.logger.warn(`Module auto-discovery failed: ${errorMsg}`, 'ModuleDiscovery');\n }\n }\n }\n\n // Merge auto-discovery configuration from multiple sources\n private mergeAutoDiscoveryConfig(options: MoroOptions) {\n const defaultConfig = this.config.modules.autoDiscovery;\n\n // Handle legacy modulesPath option\n if (options.modulesPath && !options.autoDiscover) {\n return {\n ...defaultConfig,\n paths: [options.modulesPath],\n };\n }\n\n // Handle boolean autoDiscover option\n if (typeof options.autoDiscover === 'boolean') {\n return {\n ...defaultConfig,\n enabled: options.autoDiscover,\n };\n }\n\n // Handle object autoDiscover option\n if (typeof options.autoDiscover === 'object') {\n return {\n ...defaultConfig,\n ...options.autoDiscover,\n };\n }\n\n return defaultConfig;\n }\n\n // Load discovered modules based on strategy\n private async loadDiscoveredModules(\n modules: ModuleConfig[],\n config: ModuleDefaultsConfig['autoDiscovery']\n ): Promise<void> {\n switch (config.loadingStrategy) {\n case 'eager':\n // Load all modules immediately\n for (const module of modules) {\n await this.loadModule(module);\n }\n break;\n\n case 'lazy':\n // Register modules for lazy loading\n this.registerLazyModules(modules);\n break;\n\n case 'conditional':\n // Load modules based on conditions\n await this.loadConditionalModules(modules);\n break;\n\n default:\n // Default to eager loading\n for (const module of modules) {\n await this.loadModule(module);\n }\n }\n }\n\n // Register modules for lazy loading\n private registerLazyModules(modules: ModuleConfig[]): void {\n modules.forEach(module => {\n // Store module for lazy loading when first route is accessed\n this.lazyModules.set(module.name, module);\n\n // Register placeholder routes that trigger lazy loading\n if (module.routes) {\n module.routes.forEach(route => {\n const basePath = buildModuleBasePath(\n this.config.modules?.apiPrefix,\n module.version,\n module.name\n );\n // Handle root path within module: '/' should map to basePath, not basePath + '/'\n const routePath = route.path === '/' ? '' : route.path;\n const fullPath = `${basePath}${routePath}`;\n\n // Note: Lazy loading will be implemented when route is accessed\n // For now, we'll store the module for later loading\n this.logger.debug(\n `Registered lazy route: ${route.method} ${fullPath}`,\n 'ModuleDiscovery'\n );\n });\n }\n });\n\n this.logger.info(`Registered ${modules.length} modules for lazy loading`, 'ModuleDiscovery');\n }\n\n // Load modules conditionally based on environment or configuration\n private async loadConditionalModules(modules: ModuleConfig[]): Promise<void> {\n for (const module of modules) {\n const shouldLoad = this.shouldLoadModule(module);\n\n if (shouldLoad) {\n await this.loadModule(module);\n } else {\n this.logger.debug(`Skipping module ${module.name} due to conditions`, 'ModuleDiscovery');\n }\n }\n }\n\n // Determine if a module should be loaded based on conditions\n private shouldLoadModule(module: ModuleConfig): boolean {\n const moduleConfig = module.config as any;\n\n // Check environment conditions\n if (moduleConfig?.conditions?.environment) {\n const requiredEnv = moduleConfig.conditions.environment;\n const currentEnv = process.env.NODE_ENV || 'development';\n\n if (Array.isArray(requiredEnv)) {\n if (!requiredEnv.includes(currentEnv)) {\n return false;\n }\n } else if (requiredEnv !== currentEnv) {\n return false;\n }\n }\n\n // Check feature flags\n if (moduleConfig?.conditions?.features) {\n const requiredFeatures = moduleConfig.conditions.features;\n\n for (const feature of requiredFeatures) {\n if (!process.env[`FEATURE_${feature.toUpperCase()}`]) {\n return false;\n }\n }\n }\n\n // Check custom conditions\n if (moduleConfig?.conditions?.custom) {\n const customCondition = moduleConfig.conditions.custom;\n\n if (typeof customCondition === 'function') {\n return customCondition();\n }\n }\n\n return true;\n }\n\n // Handle module changes during development\n private async handleModuleChanges(modules: ModuleConfig[]): Promise<void> {\n this.logger.info('Module changes detected, reloading...', 'ModuleDiscovery');\n\n // Unload existing modules (if supported)\n // For now, just log the change\n void this.eventBus.emit('modules:changed', {\n modules: modules.map(m => ({ name: m.name, version: m.version })),\n timestamp: new Date(),\n });\n }\n\n // Legacy method for backward compatibility\n private autoDiscoverModules(modulesPath: string) {\n // Redirect to new system (legacy sync shim over the async discovery path).\n void this.initializeAutoDiscovery({\n autoDiscover: {\n enabled: true,\n paths: [modulesPath],\n },\n }).catch(err => this.logger.error(`Auto-discovery failed: ${String(err)}`, 'ModuleDiscovery'));\n }\n\n private async importModule(modulePath: string): Promise<ModuleConfig> {\n // Convert file path to proper file URL for Windows compatibility\n const importURL = filePathToImportURL(modulePath);\n const module = await import(importURL);\n return module.default || module;\n }\n\n /**\n * Node.js Clustering Implementation\n * This clustering algorithm is based on published research and Node.js best practices.\n *\n * IPC (Inter-Process Communication) Considerations:\n * - Excessive workers create IPC bottlenecks (Source: BetterStack Node.js Guide)\n * - Round-robin scheduling provides better load distribution (Node.js Documentation)\n * - Message passing overhead increases significantly with worker count\n *\n * Memory Management:\n * - ~2GB per worker prevents memory pressure and GC overhead\n * - Conservative heap limits reduce memory fragmentation\n *\n * References:\n * - Node.js Cluster Documentation: https://nodejs.org/api/cluster.html\n * - BetterStack Node.js Clustering: https://betterstack.com/community/guides/scaling-nodejs/node-clustering/\n */\n private clusterWorkers = new Map<number, any>();\n\n private threadCluster: ThreadClusterPrimary | undefined = undefined;\n\n // Entry point for performance.clustering: decides whether THIS instance is\n // a worker (thread or process) or the primary, and which transport the\n // primary uses. Config keys are unchanged; the transport is automatic.\n private startWithClustering(port: number, host?: string, callback?: () => void): void {\n const { count: workerCount, detail } = computeWorkerCount(this.config.performance?.clustering);\n const tinfo = threadWorkerInfo();\n if (tinfo) {\n this.startClusterWorker({ kind: 'thread', info: tinfo }, port, host);\n return;\n }\n if (nodeCluster().isWorker) {\n this.startClusterWorker({ kind: 'process' }, port, host);\n return;\n }\n this.logger.info(detail, 'Cluster');\n const engineKind = this.engine;\n const transport = resolveClusterTransport({\n platform: process.platform,\n isMainThread: wt().isMainThread,\n argv1: process.argv[1],\n engineServer: engineKind.server,\n enginePackage: engineKind.enginePackage,\n workerThreadsCapable: loadNativeEngine()?.capabilities?.workerThreads === true,\n });\n if (transport.kind === 'threads') {\n this.startThreadPrimary(transport.entry, workerCount, port, host, callback);\n return;\n }\n this.logger.info(\n `Clustering: ${workerCount} worker processes (node:cluster; ${transport.reason})`,\n 'Cluster'\n );\n this.startProcessPrimary(workerCount, port, host, callback);\n }\n\n // Services that must run exactly ONCE per cluster, in the primary: the job\n // scheduler (leader election already treats the main thread of a\n // non-cluster-worker process as a participant) and the gRPC server (its own\n // port). GraphQL registers HTTP/WS routes, so it initialises in every\n // worker instead. Before 1.9.0 none of these started under clustering.\n private startPrimaryServices(): void {\n this.startJobScheduler().catch(err => {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n });\n if (this.grpcManager && !this.grpcStarted) {\n this.startGrpc().catch(error => {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n });\n }\n }\n\n private startThreadPrimary(\n entry: string,\n workerCount: number,\n port: number,\n host: string | undefined,\n callback?: () => void\n ): void {\n // The libuv threadpool is process-wide and sized once at first use;\n // the process path set this per worker process. Only if the operator\n // did not choose a size.\n if (!process.env.UV_THREADPOOL_SIZE) process.env.UV_THREADPOOL_SIZE = '64';\n // Same young-generation bound the process path applies through execArgv\n // (see YOUNG_GEN_MB_FOR_SEMI_SPACE_4), unless the operator tuned GC.\n const resourceLimits = isUserTunedYoungGen()\n ? undefined\n : { maxYoungGenerationSizeMb: YOUNG_GEN_MB_FOR_SEMI_SPACE_4 };\n\n const engineKind = this.engine;\n this.logger.info(\n `Clustering: ${workerCount} worker threads (worker_threads + SO_REUSEPORT, ` +\n `${engineKind.enginePackage}${engineKind.engineVersion ? ` v${engineKind.engineVersion}` : ''})`,\n 'Cluster'\n );\n\n let fellBack = false;\n const fallBackToProcesses = (why: string) => {\n if (fellBack) return;\n fellBack = true;\n this.logger.warn(\n `Worker threads unavailable (${why}); falling back to worker processes`,\n 'Cluster'\n );\n const primary = this.threadCluster;\n this.threadCluster = undefined;\n void primary?.shutdown(1000).finally(() => {\n this.startProcessPrimary(workerCount, port, host, callback);\n });\n };\n\n const primary = new ThreadClusterPrimary({\n entry,\n argv: process.argv.slice(2),\n workerCount,\n logger: this.logger,\n ...(resourceLimits ? { resourceLimits } : {}),\n onReady: () => {\n this.startPrimaryServices();\n if (callback) callback();\n },\n onFatal: (error, kind) => {\n if (kind === 'bind') {\n // Processes would fail identically: surface it like the single-process\n // path does (Node's server convention; rethrows without a listener).\n this.emit('error', error);\n return;\n }\n fallBackToProcesses(error.message);\n },\n });\n this.threadCluster = primary;\n try {\n primary.start();\n } catch (error) {\n fallBackToProcesses(error instanceof Error ? error.message : String(error));\n return;\n }\n\n // Graceful shutdown: drain every worker thread (each closes its server),\n // then the primary's own services; a second signal exits at once.\n let shuttingDown = false;\n const gracefulShutdown = (code: number) => {\n if (shuttingDown) {\n process.exit(code);\n return;\n }\n shuttingDown = true;\n this.logger.info('Gracefully shutting down cluster...', 'Cluster');\n this.close()\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n };\n process.on('SIGINT', () => gracefulShutdown(0));\n process.on('SIGTERM', () => gracefulShutdown(0));\n }\n\n private startProcessPrimary(\n workerCount: number,\n port: number,\n host: string | undefined,\n callback?: () => void\n ): void {\n void port;\n void host;\n this.logger.info(`Starting ${workerCount} workers`, 'Cluster');\n\n // Optimize cluster scheduling for high concurrency\n // Round-robin is the default on all platforms except Windows (Node.js docs)\n // Provides better load distribution than shared socket approach\n nodeCluster().schedulingPolicy = nodeCluster().SCHED_RR;\n\n // Workers inherit the primary's execArgv; additionally bound each\n // worker's V8 young generation unless the user tuned it themselves.\n // On big machines V8 sizes the nursery from total RAM and grows it\n // under sustained load (~10-34 MB extra RSS per process, measured on a\n // 64 GB box) - and in cluster mode that cost multiplies by the worker\n // count. A/B-benched 2026-08-01: identical throughput at 4 MB semi-space\n // in both the realistic profile (~92k vs ~90k req/s) and the pipelined\n // x10 microbenchmark (~560k both ways), while sustained-load RSS drops\n // ~30 MB per worker (115 -> 81 MB on the 25-route POST soak).\n const userTunedGC = isUserTunedYoungGen();\n\n // Set cluster settings for better performance\n nodeCluster().setupMaster({\n exec: process.argv[1] || process.execPath,\n args: process.argv.slice(2),\n silent: false,\n ...(userTunedGC ? {} : { execArgv: [...process.execArgv, '--max-semi-space-size=4'] }),\n });\n\n // IPC Optimization: Reduce communication overhead between master and workers\n // Research shows excessive IPC can create bottlenecks in clustered applications\n // (Source: BetterStack - Node.js Clustering Guide)\n process.env.NODE_CLUSTER_SCHED_POLICY = 'rr'; // Ensure round-robin\n process.env.NODE_DISABLE_COLORS = '1'; // Reduce IPC message size by disabling color codes\n\n // Graceful shutdown: SIGTERM every worker (each stops accepting, drains\n // its in-flight responses, then exits), wait for their exits up to a\n // bounded deadline, and only then exit. Exiting right after the kill\n // used to close the cluster IPC channel, and a node:cluster worker whose\n // primary disappears exits immediately - cutting the very responses the\n // worker was draining. A second signal while draining exits at once.\n let shuttingDown = false;\n const gracefulShutdown = () => {\n if (shuttingDown) process.exit(0);\n shuttingDown = true;\n this.logger.info('Gracefully shutting down cluster...', 'Cluster');\n\n if (this.clusterWorkers.size === 0) {\n nodeCluster().removeAllListeners();\n process.exit(0);\n }\n const pending = new Set<number>(this.clusterWorkers.keys());\n const timer = setTimeout(() => {\n this.logger.warn(\n `Shutdown deadline reached; terminating ${pending.size} worker process(es)`,\n 'Cluster'\n );\n for (const pid of pending) this.clusterWorkers.get(pid)?.kill('SIGKILL');\n finish();\n }, 3000);\n const finish = () => {\n clearTimeout(timer);\n nodeCluster().removeAllListeners();\n process.exit(0);\n };\n for (const [pid, worker] of this.clusterWorkers) {\n worker.removeAllListeners(); // no restart on these exits\n worker.once('exit', () => {\n pending.delete(pid);\n if (pending.size === 0) finish();\n });\n worker.kill('SIGTERM');\n }\n };\n\n // Handle process signals for graceful shutdown\n process.on('SIGINT', gracefulShutdown);\n process.on('SIGTERM', gracefulShutdown);\n\n // Fork workers with basic tracking\n for (let i = 0; i < workerCount; i++) {\n const worker = nodeCluster().fork();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.clusterWorkers.set(worker.process.pid!, worker);\n this.logger.info(`Worker ${worker.process.pid} started`, 'Cluster');\n\n // Handle individual worker messages\n worker.on('message', this.handleWorkerMessage.bind(this));\n }\n\n // Primary-only services start once the first worker is serving.\n let servicesStarted = false;\n nodeCluster().on('listening', () => {\n if (servicesStarted) return;\n servicesStarted = true;\n this.startPrimaryServices();\n });\n\n // Simple worker exit handling\n nodeCluster().on('exit', (worker: any, code: number, signal: string) => {\n const pid = worker.process.pid;\n this.clusterWorkers.delete(pid);\n\n if (code !== 0 && !worker.exitedAfterDisconnect) {\n this.logger.warn(\n `Worker ${pid} died unexpectedly (${signal || code}). Restarting...`,\n 'Cluster'\n );\n\n // Simple restart\n const newWorker = nodeCluster().fork();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.clusterWorkers.set(newWorker.process.pid!, newWorker);\n this.logger.info(`Worker ${newWorker.process.pid} restarted`, 'Cluster');\n }\n });\n\n // Master process callback\n if (callback) callback();\n }\n\n // One worker, either a worker_threads thread or a node:cluster process:\n // boot the app exactly like the single-process path (auto-discovery,\n // file-based routes, WebSocket registrations, GraphQL) and listen with\n // SO_REUSEPORT. Signals/exit are the differences: a thread gets 'shutdown'\n // from the primary over parentPort and never calls process.exit().\n private startClusterWorker(\n mode: { kind: 'thread'; info: ThreadWorkerInfo } | { kind: 'process' },\n port: number,\n host?: string\n ): void {\n const label =\n mode.kind === 'thread' ? `Worker thread ${wt().threadId}` : `Worker ${process.pid}`;\n const workerRef = mode.kind === 'thread' ? wt().threadId : process.pid;\n this.logger.info(`${label} initializing`, 'Worker');\n\n if (mode.kind === 'process') {\n // Worker-specific optimizations for high concurrency (a thread shares\n // the primary's pool, sized before it was spawned)\n process.env.UV_THREADPOOL_SIZE = '64';\n }\n\n // Reduce logging contention in workers (major bottleneck)\n // Multiple workers writing to same log files creates I/O contention\n // ONLY reduce log level if user didn't explicitly set one\n if (!this.userSetLogger) {\n // Workers log less frequently to reduce I/O contention (only if not explicitly configured)\n applyLoggingConfiguration(undefined, { level: 'warn' }); // Only warnings and errors\n }\n\n // Optimize garbage collection for workers\n // eslint-disable-next-line no-undef\n if ((global as any).gc) {\n setInterval(() => {\n // eslint-disable-next-line no-undef\n if ((global as any).gc) (global as any).gc();\n }, 60000); // GC every 60 seconds (less frequent)\n }\n\n let tcw: ThreadClusterWorker | null = null;\n if (mode.kind === 'thread') {\n tcw = new ThreadClusterWorker(this.logger);\n // 'shutdown' from the primary: drain and close; the thread then exits\n // on its own once the engine's handles are gone.\n tcw.onShutdown(async () => {\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n await this.close();\n });\n } else {\n // Graceful shutdown for worker\n const workerShutdown = () => {\n this.logger.info(`${label} shutting down gracefully...`, 'Worker');\n\n // Clean up event listeners\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n\n // Close server gracefully\n if (this.coreFramework) {\n const server = (this.coreFramework as any).server;\n if (server) {\n server.close(() => {\n process.exit(0);\n });\n }\n }\n };\n\n // Handle worker shutdown signals\n process.on('SIGTERM', workerShutdown);\n process.on('SIGINT', workerShutdown);\n }\n\n const fatal = (code: string, message: string) => {\n this.logger.error(`${label} ${message}`, 'Worker');\n if (tcw) {\n tcw.fatal(code, message);\n void this.close().finally(() => tcw?.close());\n } else {\n process.exit(1);\n }\n };\n\n // Continue with normal server startup for this worker\n void this.eventBus.emit('server:starting', {\n port,\n runtime: this.runtimeType,\n worker: workerRef,\n });\n\n // Add documentation middleware first (if enabled)\n try {\n const docsMiddleware = this.documentation.getDocsMiddleware();\n this.coreFramework.addMiddleware(docsMiddleware);\n } catch {\n // Documentation not enabled, that's fine\n }\n\n // Attach the unified router (handles both chainable and direct routes)\n this.attachUnifiedRouter();\n\n // Register legacy direct routes with the HTTP server (for backward compatibility)\n if (this.routes.length > 0) {\n this.registerDirectRoutes();\n }\n\n const workerCallback = () => {\n const displayHost = host || 'localhost';\n this.logger.info(`${label} ready on ${displayHost}:${port}`, 'Worker');\n void this.eventBus.emit('server:started', {\n port,\n runtime: this.runtimeType,\n worker: workerRef,\n engine: this.engine,\n });\n // GraphQL registers HTTP/WS routes on this app: every worker.\n this.ensureGraphQLInitialized().catch(error => {\n this.logger.error(`Failed to initialize GraphQL: ${error}`, 'GraphQL');\n });\n tcw?.ready(port);\n };\n\n const startWorkerListening = () => {\n if (host) {\n this.coreFramework.listen(port, host, workerCallback);\n } else {\n this.coreFramework.listen(port, workerCallback);\n }\n };\n // Same init as the single-process path: auto-discovery, file-based\n // routes, queued WebSocket registrations - before 1.9.0 workers skipped\n // discovery/route loading entirely.\n Promise.all([\n this.ensureAutoDiscoveryComplete().then(() => this.ensureRoutesLoaded()),\n this.processQueuedWebSocketRegistrations(),\n ])\n .then(startWorkerListening)\n .catch(error => {\n const message = error instanceof Error ? error.message : String(error);\n const code = (error as any)?.code;\n // listen() itself failed (EADDRINUSE etc.): retrying is guaranteed to\n // fail again and would surface as an unhandled rejection crash-loop.\n // Report fatally so the primary sees a clean death.\n if (\n code === 'EADDRINUSE' ||\n code === 'EACCES' ||\n /EADDRINUSE|failed to bind/i.test(message)\n ) {\n fatal(\n code === 'EACCES' ? 'EACCES' : 'EADDRINUSE',\n `could not bind port ${port}: ${message}`\n );\n return;\n }\n this.logger.error('Initialization failed in worker', 'Worker', { error: message });\n // For WebSocket failures with queued registrations, error will propagate\n if (\n error instanceof Error &&\n error.message.includes('WebSocket features require a WebSocket adapter')\n ) {\n throw error;\n }\n // Init failed but the HTTP server can still serve: start anyway, and\n // surface (not swallow) a listen failure from this path.\n try {\n startWorkerListening();\n } catch (listenError) {\n const lm = listenError instanceof Error ? listenError.message : String(listenError);\n fatal(\n (listenError as any)?.code === 'EACCES' ? 'EACCES' : 'EADDRINUSE',\n `failed to start: ${lm}`\n );\n }\n });\n }\n\n // Simple worker message handler\n private handleWorkerMessage(message: any): void {\n // Handle inter-worker communication if needed\n if (message.type === 'health-check') {\n // Worker health check response\n return;\n }\n\n // Log other worker messages\n this.logger.debug(`Worker message: ${JSON.stringify(message)}`, 'Cluster');\n }\n\n /**\n * Gracefully close the application and clean up resources\n * This should be called in tests and during shutdown\n */\n private shutdownHandlersRegistered = false;\n private isShuttingDown = false;\n // Per-instance opt-in uncaught-error listeners (removed by close()).\n private processListeners: Array<[string, (...args: any[]) => void]> = [];\n\n // Graceful shutdown is driven by ONE process-level SIGINT/SIGTERM handler\n // shared across every Moro instance (installed once), so creating many apps\n // never accumulates process listeners. Instances register here on listen()\n // and deregister on close().\n private static activeInstances = new Set<Moro>();\n private static globalSignalsInstalled = false;\n private static globalShuttingDown = false;\n\n private static installGlobalShutdownSignals(): void {\n if (Moro.globalSignalsInstalled) return;\n Moro.globalSignalsInstalled = true;\n\n const handle = (signal: string, code: number) => {\n // A second signal while already draining forces an immediate exit, so a\n // stuck shutdown can never make the process unkillable via Ctrl-C.\n if (Moro.globalShuttingDown) {\n process.exit(code);\n return;\n }\n Moro.globalShuttingDown = true;\n const instances = Array.from(Moro.activeInstances);\n instances[0]?.logger.info(`Received ${signal}, shutting down gracefully...`, 'Server');\n Promise.allSettled(instances.map(inst => inst.close()))\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n };\n\n process.on('SIGINT', () => handle('SIGINT', 0));\n process.on('SIGTERM', () => handle('SIGTERM', 0));\n }\n\n /**\n * Enable graceful shutdown for this instance. SIGINT/SIGTERM (Ctrl-C) drain\n * in-flight work via close() by default; a second signal force-exits. Opt out\n * with `server.gracefulShutdown: false` (e.g. when the host app owns signals).\n * Uncaught-error draining is separate and opt-in (`server.handleUncaught`).\n */\n private registerProcessShutdownHandlers(): void {\n if (this.shutdownHandlersRegistered) return;\n const serverCfg = this.config.server as any;\n if (serverCfg?.gracefulShutdown === false) return; // default ON; opt out here\n this.shutdownHandlersRegistered = true;\n\n Moro.activeInstances.add(this);\n Moro.installGlobalShutdownSignals();\n\n // Opt-in uncaught-error draining (per instance, removed on close()).\n if (serverCfg?.handleUncaught === true) {\n const add = (event: string, handler: (...args: any[]) => void) => {\n process.on(event as any, handler);\n this.processListeners.push([event, handler]);\n };\n add('unhandledRejection', reason => {\n this.logger.error(`Unhandled promise rejection: ${String(reason)}`, 'Server');\n this.drainAndExit(1);\n });\n add('uncaughtException', err => {\n this.logger.error(\n `Uncaught exception: ${err instanceof Error ? err.stack || err.message : String(err)}`,\n 'Server'\n );\n this.drainAndExit(1);\n });\n }\n }\n\n private drainAndExit(code: number): void {\n if (this.isShuttingDown) {\n process.exit(code);\n return;\n }\n this.isShuttingDown = true;\n this.close()\n .then(() => process.exit(code))\n .catch(() => process.exit(1));\n }\n\n /** Deregister this instance from process shutdown handling (called by close()). */\n private removeProcessShutdownHandlers(): void {\n Moro.activeInstances.delete(this);\n for (const [event, handler] of this.processListeners) {\n process.removeListener(event as any, handler);\n }\n this.processListeners = [];\n this.shutdownHandlersRegistered = false;\n }\n\n async close(): Promise<void> {\n this.logger.debug('Closing Moro application...');\n\n // Detach our process signal listeners so repeated create/close cycles\n // (tests, or a host that spins up many apps) don't leak process listeners.\n this.removeProcessShutdownHandlers();\n\n // Run user-registered onClose hooks first, while subsystems are still alive.\n // Failures in one hook don't prevent subsequent hooks or Moro's own teardown.\n if (this.closeHooks.length > 0) {\n for (const hook of this.closeHooks) {\n try {\n await hook();\n } catch (err) {\n this.logger.error(`onClose hook failed: ${String(err)}`);\n }\n }\n }\n\n // Cluster worker threads first: each drains its server via its own\n // close(); the primary's services below stop after the traffic did.\n if (this.threadCluster) {\n const primary = this.threadCluster;\n this.threadCluster = undefined;\n try {\n await primary.shutdown();\n } catch (err) {\n this.logger.error(`Error shutting down cluster worker threads: ${String(err)}`);\n }\n }\n\n // Shutdown worker threads first (fastest)\n try {\n this.logger.info('Shutting down worker threads...');\n await this.workerFacade.shutdown();\n } catch {\n // Workers might not be initialized or available\n this.logger.debug('Worker threads not available for shutdown');\n }\n\n // Shutdown job scheduler\n if (this.jobScheduler) {\n try {\n this.logger.info('Shutting down job scheduler...');\n await this.jobScheduler.shutdown();\n this.jobsStarted = false;\n } catch (err) {\n this.logger.error(`Error shutting down job scheduler: ${String(err)}`);\n }\n }\n\n // Shutdown gRPC server\n if (this.grpcManager && this.grpcStarted) {\n try {\n this.logger.info('Shutting down gRPC server...');\n await this.stopGrpc();\n } catch (err) {\n this.logger.error(`Error shutting down gRPC server: ${String(err)}`);\n }\n }\n\n // Cleanup GraphQL adapter resources\n if (this.graphqlCore) {\n try {\n await this.graphqlCore.cleanup();\n } catch (err) {\n this.logger.error(`Error cleaning up GraphQL: ${String(err)}`);\n }\n }\n\n // Flush logger buffer before shutdown\n try {\n // Use flushBuffer for immediate synchronous flush\n this.logger.flushBuffer();\n } catch {\n // Ignore flush errors during shutdown\n }\n\n // Close the core framework with timeout\n if (this.coreFramework && (this.coreFramework as any).httpServer) {\n try {\n const httpServer = (this.coreFramework as any).httpServer;\n const server = httpServer.getServer?.() || httpServer.getApp?.();\n\n // Only wait for close if the server is actually listening\n const isListening = server?.listening || server?.address?.() !== null;\n\n if (isListening) {\n // Stop accepting new connections and let in-flight requests finish,\n // but don't hang on idle keep-alive / WebSocket connections: close\n // idle sockets right away, then force-close whatever remains at the\n // deadline so this promise reflects a real close instead of only the\n // timer firing. (closeIdle/closeAllConnections exist on the Node http\n // server; the uWS/engine backends ignore the optional calls.)\n server?.closeIdleConnections?.();\n this.coreFramework.stopTlsWatch();\n await Promise.race([\n new Promise<void>(resolve => {\n httpServer.close(() => {\n resolve();\n });\n }),\n new Promise<void>(resolve => {\n const timer = setTimeout(() => {\n try {\n server?.closeAllConnections?.();\n } catch {\n // best-effort force-close\n }\n resolve();\n }, 2000); // 2 second grace period\n timer.unref(); // Don't keep process alive\n }),\n ]);\n } else {\n // Server was never started, just skip close\n this.logger.debug('HTTP server was never started, skipping close');\n }\n } catch {\n // Force close if graceful close fails\n this.logger.warn('Force closing HTTP server due to timeout');\n }\n }\n\n // Clean up module discovery watchers\n if (this.moduleDiscovery && typeof this.moduleDiscovery.cleanup === 'function') {\n try {\n this.moduleDiscovery.cleanup();\n } catch {\n // Ignore cleanup errors\n }\n }\n\n // Shutdown queue manager\n if (this.queueManager) {\n try {\n await this.queueManager.shutdown();\n this.logger.debug('Queue system shutdown complete');\n } catch (error) {\n this.logger.warn(`Error shutting down queue system: ${error}`);\n }\n }\n // Clear queue state on close\n this.queueConfigs.clear();\n this.queueInitialized = false;\n this.queueInitPromise = undefined;\n this.queueManager = undefined;\n\n // Shutdown mail system\n if (this.mailManager) {\n try {\n await this.mailManager.close();\n this.logger.debug('Mail system shutdown complete');\n } catch (error) {\n this.logger.warn(`Error shutting down mail system: ${error}`);\n }\n }\n\n // Clean up event listeners\n try {\n this.eventBus.removeAllListeners();\n this.removeAllListeners();\n } catch {\n // Ignore cleanup errors\n }\n\n this.logger.debug('Moro application closed successfully');\n }\n\n // ========================================\n // Job Scheduling API\n // ========================================\n\n /**\n * Register a background job with cron or interval schedule\n * @param name - Job name (used for identification)\n * @param schedule - Cron expression, interval string ('5m', '1h'), or schedule object\n * @param handler - Job function to execute\n * @param options - Job configuration options\n * @returns Job ID for management\n *\n * @example\n * // Cron schedule\n * app.job('cleanup', '0 2 * * *', async () => {\n * await cleanupOldData();\n * });\n *\n * // Interval schedule\n * app.job('health-check', '5m', async (ctx) => {\n * console.log('Health check', ctx.executionId);\n * });\n *\n * // Advanced options\n * app.job('report', '@daily', generateReport, {\n * timeout: 60000,\n * maxRetries: 3,\n * onError: (ctx, error) => console.error('Job failed', error)\n * });\n */\n job(\n name: string,\n schedule: string | JobSchedule,\n handler: JobFunction,\n options: SimpleJobOptions = {}\n ): string {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled. Set config.jobs.enabled = true');\n }\n\n let jobSchedule: JobSchedule;\n\n // Parse schedule input\n if (typeof schedule === 'string') {\n // Check if it's a cron expression or interval\n if (schedule.match(/^(\\d+[smhd]|\\d+\\s*(seconds?|minutes?|hours?|days?))$/i)) {\n // Interval format\n jobSchedule = everyInterval(schedule);\n } else {\n // Cron format\n jobSchedule = cronSchedule(schedule, options.timezone);\n }\n } else {\n jobSchedule = schedule;\n }\n\n const jobOptions: Partial<JobOptions> = {\n name: options.name || name,\n ...(options.enabled !== undefined ? { enabled: options.enabled } : {}),\n ...(options.priority !== undefined ? { priority: options.priority } : {}),\n ...(options.timezone !== undefined ? { timezone: options.timezone } : {}),\n ...(options.maxConcurrent !== undefined ? { maxConcurrent: options.maxConcurrent } : {}),\n ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),\n ...(options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n ...(options.retryDelay !== undefined ? { retryDelay: options.retryDelay } : {}),\n ...(options.retryBackoff !== undefined ? { retryBackoff: options.retryBackoff } : {}),\n ...(options.enableCircuitBreaker !== undefined\n ? { enableCircuitBreaker: options.enableCircuitBreaker }\n : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n ...(options.onStart !== undefined ? { onStart: options.onStart } : {}),\n ...(options.onComplete !== undefined ? { onComplete: options.onComplete } : {}),\n ...(options.onError !== undefined ? { onError: options.onError } : {}),\n };\n\n const jobId = this.jobScheduler.registerJob(name, jobSchedule, handler, jobOptions);\n\n this.logger.info(`Job registered: ${name} (${jobId})`);\n\n return jobId;\n }\n\n /**\n * Enable or disable a registered job\n */\n setJobEnabled(jobId: string, enabled: boolean): boolean {\n if (!this.jobScheduler) {\n return false;\n }\n\n return this.jobScheduler.setJobEnabled(jobId, enabled);\n }\n\n /**\n * Manually trigger a job execution\n */\n async triggerJob(jobId: string, metadata?: Record<string, any>): Promise<any> {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled');\n }\n\n return this.jobScheduler.triggerJob(jobId, metadata);\n }\n\n /**\n * Unregister a job\n */\n unregisterJob(jobId: string): boolean {\n if (!this.jobScheduler) {\n throw new Error('Job scheduler is not enabled');\n }\n\n return this.jobScheduler.unregisterJob(jobId);\n }\n\n /**\n * Get job metrics\n */\n getJobMetrics(jobId: string): JobMetrics | null {\n if (!this.jobScheduler) {\n return null;\n }\n\n return this.jobScheduler.getJobMetrics(jobId);\n }\n\n /**\n * Get job health status\n */\n getJobHealth(jobId?: string): JobHealth | JobHealth[] {\n if (!this.jobHealthChecker) {\n if (jobId) {\n return {\n jobId,\n name: 'Unknown',\n status: 'unknown',\n enabled: false,\n consecutiveFailures: 0,\n message: 'Job scheduler not enabled',\n };\n }\n return [];\n }\n\n if (jobId) {\n return this.jobHealthChecker.checkJobHealth(jobId);\n }\n\n return this.jobHealthChecker.checkAllJobs();\n }\n\n /**\n * Get scheduler statistics\n */\n getJobStats(): SchedulerStats | null {\n if (!this.jobScheduler) {\n return null;\n }\n\n return this.jobScheduler.getStats();\n }\n\n /**\n * Get overall scheduler health\n */\n getSchedulerHealth() {\n if (!this.jobHealthChecker) {\n return {\n status: 'unknown' as const,\n message: 'Job scheduler not enabled',\n stats: null,\n jobs: [],\n unhealthyJobCount: 0,\n };\n }\n\n return this.jobHealthChecker.getSchedulerHealth();\n }\n\n /**\n * Start the job scheduler (called automatically on listen)\n */\n private async startJobScheduler(): Promise<void> {\n if (!this.jobScheduler || this.jobsStarted) {\n return;\n }\n\n try {\n await this.jobScheduler.start();\n this.jobsStarted = true;\n this.logger.info('Job scheduler started');\n } catch (err) {\n this.logger.error(`Failed to start job scheduler: ${String(err)}`);\n }\n }\n\n // ========================================\n // GraphQL API\n // ========================================\n\n /**\n * Configure GraphQL endpoint (synchronous, lazy initialization)\n *\n * @param options - GraphQL configuration options\n *\n * @example\n * ```ts\n * // Using type definitions and resolvers\n * app.graphqlInit({\n * typeDefs: `\n * type Query {\n * hello: String\n * users: [User]\n * }\n * type User {\n * id: ID!\n * name: String!\n * }\n * `,\n * resolvers: {\n * Query: {\n * hello: () => 'Hello World!',\n * users: () => [{ id: '1', name: 'Alice' }]\n * }\n * }\n * });\n *\n * // Using Pothos schema builder\n * import SchemaBuilder from '@pothos/core';\n *\n * const builder = new SchemaBuilder();\n * builder.queryType({\n * fields: (t) => ({\n * hello: t.string({ resolve: () => 'Hello World!' })\n * })\n * });\n *\n * app.graphqlInit({\n * pothosSchema: builder\n * });\n * ```\n */\n graphqlInit(options: GraphQLOptions): this {\n if (this.graphqlCore || this.graphqlInitPromise) {\n throw new Error('GraphQL has already been configured. Call graphqlInit() only once.');\n }\n\n // Check if graphql package is available\n if (!this.isGraphQLAvailable()) {\n throw new Error(\n 'GraphQL support requires the graphql package to be installed.\\n' +\n 'Install it with: npm install graphql\\n' +\n 'For TypeScript-first GraphQL, also consider: npm install @pothos/core\\n' +\n 'For performance boost: npm install graphql-jit'\n );\n }\n\n this.logger.info('Configuring GraphQL (will initialize on server start)', 'GraphQL', {\n path: options.path || '/graphql',\n jit: options.enableJIT !== false,\n playground: options.enablePlayground !== false,\n });\n\n // Store config and trigger initialization immediately\n this.graphqlConfig = options;\n this.graphqlInitPromise = this.initializeGraphQL(options);\n void this.eventBus.emit('graphql:configured', { options });\n\n return this;\n }\n\n /**\n * Lazy initialize GraphQL system\n */\n private async ensureGraphQLInitialized(): Promise<void> {\n if (this.graphqlCore || this.graphqlInitPromise) {\n await this.graphqlInitPromise;\n return;\n }\n\n if (!this.graphqlConfig) {\n return; // GraphQL not configured, skip\n }\n\n this.graphqlInitPromise = this.initializeGraphQL(this.graphqlConfig);\n await this.graphqlInitPromise;\n }\n\n /**\n * Initialize GraphQL system asynchronously\n */\n private async initializeGraphQL(options: GraphQLOptions): Promise<void> {\n try {\n // Lazy load GraphQL modules\n await this.loadGraphQLModules();\n\n // Create GraphQL core\n this.graphqlCore = new GraphQLCore(options);\n\n // Initialize GraphQL\n await this.graphqlCore.initialize();\n\n this.logger.info('GraphQL initialized successfully', 'GraphQL');\n\n // Setup subscriptions if enabled\n if (options.enableSubscriptions !== false && this.config.websocket.enabled) {\n this.setupGraphQLSubscriptions(options);\n }\n } catch (error) {\n this.logger.error('Failed to initialize GraphQL', 'GraphQL', { error });\n throw error;\n }\n }\n\n /**\n * Check if GraphQL package is available\n */\n private isGraphQLAvailable(): boolean {\n try {\n require.resolve('graphql');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Lazy load GraphQL modules\n */\n private async loadGraphQLModules(): Promise<void> {\n if (GraphQLCore) {\n return; // Already loaded\n }\n\n try {\n // GraphQL core now uses adapters with no static imports from 'graphql'\n const coreModule = await import('./core/graphql/core.js');\n GraphQLCore = coreModule.GraphQLCore;\n\n const subsModule = await import('./core/middleware/built-in/graphql/subscriptions.js');\n GraphQLSubscriptionManager = subsModule.GraphQLSubscriptionManager;\n setupGraphQLSubscriptions = subsModule.setupGraphQLSubscriptions;\n } catch (error) {\n this.logger.error('Failed to load GraphQL modules', 'GraphQL', { error });\n throw new Error('Failed to load GraphQL modules. Please ensure graphql is installed.');\n }\n }\n\n /**\n * Setup GraphQL subscriptions\n */\n private setupGraphQLSubscriptions(options: GraphQLOptions): void {\n const websocketAdapter = this.coreFramework.getWebSocketAdapter();\n\n if (!websocketAdapter) {\n this.logger.warn('GraphQL subscriptions require WebSocket to be enabled', 'GraphQL');\n return;\n }\n\n if (!this.graphqlCore) {\n return;\n }\n\n const schema = this.graphqlCore.getSchema();\n\n this.graphqlSubscriptionManager = setupGraphQLSubscriptions(websocketAdapter, schema, {\n path: options.path ? `${options.path}/subscriptions` : '/graphql/subscriptions',\n contextFactory: options.context,\n });\n\n this.logger.info('GraphQL subscriptions enabled', 'GraphQL', {\n path: options.path ? `${options.path}/subscriptions` : '/graphql/subscriptions',\n });\n }\n\n /**\n * Get GraphQL schema (if configured)\n */\n async getGraphQLSchema(): Promise<any | undefined> {\n await this.ensureGraphQLInitialized();\n return this.graphqlCore?.getSchema();\n }\n\n // ========================================\n // Worker Threads API\n // ========================================\n\n /**\n * Execute a task on worker threads (CPU-intensive operations)\n * @param task - Task to execute\n * @returns Promise resolving to task result\n *\n * @example\n * ```ts\n * // JWT verification (CPU-intensive)\n * const payload = await app.executeOnWorker({\n * id: 'jwt-verify-123',\n * type: 'jwt:verify',\n * data: { token, secret }\n * });\n *\n * // Heavy computation\n * const result = await app.executeOnWorker({\n * id: 'compute-456',\n * type: 'computation:heavy',\n * data: { iterations: 1000000 }\n * });\n * ```\n */\n async executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n return this.workerFacade.executeTask<T>(task);\n }\n\n /**\n * Get worker manager instance for advanced usage\n */\n async getWorkerManager() {\n await this.workerFacade.ensureInitialized?.(); // Trigger initialization if needed\n return this.workerFacade;\n }\n\n /**\n * Get worker thread statistics\n */\n async getWorkerStats() {\n return this.workerFacade.getStats();\n }\n\n /**\n * JWT operations using worker threads (prevents event loop blocking)\n */\n async getJwtWorker() {\n return this.workerFacade.getJwtWorker();\n }\n\n /**\n * Crypto operations using worker threads\n */\n async getCryptoWorker() {\n return this.workerFacade.getCryptoWorker();\n }\n\n /**\n * Heavy computation operations using worker threads\n */\n async getComputeWorker() {\n return this.workerFacade.getComputeWorker();\n }\n\n /**\n * Get GraphQL stats\n */\n async getGraphQLStats() {\n await this.ensureGraphQLInitialized();\n\n if (!this.graphqlCore) {\n return null;\n }\n\n return {\n ...this.graphqlCore.getStats(),\n subscriptions: this.graphqlSubscriptionManager?.getSubscriptionCount() || 0,\n };\n }\n\n // =====================\n // gRPC Methods\n // =====================\n\n /**\n * Configure gRPC server (synchronous, lazy initialization)\n *\n * @example\n * ```typescript\n * app.grpcInit({\n * port: 50051,\n * host: '0.0.0.0',\n * adapter: 'grpc-js',\n * enableHealthCheck: true,\n * enableReflection: true\n * });\n * ```\n */\n grpcInit(options: GrpcOptions = {}): this {\n if (this.grpcInitPromise) {\n this.logger.warn('gRPC already configured', 'GRPC');\n return this;\n }\n\n this.logger.info('Configuring gRPC (will initialize on server start)', 'GRPC');\n\n // Store config for lazy initialization\n this.grpcConfig = {\n port: 50051,\n host: '0.0.0.0',\n adapter: 'grpc-js',\n enableHealthCheck: true,\n enableReflection: false,\n ...options,\n };\n\n return this;\n }\n\n /**\n * Lazy initialize gRPC system\n */\n private async ensureGrpcInitialized(): Promise<void> {\n if (this.grpcManager || this.grpcInitPromise) {\n await this.grpcInitPromise;\n return;\n }\n\n if (!this.grpcConfig) {\n return; // gRPC not configured, skip\n }\n\n this.grpcInitPromise = (async () => {\n try {\n this.logger.info('Initializing gRPC system', 'GRPC');\n\n // Lazy load gRPC manager\n const { GrpcManager } = await import('./core/grpc/grpc-manager.js');\n\n // Create gRPC manager\n this.grpcManager = new GrpcManager(this.grpcConfig);\n\n // Initialize gRPC\n await this.grpcManager.initialize();\n\n this.logger.info('gRPC system initialized', 'GRPC');\n } catch (error) {\n this.logger.error(`Failed to initialize gRPC: ${error}`, 'GRPC');\n throw error;\n }\n })();\n\n await this.grpcInitPromise;\n }\n\n /**\n * Register a gRPC service from a proto file\n *\n * @example\n * ```typescript\n * app.grpcService('./proto/users.proto', 'UserService', {\n * getUser: async (call, callback) => {\n * const user = await db.users.findById(call.request.id);\n * callback(null, user);\n * },\n * listUsers: async (call) => {\n * for (const user of users) {\n * call.write(user);\n * }\n * call.end();\n * }\n * });\n * ```\n */\n async grpcService(\n protoPath: string,\n serviceName: string,\n implementation: ServiceImplementation,\n packageName?: string\n ): Promise<void> {\n if (!this.grpcConfig && !this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n // Lazy initialize gRPC if not already done\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n try {\n await this.grpcManager.registerService(protoPath, serviceName, implementation, packageName);\n\n this.logger.info(`gRPC service registered: ${serviceName}`, 'GRPC');\n } catch (error) {\n this.logger.error(`Failed to register gRPC service ${serviceName}: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Start gRPC server\n * Called automatically by listen() if gRPC is configured\n */\n async startGrpc(): Promise<void> {\n // Lazy initialize if needed\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n return;\n }\n\n if (this.grpcStarted) {\n this.logger.warn('gRPC server already started', 'GRPC');\n return;\n }\n\n try {\n await this.grpcManager.start();\n this.grpcStarted = true;\n\n const stats = this.grpcManager.getStats();\n if (stats) {\n this.logger.info('gRPC server started successfully', 'GRPC');\n }\n } catch (error) {\n this.logger.error(`Failed to start gRPC server: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Stop gRPC server gracefully\n */\n async stopGrpc(): Promise<void> {\n if (!this.grpcManager || !this.grpcStarted) {\n return;\n }\n\n try {\n await this.grpcManager.stop();\n this.grpcStarted = false;\n this.logger.info('gRPC server stopped', 'GRPC');\n } catch (error) {\n this.logger.error(`Error stopping gRPC server: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Create a gRPC client for calling remote services\n *\n * @example\n * ```typescript\n * const client = await app.createGrpcClient(\n * './proto/users.proto',\n * 'UserService',\n * 'localhost:50051'\n * );\n *\n * const user = await client.getUser({ id: '123' });\n * ```\n */\n async createGrpcClient(\n protoPath: string,\n serviceName: string,\n address: string,\n options?: Partial<GrpcClientOptions>\n ): Promise<GrpcClient> {\n if (!this.grpcConfig && !this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n // Lazy initialize gRPC if not already done\n await this.ensureGrpcInitialized();\n\n if (!this.grpcManager) {\n throw new Error(\n 'gRPC not initialized. Call app.grpcInit() first.\\n' +\n 'Example: app.grpcInit({ port: 50051 });'\n );\n }\n\n try {\n const client = await this.grpcManager.createClient(protoPath, serviceName, address, options);\n\n this.logger.info(`gRPC client created for ${serviceName} at ${address}`, 'GRPC');\n\n return client;\n } catch (error) {\n this.logger.error(`Failed to create gRPC client: ${error}`, 'GRPC');\n throw error;\n }\n }\n\n /**\n * Get gRPC statistics\n */\n getGrpcStats() {\n if (!this.grpcManager) {\n return null;\n }\n\n return this.grpcManager.getStats();\n }\n\n /**\n * Get list of registered gRPC services\n */\n getGrpcServices() {\n if (!this.grpcManager) {\n return [];\n }\n\n return this.grpcManager.getServices();\n }\n\n /**\n * Initialize queue system (synchronous for first queue, subsequent queues added immediately)\n *\n * @example\n * ```typescript\n * app.queueInit('emails', {\n * adapter: 'bull',\n * connection: {\n * host: 'localhost',\n * port: 6379\n * },\n * concurrency: 5\n * });\n * ```\n */\n queueInit(name: string, options: any): this {\n // Initialize queue manager on first call\n if (!this.queueInitialized && !this.queueInitPromise) {\n this.queueInitPromise = (async () => {\n try {\n this.logger.info('Initializing queue system', 'QUEUE');\n const { QueueManager } = await import('./core/queue/index.js');\n this.queueManager = new QueueManager(this.eventBus as any);\n this.queueInitialized = true;\n this.logger.info('Queue system initialized', 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to initialize queue system: ${error}`, 'QUEUE');\n throw error;\n }\n })();\n }\n\n // Store config to register after initialization\n this.queueConfigs.set(name, options);\n this.logger.debug(`Queue \"${name}\" configured`, 'QUEUE');\n\n // Register queue async (manager will be ready)\n if (this.queueInitPromise) {\n this.queueInitPromise\n .then(async () => {\n if (this.queueManager) {\n await this.queueManager.registerQueue(name, options);\n this.logger.info(`Queue \"${name}\" registered with ${options.adapter} adapter`, 'QUEUE');\n }\n })\n .catch(error => {\n this.logger.error(`Failed to register queue \"${name}\": ${error}`, 'QUEUE');\n });\n }\n\n return this;\n }\n\n /**\n * Ensure queue system is initialized\n */\n private async ensureQueueInitialized(): Promise<void> {\n if (this.queueInitPromise) {\n await this.queueInitPromise;\n }\n }\n\n /**\n * @deprecated Use queueInit() instead\n */\n async queue(name: string, options: any): Promise<void> {\n if (!this.queueInitialized) {\n try {\n this.logger.info('Initializing queue system', 'QUEUE');\n const { QueueManager } = await import('./core/queue/index.js');\n this.queueManager = new QueueManager(this.eventBus as any);\n this.queueInitialized = true;\n this.logger.info('Queue system initialized', 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to initialize queue system: ${error}`, 'QUEUE');\n throw error;\n }\n }\n\n try {\n await this.queueManager.registerQueue(name, options);\n this.logger.info(`Queue \"${name}\" registered with ${options.adapter} adapter`, 'QUEUE');\n } catch (error) {\n this.logger.error(`Failed to register queue \"${name}\": ${error}`, 'QUEUE');\n throw error;\n }\n }\n\n /**\n * Add a job to a queue\n *\n * @example\n * ```typescript\n * await app.addToQueue('emails', {\n * to: 'user@example.com',\n * subject: 'Welcome'\n * }, {\n * priority: 10,\n * delay: 5000\n * });\n * ```\n */\n async addToQueue<T = any>(queueName: string, data: T, options?: any): Promise<any> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queueInit('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.addToQueue(queueName, data, options);\n }\n\n /**\n * Add multiple jobs to a queue in bulk\n *\n * @example\n * ```typescript\n * await app.addBulkToQueue('emails', [\n * { data: { to: 'user1@example.com' }, options: { priority: 1 } },\n * { data: { to: 'user2@example.com' }, options: { priority: 2 } }\n * ]);\n * ```\n */\n async addBulkToQueue<T = any>(\n queueName: string,\n jobs: Array<{ data: T; options?: any }>\n ): Promise<any[]> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queue('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.addBulkToQueue(queueName, jobs);\n }\n\n /**\n * Register a processor for a queue\n *\n * @example\n * ```typescript\n * // Simple processor\n * app.processQueue('emails', async (job) => {\n * await sendEmail(job.data);\n * });\n *\n * // With concurrency\n * app.processQueue('images', 3, async (job) => {\n * await processImage(job.data);\n * });\n * ```\n */\n async processQueue<R = any>(\n queueName: string,\n concurrencyOrHandler: number | ((job: any) => Promise<R>),\n handler?: (job: any) => Promise<R>\n ): Promise<void> {\n // Ensure queue system is initialized\n await this.ensureQueueInitialized();\n\n if (!this.queueManager) {\n throw new Error(\n `Queue \"${queueName}\" not initialized. Call app.queueInit('${queueName}', options) first.`\n );\n }\n\n return await this.queueManager.processQueue(queueName, concurrencyOrHandler, handler);\n }\n\n /**\n * Get queue status\n */\n async getQueueStatus(queueName: string): Promise<any> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getQueueStatus(queueName);\n }\n\n /**\n * Get a specific job from a queue\n */\n async getJob(queueName: string, jobId: string): Promise<any> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getJob(queueName, jobId);\n }\n\n /**\n * Get jobs from a queue by status\n */\n async getJobs(\n queueName: string,\n status?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'paused',\n start: number = 0,\n end: number = -1\n ): Promise<any[]> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.getJobs(queueName, status, start, end);\n }\n\n /**\n * Remove a job from a queue\n */\n async removeJob(queueName: string, jobId: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.removeJob(queueName, jobId);\n }\n\n /**\n * Retry a failed job\n */\n async retryJob(queueName: string, jobId: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.retryJob(queueName, jobId);\n }\n\n /**\n * Pause a queue\n */\n async pauseQueue(queueName: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.pauseQueue(queueName);\n }\n\n /**\n * Resume a paused queue\n */\n async resumeQueue(queueName: string): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.resumeQueue(queueName);\n }\n\n /**\n * Clean old jobs from a queue\n */\n async cleanQueue(\n queueName: string,\n gracePeriod: number,\n status?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'paused'\n ): Promise<void> {\n if (!this.queueManager) {\n throw new Error(`Queue system not initialized.`);\n }\n\n return await this.queueManager.cleanQueue(queueName, gracePeriod, status);\n }\n\n /**\n * Get all registered queue names\n */\n getQueueNames(): string[] {\n // Return configured queues (includes both initialized and pending)\n const configuredQueues = Array.from(this.queueConfigs.keys());\n\n if (!this.queueManager) {\n return configuredQueues;\n }\n\n // Merge with manager's queues (in case some were added directly)\n const managerQueues = this.queueManager.getQueueNames();\n const allQueues = new Set([...configuredQueues, ...managerQueues]);\n return Array.from(allQueues);\n }\n\n /**\n * Check if a queue is registered\n */\n hasQueue(queueName: string): boolean {\n // Check if it's configured (includes both initialized and pending)\n if (this.queueConfigs.has(queueName)) {\n return true;\n }\n\n if (!this.queueManager) {\n return false;\n }\n\n return this.queueManager.hasQueue(queueName);\n }\n\n // =====================\n // Mail System Methods\n // =====================\n\n /**\n * Configure mail system (synchronous, lazy initialization)\n *\n * @example\n * ```typescript\n * // Using Nodemailer (SMTP) - chainable, no await needed!\n * app.mailInit({\n * adapter: 'nodemailer',\n * from: { name: 'My App', email: 'noreply@myapp.com' },\n * connection: {\n * host: 'smtp.gmail.com',\n * port: 587,\n * secure: false,\n * auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASSWORD }\n * },\n * templates: { path: './emails', engine: 'moro', cache: true }\n * });\n *\n * // Using SendGrid\n * app.mailInit({\n * adapter: 'sendgrid',\n * from: 'noreply@myapp.com',\n * connection: { apiKey: process.env.SENDGRID_API_KEY }\n * });\n * ```\n */\n mailInit(config: MailConfig): this {\n if (this.mailInitialized) {\n this.logger.warn('Mail system already configured', 'Mail');\n return this;\n }\n\n // Store config for lazy initialization\n this.mailConfig = config;\n this.logger.debug('Mail system configured (will initialize on first use)', 'Mail');\n void this.eventBus.emit('mail:configured', { config });\n\n return this;\n }\n\n /**\n * Lazy initialize mail system on first use\n */\n private async ensureMailInitialized(): Promise<void> {\n if (this.mailInitialized) {\n return;\n }\n\n if (!this.mailConfig) {\n throw new Error(\n 'Mail system not configured. Call app.mailInit(config) first.\\n' +\n \"Example: app.mailInit({ adapter: 'console', from: 'noreply@myapp.com' });\"\n );\n }\n\n try {\n this.logger.info('Initializing mail system', 'Mail');\n\n const { MailManager } = await import('./core/mail/index.js');\n this.mailManager = new MailManager(this.mailConfig);\n\n await this.mailManager.initialize();\n\n if (this.mailConfig.queue?.enabled && this.queueManager) {\n this.mailManager.setQueueManager(this.queueManager);\n\n const queueName = this.mailConfig.queue.name || 'emails';\n\n if (!this.queueManager.hasQueue(queueName)) {\n this.queueConfigs.set(queueName, {\n adapter: 'memory',\n concurrency: this.mailConfig.queue.attempts || 3,\n });\n await this.ensureQueueInitialized();\n\n await this.processQueue(queueName, async (job: any) => {\n if (this.mailManager) {\n // deliver() bypasses the queue check; send() would re-enqueue the\n // job forever and never actually transmit the email.\n return await this.mailManager.deliver(job.data);\n }\n throw new Error('Mail manager not initialized');\n });\n }\n\n this.logger.info(`Mail queue \"${queueName}\" configured`, 'Mail');\n }\n\n this.mailInitialized = true;\n this.logger.info('Mail system initialized successfully', 'Mail');\n } catch (error) {\n this.logger.error(`Failed to initialize mail system: ${error}`, 'Mail');\n throw error;\n }\n }\n\n /**\n * Send an email\n *\n * @example\n * ```typescript\n * // Simple email\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Welcome',\n * text: 'Welcome to our app!'\n * });\n *\n * // With template\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Password Reset',\n * template: 'password-reset',\n * data: { name: 'John', resetUrl: 'https://myapp.com/reset/token123' }\n * });\n *\n * // With attachments\n * await app.sendMail({\n * to: 'user@example.com',\n * subject: 'Invoice',\n * template: 'invoice',\n * data: { invoice },\n * attachments: [{ filename: 'invoice.pdf', content: pdfBuffer }]\n * });\n * ```\n */\n async sendMail(options: MailOptions): Promise<MailResult> {\n // Lazy initialize on first use\n await this.ensureMailInitialized();\n\n void this.eventBus.emit('mail:sending', { options });\n\n try {\n const result = await this.mailManager.send(options);\n\n if (result.success) {\n void this.eventBus.emit('mail:sent', { result, options });\n } else {\n void this.eventBus.emit('mail:failed', { error: new Error(result.error), options });\n }\n\n return result;\n } catch (error) {\n void this.eventBus.emit('mail:failed', { error, options });\n throw error;\n }\n }\n\n /**\n * Send multiple emails in bulk\n *\n * @example\n * ```typescript\n * await app.sendBulkMail([\n * { to: 'user1@example.com', subject: 'Hello', text: 'Hi!' },\n * { to: 'user2@example.com', subject: 'Hello', text: 'Hi!' }\n * ]);\n * ```\n */\n async sendBulkMail(options: MailOptions[]): Promise<MailResult[]> {\n // Lazy initialize on first use\n await this.ensureMailInitialized();\n\n return await this.mailManager.sendBulk(options);\n }\n\n /**\n * Verify mail adapter connection\n */\n async verifyMail(): Promise<boolean> {\n // Lazy initialize on first use\n try {\n await this.ensureMailInitialized();\n return await this.mailManager.verify();\n } catch {\n return false;\n }\n }\n\n /**\n * Get mail template engine for advanced usage\n */\n getMailTemplateEngine(): any {\n if (!this.mailManager) {\n return undefined;\n }\n\n return this.mailManager.getTemplateEngine();\n }\n\n /**\n * Check if mail system is configured\n */\n hasMailSystem(): boolean {\n return !!this.mailConfig || this.mailInitialized;\n }\n}\n\nlet currentApp: Moro | null = null;\n\n/**\n * Get the current Moro application instance.\n *\n * Returns the app created by the most recent createApp() call.\n * Use this in standalone route files so they can register routes\n * without needing the app to be passed in.\n *\n * @example\n * // routes/health.routes.ts\n * import { getApp } from '@morojs/moro';\n * const app = getApp();\n *\n * app.get('/health', (req, res) => {\n * res.json({ status: 'healthy' });\n * });\n */\nexport function getApp(): Moro {\n if (!currentApp) {\n throw new Error('No app instance available. Call createApp() before getApp().');\n }\n return currentApp;\n}\n\n/**\n * Create and fully initialise a Moro application.\n *\n * Must be awaited — the async step loads moro.config.js/ts via dynamic\n * import() so ESM config files (projects with \"type\":\"module\") work correctly,\n * exactly the same way all other modules are loaded.\n *\n * @example\n * const app = await createApp({ server: { port: 3000 } });\n * app.listen();\n */\n/**\n * Apply LOG_LEVEL / MORO_LOG_LEVEL env var and options.logger to the global logger\n * before config loading runs, so config-system debug logs respect the user's level.\n */\nfunction applyEarlyLogLevel(options?: MoroOptions): void {\n const envLevel = process.env.LOG_LEVEL || process.env.MORO_LOG_LEVEL;\n if (envLevel) {\n applyLoggingConfiguration({ level: envLevel }, undefined);\n }\n if (options?.logger !== undefined) {\n applyLoggingConfiguration(undefined, options.logger);\n }\n}\n\nexport async function createApp(options?: MoroOptions): Promise<Moro> {\n applyEarlyLogLevel(options);\n const config = await initializeConfigAsync(options);\n const app = new Moro(options, config);\n currentApp = app;\n return app;\n}\n\n/**\n * Create a Node.js-targeted Moro application. Must be awaited.\n * @example const app = await createAppNode();\n */\nexport async function createAppNode(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'node' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create a Vercel Edge-targeted Moro application. Must be awaited.\n * @example const app = await createAppEdge();\n */\nexport async function createAppEdge(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'vercel-edge' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create an AWS Lambda-targeted Moro application. Must be awaited.\n * @example const app = await createAppLambda();\n */\nexport async function createAppLambda(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'aws-lambda' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n\n/**\n * Create a Cloudflare Workers-targeted Moro application. Must be awaited.\n * @example const app = await createAppWorker();\n */\nexport async function createAppWorker(options?: Omit<MoroOptions, 'runtime'>): Promise<Moro> {\n const mergedOptions = { ...options, runtime: { type: 'cloudflare-workers' as const } };\n applyEarlyLogLevel(mergedOptions);\n const config = await initializeConfigAsync(mergedOptions);\n return new Moro(mergedOptions, config);\n}\n"]}
|