@morojs/moro 1.8.3 → 1.8.4

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.
Files changed (87) hide show
  1. package/dist/core/config/config-sources.js.map +1 -1
  2. package/dist/core/framework.d.ts +11 -0
  3. package/dist/core/framework.js +107 -36
  4. package/dist/core/framework.js.map +1 -1
  5. package/dist/core/graphql/core.js.map +1 -1
  6. package/dist/core/grpc/types.js.map +1 -1
  7. package/dist/core/http/moro-engine-server.js.map +1 -1
  8. package/dist/core/mail/mail-adapter.js.map +1 -1
  9. package/dist/core/middleware/built-in/cloudwatch/index.d.ts +4 -0
  10. package/dist/core/middleware/built-in/cloudwatch/index.js +5 -0
  11. package/dist/core/middleware/built-in/cloudwatch/index.js.map +1 -0
  12. package/dist/core/middleware/built-in/cloudwatch/middleware.d.ts +31 -0
  13. package/dist/core/middleware/built-in/cloudwatch/middleware.js +52 -0
  14. package/dist/core/middleware/built-in/cloudwatch/middleware.js.map +1 -0
  15. package/dist/core/middleware/built-in/error-tracker/index.d.ts +3 -1
  16. package/dist/core/middleware/built-in/error-tracker/index.js +3 -2
  17. package/dist/core/middleware/built-in/error-tracker/index.js.map +1 -1
  18. package/dist/core/middleware/built-in/error-tracker/middleware.d.ts +6 -3
  19. package/dist/core/middleware/built-in/error-tracker/middleware.js +18 -13
  20. package/dist/core/middleware/built-in/error-tracker/middleware.js.map +1 -1
  21. package/dist/core/middleware/built-in/index.d.ts +43 -7
  22. package/dist/core/middleware/built-in/index.js +37 -7
  23. package/dist/core/middleware/built-in/index.js.map +1 -1
  24. package/dist/core/middleware/built-in/performance-monitor/index.d.ts +3 -1
  25. package/dist/core/middleware/built-in/performance-monitor/index.js +3 -2
  26. package/dist/core/middleware/built-in/performance-monitor/index.js.map +1 -1
  27. package/dist/core/middleware/built-in/performance-monitor/middleware.d.ts +3 -3
  28. package/dist/core/middleware/built-in/performance-monitor/middleware.js +19 -17
  29. package/dist/core/middleware/built-in/performance-monitor/middleware.js.map +1 -1
  30. package/dist/core/middleware/built-in/prometheus/core.d.ts +27 -0
  31. package/dist/core/middleware/built-in/prometheus/core.js +0 -0
  32. package/dist/core/middleware/built-in/prometheus/core.js.map +1 -0
  33. package/dist/core/middleware/built-in/prometheus/index.d.ts +5 -0
  34. package/dist/core/middleware/built-in/prometheus/index.js +6 -0
  35. package/dist/core/middleware/built-in/prometheus/index.js.map +1 -0
  36. package/dist/core/middleware/built-in/prometheus/middleware.d.ts +15 -0
  37. package/dist/core/middleware/built-in/prometheus/middleware.js +30 -0
  38. package/dist/core/middleware/built-in/prometheus/middleware.js.map +1 -0
  39. package/dist/core/middleware/built-in/request-logger/index.d.ts +3 -1
  40. package/dist/core/middleware/built-in/request-logger/index.js +3 -2
  41. package/dist/core/middleware/built-in/request-logger/index.js.map +1 -1
  42. package/dist/core/middleware/built-in/request-logger/middleware.d.ts +4 -4
  43. package/dist/core/middleware/built-in/request-logger/middleware.js +14 -12
  44. package/dist/core/middleware/built-in/request-logger/middleware.js.map +1 -1
  45. package/dist/core/middleware/index.d.ts +1 -1
  46. package/dist/core/middleware/index.js +1 -1
  47. package/dist/core/middleware/index.js.map +1 -1
  48. package/dist/core/pooling/index.d.ts +3 -0
  49. package/dist/core/pooling/index.js +5 -0
  50. package/dist/core/pooling/index.js.map +1 -0
  51. package/dist/core/pooling/lru-cache.d.ts +32 -0
  52. package/dist/core/pooling/lru-cache.js +74 -0
  53. package/dist/core/pooling/lru-cache.js.map +1 -0
  54. package/dist/core/pooling/object-pool-manager.d.ts +3 -1
  55. package/dist/core/pooling/object-pool-manager.js +37 -140
  56. package/dist/core/pooling/object-pool-manager.js.map +1 -1
  57. package/dist/core/pooling/object-pool.d.ts +42 -0
  58. package/dist/core/pooling/object-pool.js +78 -0
  59. package/dist/core/pooling/object-pool.js.map +1 -0
  60. package/dist/core/routing/create-router.js.map +1 -1
  61. package/dist/core/routing/path-matcher.js +1 -43
  62. package/dist/core/routing/path-matcher.js.map +1 -1
  63. package/dist/core/utilities/hooks.d.ts +0 -1
  64. package/dist/core/utilities/hooks.js +0 -2
  65. package/dist/core/utilities/hooks.js.map +1 -1
  66. package/dist/core/utilities/index.d.ts +0 -1
  67. package/dist/core/utilities/index.js +0 -2
  68. package/dist/core/utilities/index.js.map +1 -1
  69. package/dist/core/workers/facade.d.ts +20 -4
  70. package/dist/core/workers/facade.js +15 -7
  71. package/dist/core/workers/facade.js.map +1 -1
  72. package/dist/core/workers/worker-manager.d.ts +12 -0
  73. package/dist/core/workers/worker-manager.js +27 -0
  74. package/dist/core/workers/worker-manager.js.map +1 -1
  75. package/dist/core/workers/worker.d.ts +17 -1
  76. package/dist/core/workers/worker.js +28 -26
  77. package/dist/core/workers/worker.js.map +1 -1
  78. package/dist/index.d.ts +39 -2
  79. package/dist/index.js +14 -2
  80. package/dist/index.js.map +1 -1
  81. package/dist/moro.js +25 -1
  82. package/dist/moro.js.map +1 -1
  83. package/dist/types/config.js.map +1 -1
  84. package/dist/types/core.d.ts +1 -0
  85. package/dist/types/core.js.map +1 -1
  86. package/dist/types/module.js.map +1 -1
  87. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"object-pool-manager.js","sourceRoot":"","sources":["../../../src/core/pooling/object-pool-manager.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,6EAA6E;AAE7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,MAAM,MAAM,GAAG,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;AAE1D;;GAEG;AACH,MAAM,UAAU;IACN,IAAI,GAAQ,EAAE,CAAC;IACN,OAAO,CAAU;IACjB,KAAK,CAAkC;IACvC,OAAO,CAAS;IACzB,YAAY,GAAG,CAAC,CAAC;IACjB,YAAY,GAAG,CAAC,CAAC;IACjB,WAAW,GAAG,CAAC,CAAC;IAExB,YAAY,OAAgB,EAAE,UAAkB,GAAG,EAAE,K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,CAAC,CAAC,CAAC,GAAG;YAC7D,oBAAoB,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG;YACnE,oBAAoB,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG;YACnE,WAAW,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK;SACtD,CAAC,CAAC;IACL,CAAC;;AAGH;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO,iBAAiB,CAAC,WAAW,EAAE,CAAC;AACzC,CAAC","sourcesContent":["// Unified Object Pool Manager\n// Consolidates object pooling from http-server, router, and other components\n\nimport { createFrameworkLogger } from '../logger/index.js';\nimport * as crypto from 'crypto';\nconst logger = createFrameworkLogger('ObjectPoolManager');\n\n/**\n * Generic object pool for reusable objects\n */\nclass ObjectPool<T> {\n private pool: T[] = [];\n private readonly factory: () => T;\n private readonly reset?: ((obj: T) => void) | undefined;\n private readonly maxSize: number;\n private acquireCount = 0;\n private releaseCount = 0;\n private createCount = 0;\n\n constructor(factory: () => T, maxSize: number = 100, reset?: (obj: T) => void) {\n this.factory = factory;\n this.maxSize = maxSize;\n this.reset = reset;\n }\n\n acquire(): T {\n this.acquireCount++;\n\n if (this.pool.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.pool.pop()!;\n }\n\n this.createCount++;\n return this.factory();\n }\n\n release(obj: T): void {\n if (this.pool.length >= this.maxSize) {\n return; // Pool is full, let it be garbage collected\n }\n\n this.releaseCount++;\n\n // Reset object if reset function provided\n if (this.reset) {\n this.reset(obj);\n }\n\n this.pool.push(obj);\n }\n\n get size(): number {\n return this.pool.length;\n }\n\n get stats() {\n return {\n poolSize: this.pool.length,\n maxSize: this.maxSize,\n acquireCount: this.acquireCount,\n releaseCount: this.releaseCount,\n createCount: this.createCount,\n utilization: this.maxSize > 0 ? this.pool.length / this.maxSize : 0,\n };\n }\n\n clear(): void {\n this.pool = [];\n }\n}\n\n/**\n * LRU Cache for route lookups\n */\nclass LRUCache<K, V> {\n private cache = new Map<K, V>();\n private readonly maxSize: number;\n private hits = 0;\n private misses = 0;\n\n constructor(maxSize: number = 500) {\n this.maxSize = maxSize;\n }\n\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n this.hits++;\n // Move to end (most recently used)\n this.cache.delete(key);\n this.cache.set(key, value);\n return value;\n }\n this.misses++;\n return undefined;\n }\n\n set(key: K, value: V): void {\n if (this.cache.has(key)) {\n this.cache.delete(key);\n }\n\n this.cache.set(key, value);\n\n // Evict oldest if over capacity\n if (this.cache.size > this.maxSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) {\n this.cache.delete(firstKey);\n }\n }\n }\n\n has(key: K): boolean {\n return this.cache.has(key);\n }\n\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n this.hits = 0;\n this.misses = 0;\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get stats() {\n const total = this.hits + this.misses;\n return {\n size: this.cache.size,\n maxSize: this.maxSize,\n hits: this.hits,\n misses: this.misses,\n hitRate: total > 0 ? this.hits / total : 0,\n };\n }\n}\n\n/**\n * ObjectPoolManager - Singleton for managing all object pools\n * Consolidates pools from:\n * - MoroHttpServer (paramObjectPool, bufferPool)\n * - Router (paramObjectPool)\n * - Various route caches\n */\nexport class ObjectPoolManager {\n private static instance: ObjectPoolManager | null = null;\n\n // Parameter object pool (for route params)\n private paramPool: ObjectPool<Record<string, string>>;\n\n // Header object pool (for parsed headers)\n private headerPool: ObjectPool<Record<string, string>>;\n\n // Query object pool (for parsed query strings)\n private queryPool: ObjectPool<Record<string, string>>;\n\n // Buffer pools by size\n private bufferPools: Map<number, ObjectPool<Buffer>>;\n private readonly bufferSizes = [64, 256, 1024, 4096, 16384];\n\n // Route lookup cache\n private routeCache: LRUCache<string, any>;\n\n // Response cache (for common responses - now includes full response metadata)\n private responseCache: LRUCache<\n string,\n { buffer: Buffer; headers: Record<string, string>; statusCode: number }\n >;\n\n // Performance monitoring\n private performanceStats = {\n poolHits: 0,\n poolMisses: 0,\n totalAcquisitions: 0,\n totalReleases: 0,\n lastAdjustment: 0,\n adjustmentInterval: 60000, // 1 minute\n };\n\n // Adaptive pool sizing\n private poolUsageHistory: Map<string, number[]> = new Map();\n private adaptiveMode = true;\n\n private constructor() {\n // Set initial last adjustment time to prevent immediate adjustment\n this.performanceStats.lastAdjustment = Date.now();\n\n // Initialize parameter object pool with adaptive sizing\n this.paramPool = new ObjectPool(\n () => ({}),\n 100, // Initial size\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize header object pool\n this.headerPool = new ObjectPool(\n () => ({}),\n 50, // Initial size - headers are less common to pool\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize query object pool\n this.queryPool = new ObjectPool(\n () => ({}),\n 100, // Initial size - queries are very common\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize buffer pools with enhanced sizing\n this.bufferPools = new Map();\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n this.bufferPools.set(\n size,\n new ObjectPool<Buffer>(() => Buffer.allocUnsafe(size), this.getOptimalPoolSize(size))\n );\n }\n\n // Initialize caches with enhanced statistics\n this.routeCache = new LRUCache(500);\n this.responseCache = new LRUCache(200); // Increased for full response caching\n\n // Pre-warm pools with optimal defaults\n this.preWarmPools();\n\n logger.debug(\n 'ObjectPoolManager initialized with enhanced performance features',\n 'Initialization'\n );\n }\n\n /**\n * Pre-warm pools with optimal sizes for better startup performance\n * Can be called with custom sizes to override defaults\n */\n preWarmPools(sizes?: {\n params?: number;\n query?: number;\n headers?: number;\n buffers?: Record<number, number>;\n }): void {\n // Aggressive pre-warming for common scenarios\n const paramSize = sizes?.params ?? 50; // More aggressive default\n const querySize = sizes?.query ?? 50;\n const headerSize = sizes?.headers ?? 10;\n\n // Pre-warm parameter pool\n for (let i = 0; i < paramSize; i++) {\n const obj = this.paramPool.acquire();\n this.paramPool.release(obj);\n }\n\n // Pre-warm query pool\n for (let i = 0; i < querySize; i++) {\n const obj = this.queryPool.acquire();\n this.queryPool.release(obj);\n }\n\n // Pre-warm header pool\n for (let i = 0; i < headerSize; i++) {\n const obj = this.headerPool.acquire();\n this.headerPool.release(obj);\n }\n\n // Pre-warm buffer pools with configurable sizes\n const bufferSizes = sizes?.buffers ?? {};\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n const pool = this.bufferPools.get(size);\n if (pool) {\n const warmCount = bufferSizes[size] ?? Math.min(25, pool.stats.maxSize);\n for (let j = 0; j < warmCount; j++) {\n const buffer = pool.acquire();\n pool.release(buffer);\n }\n }\n }\n\n logger.debug('Object pools pre-warmed with optimal sizes', 'PoolManager', {\n params: paramSize,\n query: querySize,\n headers: headerSize,\n });\n }\n\n /**\n * Get optimal pool size based on buffer size and usage patterns\n */\n private getOptimalPoolSize(bufferSize: number): number {\n // Smaller buffers can have larger pools\n if (bufferSize <= 256) return 100;\n if (bufferSize <= 1024) return 75;\n if (bufferSize <= 4096) return 50;\n return 25; // Large buffers need smaller pools\n }\n\n static getInstance(): ObjectPoolManager {\n if (!this.instance) {\n this.instance = new ObjectPoolManager();\n }\n return this.instance;\n }\n\n /**\n * Reset the singleton (useful for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearAll();\n }\n this.instance = null;\n }\n\n // Parameter Object Pool\n\n acquireParams(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n const obj = this.paramPool.acquire();\n\n if (this.poolUsageHistory.has('params')) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const history = this.poolUsageHistory.get('params')!;\n if (history.length >= 100) {\n history.shift(); // Keep only last 100 measurements\n }\n history.push(this.paramPool.size);\n } else {\n this.poolUsageHistory.set('params', [this.paramPool.size]);\n }\n\n return obj;\n }\n\n releaseParams(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.paramPool.release(obj);\n\n // Adaptive pool sizing based on usage patterns\n if (\n this.adaptiveMode &&\n Date.now() - this.performanceStats.lastAdjustment > this.performanceStats.adjustmentInterval\n ) {\n this.adjustPoolSizes();\n }\n }\n\n // Header Object Pool\n\n acquireHeaders(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n return this.headerPool.acquire();\n }\n\n releaseHeaders(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.headerPool.release(obj);\n }\n\n // Query Object Pool\n\n acquireQuery(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n return this.queryPool.acquire();\n }\n\n releaseQuery(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.queryPool.release(obj);\n }\n\n // Request ID Generation\n\n generateRequestId(): string {\n return crypto.randomUUID();\n }\n\n // Buffer Pool\n\n acquireBuffer(size: number): Buffer {\n this.performanceStats.totalAcquisitions++;\n\n // Find smallest buffer that fits\n for (const poolSize of this.bufferSizes) {\n if (size <= poolSize) {\n const pool = this.bufferPools.get(poolSize);\n if (pool) {\n const buffer = pool.acquire();\n this.performanceStats.poolHits++;\n\n // Track usage for adaptive sizing\n const poolKey = `buffer_${poolSize}`;\n if (this.poolUsageHistory.has(poolKey)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const history = this.poolUsageHistory.get(poolKey)!;\n if (history.length >= 100) {\n history.shift();\n }\n history.push(pool.size);\n } else {\n this.poolUsageHistory.set(poolKey, [pool.size]);\n }\n\n return buffer;\n }\n }\n }\n\n // No pool available for this size, allocate directly\n this.performanceStats.poolMisses++;\n return Buffer.allocUnsafe(size);\n }\n\n releaseBuffer(buffer: Buffer): void {\n this.performanceStats.totalReleases++;\n const size = buffer.length;\n const pool = this.bufferPools.get(size);\n if (pool) {\n pool.release(buffer);\n\n // Adaptive pool sizing based on usage patterns\n if (\n this.adaptiveMode &&\n Date.now() - this.performanceStats.lastAdjustment > this.performanceStats.adjustmentInterval\n ) {\n this.adjustPoolSizes();\n }\n }\n // If no pool for this size, let it be garbage collected\n }\n\n // Route Cache\n\n getCachedRoute(key: string): any {\n return this.routeCache.get(key);\n }\n\n cacheRoute(key: string, route: any): void {\n this.routeCache.set(key, route);\n }\n\n hasCachedRoute(key: string): boolean {\n return this.routeCache.has(key);\n }\n\n clearRouteCache(): void {\n this.routeCache.clear();\n }\n\n // Response Cache (For Opt-In Explicit Caching Only)\n // NOTE: This cache is NOT used automatically by the framework.\n // It's available for developers who explicitly want to cache specific responses.\n // Developers must carefully manage cache keys to avoid stale/incorrect data.\n\n getCachedResponse(\n key: string\n ): { buffer: Buffer; headers: Record<string, string>; statusCode: number } | undefined {\n return this.responseCache.get(key);\n }\n\n cacheResponse(\n key: string,\n buffer: Buffer,\n headers: Record<string, string>,\n statusCode: number = 200\n ): void {\n // Cache responses up to 4KB\n // WARNING: Only use this for static responses that never change\n if (buffer.length < 4096) {\n this.responseCache.set(key, {\n buffer: Buffer.from(buffer), // Clone to avoid mutations\n headers: { ...headers }, // Clone headers\n statusCode,\n });\n }\n }\n\n hasCachedResponse(key: string): boolean {\n return this.responseCache.has(key);\n }\n\n clearResponseCache(): void {\n this.responseCache.clear();\n }\n\n /**\n * Adaptively adjust pool sizes based on usage patterns\n */\n private adjustPoolSizes(): void {\n this.performanceStats.lastAdjustment = Date.now();\n\n // Adjust parameter pool size\n const paramHistory = this.poolUsageHistory.get('params') || [];\n if (paramHistory.length >= 10) {\n const avgUsage = paramHistory.reduce((sum, size) => sum + size, 0) / paramHistory.length;\n const targetSize = Math.min(Math.max(Math.round(avgUsage * 1.2), 50), 200); // 20% buffer, 50-200 range\n\n if (Math.abs(this.paramPool.stats.maxSize - targetSize) > 10) {\n logger.debug(\n `Adjusting param pool size from ${this.paramPool.stats.maxSize} to ${targetSize}`,\n 'PoolManager'\n );\n // Note: We can't directly change maxSize, but we can log the recommendation\n // In a real implementation, we'd recreate the pool with the new size\n }\n }\n\n // Adjust buffer pool sizes\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n const poolKey = `buffer_${size}`;\n const history = this.poolUsageHistory.get(poolKey) || [];\n if (history.length >= 10) {\n const avgUsage = history.reduce((sum, size) => sum + size, 0) / history.length;\n const pool = this.bufferPools.get(size);\n if (pool) {\n const currentMax = pool.stats.maxSize;\n const targetMax = this.getOptimalPoolSize(size);\n\n if (Math.abs(currentMax - targetMax) > 5) {\n logger.debug(\n `Buffer pool ${size}B: usage ${avgUsage.toFixed(1)}/${currentMax}, target ${targetMax}`,\n 'PoolManager'\n );\n }\n }\n }\n }\n\n logger.debug('Pool size adjustment cycle completed', 'PoolManager');\n }\n\n /**\n * Enable or disable adaptive pool sizing\n */\n setAdaptiveMode(enabled: boolean): void {\n this.adaptiveMode = enabled;\n logger.debug(`Adaptive pool sizing ${enabled ? 'enabled' : 'disabled'}`, 'PoolManager');\n }\n\n // Utility Methods\n\n /**\n * Clear all pools and caches\n */\n clearAll(): void {\n this.paramPool.clear();\n this.headerPool.clear();\n this.queryPool.clear();\n this.bufferPools.forEach(pool => pool.clear());\n this.routeCache.clear();\n this.responseCache.clear();\n logger.debug('All pools and caches cleared', 'Maintenance');\n }\n\n /**\n * Force garbage collection on pooled objects\n */\n forceCleanup(): void {\n this.clearAll();\n\n // Force GC if available\n if (globalThis?.gc) {\n globalThis.gc();\n logger.debug('Forced garbage collection', 'Maintenance');\n }\n }\n\n /**\n * Get comprehensive performance statistics\n */\n getStats() {\n const bufferPoolStats: Record<string, any> = {};\n this.bufferPools.forEach((pool, size) => {\n bufferPoolStats[`${size}B`] = pool.stats;\n });\n\n return {\n paramPool: this.paramPool.stats,\n headerPool: this.headerPool.stats,\n queryPool: this.queryPool.stats,\n bufferPools: bufferPoolStats,\n routeCache: this.routeCache.stats,\n responseCache: this.responseCache.stats,\n totalMemory: {\n params: this.paramPool.size * 50, // Rough estimate\n headers: this.headerPool.size * 100, // Rough estimate\n queries: this.queryPool.size * 50, // Rough estimate\n buffers: Array.from(this.bufferPools.values()).reduce((sum, pool) => sum + pool.size, 0),\n routes: this.routeCache.size * 200, // Rough estimate\n responses: this.responseCache.size * 1000, // Rough estimate (increased for full responses)\n },\n };\n }\n\n /**\n * Get performance summary for monitoring\n */\n getPerformanceSummary() {\n const stats = this.getStats();\n const routeCacheTotal = stats.routeCache.hits + stats.routeCache.misses;\n const responseCacheTotal = stats.responseCache.hits + stats.responseCache.misses;\n\n // Manually sum memory instead of Object.values().reduce()\n let totalMemory = 0;\n totalMemory += stats.totalMemory.params;\n totalMemory += stats.totalMemory.headers;\n totalMemory += stats.totalMemory.queries;\n totalMemory += stats.totalMemory.buffers;\n totalMemory += stats.totalMemory.routes;\n totalMemory += stats.totalMemory.responses;\n\n return {\n routeCacheHitRate: routeCacheTotal > 0 ? (stats.routeCache.hits / routeCacheTotal) * 100 : 0,\n responseCacheHitRate:\n responseCacheTotal > 0 ? (stats.responseCache.hits / responseCacheTotal) * 100 : 0,\n paramPoolUtilization: stats.paramPool.utilization * 100,\n totalMemoryKB: totalMemory / 1024,\n };\n }\n\n /**\n * Log performance statistics\n */\n logStats(): void {\n const summary = this.getPerformanceSummary();\n logger.info('ObjectPoolManager Performance', 'Stats', {\n routeCacheHitRate: `${summary.routeCacheHitRate.toFixed(1)}%`,\n responseCacheHitRate: `${summary.responseCacheHitRate.toFixed(1)}%`,\n paramPoolUtilization: `${summary.paramPoolUtilization.toFixed(1)}%`,\n totalMemory: `${summary.totalMemoryKB.toFixed(1)} KB`,\n });\n }\n}\n\n/**\n * Convenience function to get the singleton instance\n */\nexport function getPoolManager(): ObjectPoolManager {\n return ObjectPoolManager.getInstance();\n}\n"]}
1
+ {"version":3,"file":"object-pool-manager.js","sourceRoot":"","sources":["../../../src/core/pooling/object-pool-manager.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,6EAA6E;AAE7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,MAAM,MAAM,GAAG,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;AAE1D;;;;;;GAMG;AACH,MAAM,OAAO,iBAAiB;IACpB,MAAM,CAAC,QAAQ,GAA6B,IAAI,CAAC;IAEzD,2CAA2C;IACnC,SAAS,CAAqC;IAEtD,0CAA0C;IAClC,UAAU,CAAqC;IAEvD,+CAA+C;IACvC,SAAS,CAAqC;IAEtD,uBAAuB;IACf,WAAW,CAAkC;IACpC,WAAW,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAE5D,qBAAqB;IACb,UAAU,CAAwB;IAE1C,8EAA8E;IACtE,aAAa,CAGnB;IAEF,yBAAyB;IACjB,gBAAgB,GAAG;QACzB,QAAQ,EAAE,CAAC;QACX,UAAU,EAAE,CAAC;QACb,iBAAiB,EAAE,CAAC;QACpB,aAAa,EAAE,CAAC;QAChB,cAAc,EAAE,CAAC;QACjB,kBAAkB,EAAE,KAAK,EAAE,WAAW;KACvC,CAAC;IAEF,uBAAuB;IACf,gBAAgB,GAA0B,IAAI,GAAG,EAAE,CAAC;IACpD,YAAY,GAAG,IAAI,CAAC;IAE5B;QACE,mEAAmE;QACnE,IAAI,CAAC,gBAAgB,CAAC,cAAc,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAElD,wDAAwD;QACxD,IAAI,CAAC,SAAS,GAAG,IAAI,UA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AO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG;YACnE,WAAW,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK;SACtD,CAAC,CAAC;IACL,CAAC;;AAGH;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO,iBAAiB,CAAC,WAAW,EAAE,CAAC;AACzC,CAAC","sourcesContent":["// Unified Object Pool Manager\n// Consolidates object pooling from http-server, router, and other components\n\nimport { createFrameworkLogger } from '../logger/index.js';\nimport * as crypto from 'crypto';\nimport { ObjectPool } from './object-pool.js';\nimport { LRUCache } from './lru-cache.js';\nconst logger = createFrameworkLogger('ObjectPoolManager');\n\n/**\n * ObjectPoolManager - Singleton for managing all object pools\n * Consolidates pools from:\n * - MoroHttpServer (paramObjectPool, bufferPool)\n * - Router (paramObjectPool)\n * - Various route caches\n */\nexport class ObjectPoolManager {\n private static instance: ObjectPoolManager | null = null;\n\n // Parameter object pool (for route params)\n private paramPool: ObjectPool<Record<string, string>>;\n\n // Header object pool (for parsed headers)\n private headerPool: ObjectPool<Record<string, string>>;\n\n // Query object pool (for parsed query strings)\n private queryPool: ObjectPool<Record<string, string>>;\n\n // Buffer pools by size\n private bufferPools: Map<number, ObjectPool<Buffer>>;\n private readonly bufferSizes = [64, 256, 1024, 4096, 16384];\n\n // Route lookup cache\n private routeCache: LRUCache<string, any>;\n\n // Response cache (for common responses - now includes full response metadata)\n private responseCache: LRUCache<\n string,\n { buffer: Buffer; headers: Record<string, string>; statusCode: number }\n >;\n\n // Performance monitoring\n private performanceStats = {\n poolHits: 0,\n poolMisses: 0,\n totalAcquisitions: 0,\n totalReleases: 0,\n lastAdjustment: 0,\n adjustmentInterval: 60000, // 1 minute\n };\n\n // Adaptive pool sizing\n private poolUsageHistory: Map<string, number[]> = new Map();\n private adaptiveMode = true;\n\n private constructor() {\n // Set initial last adjustment time to prevent immediate adjustment\n this.performanceStats.lastAdjustment = Date.now();\n\n // Initialize parameter object pool with adaptive sizing\n this.paramPool = new ObjectPool(\n () => ({}),\n 100, // Initial size\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize header object pool\n this.headerPool = new ObjectPool(\n () => ({}),\n 50, // Initial size - headers are less common to pool\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize query object pool\n this.queryPool = new ObjectPool(\n () => ({}),\n 100, // Initial size - queries are very common\n (obj: Record<string, string>) => {\n // Clear all properties\n for (const key in obj) {\n delete obj[key];\n }\n }\n );\n\n // Initialize buffer pools with enhanced sizing\n this.bufferPools = new Map();\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n this.bufferPools.set(\n size,\n new ObjectPool<Buffer>(() => Buffer.allocUnsafe(size), this.getOptimalPoolSize(size))\n );\n }\n\n // Initialize caches with enhanced statistics\n this.routeCache = new LRUCache(500);\n this.responseCache = new LRUCache(200); // Increased for full response caching\n\n // Pre-warm pools with optimal defaults\n this.preWarmPools();\n\n logger.debug(\n 'ObjectPoolManager initialized with enhanced performance features',\n 'Initialization'\n );\n }\n\n /**\n * Pre-warm pools with optimal sizes for better startup performance\n * Can be called with custom sizes to override defaults\n */\n preWarmPools(sizes?: {\n params?: number;\n query?: number;\n headers?: number;\n buffers?: Record<number, number>;\n }): void {\n // Aggressive pre-warming for common scenarios\n const paramSize = sizes?.params ?? 50; // More aggressive default\n const querySize = sizes?.query ?? 50;\n const headerSize = sizes?.headers ?? 10;\n\n // Pre-warm parameter pool\n for (let i = 0; i < paramSize; i++) {\n const obj = this.paramPool.acquire();\n this.paramPool.release(obj);\n }\n\n // Pre-warm query pool\n for (let i = 0; i < querySize; i++) {\n const obj = this.queryPool.acquire();\n this.queryPool.release(obj);\n }\n\n // Pre-warm header pool\n for (let i = 0; i < headerSize; i++) {\n const obj = this.headerPool.acquire();\n this.headerPool.release(obj);\n }\n\n // Pre-warm buffer pools with configurable sizes\n const bufferSizes = sizes?.buffers ?? {};\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n const pool = this.bufferPools.get(size);\n if (pool) {\n const warmCount = bufferSizes[size] ?? Math.min(25, pool.stats.maxSize);\n for (let j = 0; j < warmCount; j++) {\n const buffer = pool.acquire();\n pool.release(buffer);\n }\n }\n }\n\n logger.debug('Object pools pre-warmed with optimal sizes', 'PoolManager', {\n params: paramSize,\n query: querySize,\n headers: headerSize,\n });\n }\n\n /**\n * Get optimal pool size based on buffer size and usage patterns\n */\n private getOptimalPoolSize(bufferSize: number): number {\n // Smaller buffers can have larger pools\n if (bufferSize <= 256) return 100;\n if (bufferSize <= 1024) return 75;\n if (bufferSize <= 4096) return 50;\n return 25; // Large buffers need smaller pools\n }\n\n static getInstance(): ObjectPoolManager {\n if (!this.instance) {\n this.instance = new ObjectPoolManager();\n }\n return this.instance;\n }\n\n /**\n * Reset the singleton (useful for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearAll();\n }\n this.instance = null;\n }\n\n // Parameter Object Pool\n\n acquireParams(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n const obj = this.paramPool.acquire();\n\n if (this.poolUsageHistory.has('params')) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const history = this.poolUsageHistory.get('params')!;\n if (history.length >= 100) {\n history.shift(); // Keep only last 100 measurements\n }\n history.push(this.paramPool.size);\n } else {\n this.poolUsageHistory.set('params', [this.paramPool.size]);\n }\n\n return obj;\n }\n\n releaseParams(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.paramPool.release(obj);\n\n // Adaptive pool sizing based on usage patterns\n if (\n this.adaptiveMode &&\n Date.now() - this.performanceStats.lastAdjustment > this.performanceStats.adjustmentInterval\n ) {\n this.adjustPoolSizes();\n }\n }\n\n // Header Object Pool\n\n acquireHeaders(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n return this.headerPool.acquire();\n }\n\n releaseHeaders(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.headerPool.release(obj);\n }\n\n // Query Object Pool\n\n acquireQuery(): Record<string, string> {\n this.performanceStats.totalAcquisitions++;\n const obj = this.queryPool.acquire();\n\n const history = this.poolUsageHistory.get('query');\n if (history) {\n if (history.length >= 100) {\n history.shift();\n }\n history.push(this.queryPool.size);\n } else {\n this.poolUsageHistory.set('query', [this.queryPool.size]);\n }\n\n return obj;\n }\n\n releaseQuery(obj: Record<string, string>): void {\n this.performanceStats.totalReleases++;\n this.queryPool.release(obj);\n\n if (\n this.adaptiveMode &&\n Date.now() - this.performanceStats.lastAdjustment > this.performanceStats.adjustmentInterval\n ) {\n this.adjustPoolSizes();\n }\n }\n\n // Request ID Generation\n\n generateRequestId(): string {\n return crypto.randomUUID();\n }\n\n // Buffer Pool\n\n acquireBuffer(size: number): Buffer {\n this.performanceStats.totalAcquisitions++;\n\n // Find smallest buffer that fits\n for (const poolSize of this.bufferSizes) {\n if (size <= poolSize) {\n const pool = this.bufferPools.get(poolSize);\n if (pool) {\n const buffer = pool.acquire();\n this.performanceStats.poolHits++;\n\n // Track usage for adaptive sizing\n const poolKey = `buffer_${poolSize}`;\n if (this.poolUsageHistory.has(poolKey)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const history = this.poolUsageHistory.get(poolKey)!;\n if (history.length >= 100) {\n history.shift();\n }\n history.push(pool.size);\n } else {\n this.poolUsageHistory.set(poolKey, [pool.size]);\n }\n\n return buffer;\n }\n }\n }\n\n // No pool available for this size, allocate directly\n this.performanceStats.poolMisses++;\n return Buffer.allocUnsafe(size);\n }\n\n releaseBuffer(buffer: Buffer): void {\n this.performanceStats.totalReleases++;\n const size = buffer.length;\n const pool = this.bufferPools.get(size);\n if (pool) {\n pool.release(buffer);\n\n // Adaptive pool sizing based on usage patterns\n if (\n this.adaptiveMode &&\n Date.now() - this.performanceStats.lastAdjustment > this.performanceStats.adjustmentInterval\n ) {\n this.adjustPoolSizes();\n }\n }\n // If no pool for this size, let it be garbage collected\n }\n\n // Route Cache\n\n getCachedRoute(key: string): any {\n return this.routeCache.get(key);\n }\n\n cacheRoute(key: string, route: any): void {\n this.routeCache.set(key, route);\n }\n\n hasCachedRoute(key: string): boolean {\n return this.routeCache.has(key);\n }\n\n clearRouteCache(): void {\n this.routeCache.clear();\n }\n\n // Response Cache (For Opt-In Explicit Caching Only)\n // NOTE: This cache is NOT used automatically by the framework.\n // It's available for developers who explicitly want to cache specific responses.\n // Developers must carefully manage cache keys to avoid stale/incorrect data.\n\n getCachedResponse(\n key: string\n ): { buffer: Buffer; headers: Record<string, string>; statusCode: number } | undefined {\n return this.responseCache.get(key);\n }\n\n cacheResponse(\n key: string,\n buffer: Buffer,\n headers: Record<string, string>,\n statusCode: number = 200\n ): void {\n // Cache responses up to 4KB\n // WARNING: Only use this for static responses that never change\n if (buffer.length < 4096) {\n this.responseCache.set(key, {\n buffer: Buffer.from(buffer), // Clone to avoid mutations\n headers: { ...headers }, // Clone headers\n statusCode,\n });\n }\n }\n\n hasCachedResponse(key: string): boolean {\n return this.responseCache.has(key);\n }\n\n clearResponseCache(): void {\n this.responseCache.clear();\n }\n\n /**\n * Adaptively adjust pool sizes based on usage patterns.\n * Each pool is sized to ~120% of its average observed size, clamped to a\n * [min, max] range, and only resized when the change exceeds a threshold.\n */\n private adjustPoolSizes(): void {\n this.performanceStats.lastAdjustment = Date.now();\n\n const applyFromHistory = (\n pool: ObjectPool<any>,\n historyKey: string,\n min: number,\n max: number,\n threshold: number,\n label: string\n ): void => {\n const history = this.poolUsageHistory.get(historyKey) || [];\n if (history.length < 10) return;\n\n const avgUsage = history.reduce((sum, size) => sum + size, 0) / history.length;\n const targetSize = Math.min(Math.max(Math.round(avgUsage * 1.2), min), max);\n\n if (Math.abs(pool.stats.maxSize - targetSize) > threshold) {\n logger.debug(\n `Adjusting ${label} pool size from ${pool.stats.maxSize} to ${targetSize}`,\n 'PoolManager'\n );\n pool.setMaxSize(targetSize);\n }\n };\n\n applyFromHistory(this.paramPool, 'params', 50, 200, 10, 'param');\n applyFromHistory(this.queryPool, 'query', 50, 200, 10, 'query');\n\n const bufferSizesLen = this.bufferSizes.length;\n for (let i = 0; i < bufferSizesLen; i++) {\n const size = this.bufferSizes[i];\n if (size === undefined) continue;\n const pool = this.bufferPools.get(size);\n if (!pool) continue;\n applyFromHistory(\n pool,\n `buffer_${size}`,\n 10,\n this.getOptimalPoolSize(size) * 2,\n 5,\n `buffer ${size}B`\n );\n }\n\n logger.debug('Pool size adjustment cycle completed', 'PoolManager');\n }\n\n /**\n * Enable or disable adaptive pool sizing\n */\n setAdaptiveMode(enabled: boolean): void {\n this.adaptiveMode = enabled;\n logger.debug(`Adaptive pool sizing ${enabled ? 'enabled' : 'disabled'}`, 'PoolManager');\n }\n\n // Utility Methods\n\n /**\n * Clear all pools and caches\n */\n clearAll(): void {\n this.paramPool.clear();\n this.headerPool.clear();\n this.queryPool.clear();\n this.bufferPools.forEach(pool => pool.clear());\n this.routeCache.clear();\n this.responseCache.clear();\n logger.debug('All pools and caches cleared', 'Maintenance');\n }\n\n /**\n * Force garbage collection on pooled objects\n */\n forceCleanup(): void {\n this.clearAll();\n\n // Force GC if available\n if (globalThis?.gc) {\n globalThis.gc();\n logger.debug('Forced garbage collection', 'Maintenance');\n }\n }\n\n /**\n * Get comprehensive performance statistics\n */\n getStats() {\n const bufferPoolStats: Record<string, any> = {};\n this.bufferPools.forEach((pool, size) => {\n bufferPoolStats[`${size}B`] = pool.stats;\n });\n\n return {\n paramPool: this.paramPool.stats,\n headerPool: this.headerPool.stats,\n queryPool: this.queryPool.stats,\n bufferPools: bufferPoolStats,\n routeCache: this.routeCache.stats,\n responseCache: this.responseCache.stats,\n totalMemory: {\n params: this.paramPool.size * 50, // Rough estimate\n headers: this.headerPool.size * 100, // Rough estimate\n queries: this.queryPool.size * 50, // Rough estimate\n buffers: Array.from(this.bufferPools.values()).reduce((sum, pool) => sum + pool.size, 0),\n routes: this.routeCache.size * 200, // Rough estimate\n responses: this.responseCache.size * 1000, // Rough estimate (increased for full responses)\n },\n };\n }\n\n /**\n * Get performance summary for monitoring\n */\n getPerformanceSummary() {\n const stats = this.getStats();\n const routeCacheTotal = stats.routeCache.hits + stats.routeCache.misses;\n const responseCacheTotal = stats.responseCache.hits + stats.responseCache.misses;\n\n // Manually sum memory instead of Object.values().reduce()\n let totalMemory = 0;\n totalMemory += stats.totalMemory.params;\n totalMemory += stats.totalMemory.headers;\n totalMemory += stats.totalMemory.queries;\n totalMemory += stats.totalMemory.buffers;\n totalMemory += stats.totalMemory.routes;\n totalMemory += stats.totalMemory.responses;\n\n return {\n routeCacheHitRate: routeCacheTotal > 0 ? (stats.routeCache.hits / routeCacheTotal) * 100 : 0,\n responseCacheHitRate:\n responseCacheTotal > 0 ? (stats.responseCache.hits / responseCacheTotal) * 100 : 0,\n paramPoolUtilization: stats.paramPool.utilization * 100,\n totalMemoryKB: totalMemory / 1024,\n };\n }\n\n /**\n * Log performance statistics\n */\n logStats(): void {\n const summary = this.getPerformanceSummary();\n logger.info('ObjectPoolManager Performance', 'Stats', {\n routeCacheHitRate: `${summary.routeCacheHitRate.toFixed(1)}%`,\n responseCacheHitRate: `${summary.responseCacheHitRate.toFixed(1)}%`,\n paramPoolUtilization: `${summary.paramPoolUtilization.toFixed(1)}%`,\n totalMemory: `${summary.totalMemoryKB.toFixed(1)} KB`,\n });\n }\n}\n\n/**\n * Convenience function to get the singleton instance\n */\nexport function getPoolManager(): ObjectPoolManager {\n return ObjectPoolManager.getInstance();\n}\n"]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Generic object pool for reusable objects
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { ObjectPool } from '@morojs/moro';
7
+ *
8
+ * const pool = new ObjectPool(() => ({}), 100, obj => {
9
+ * for (const key in obj) delete obj[key];
10
+ * });
11
+ * const obj = pool.acquire();
12
+ * // ... use obj ...
13
+ * pool.release(obj);
14
+ * ```
15
+ */
16
+ export declare class ObjectPool<T> {
17
+ private pool;
18
+ private readonly factory;
19
+ private readonly reset?;
20
+ private maxSize;
21
+ private acquireCount;
22
+ private releaseCount;
23
+ private createCount;
24
+ constructor(factory: () => T, maxSize?: number, reset?: (obj: T) => void);
25
+ acquire(): T;
26
+ release(obj: T): void;
27
+ /**
28
+ * Adjust the pool's capacity. Shrinking drops surplus pooled objects
29
+ * immediately (they are left for garbage collection).
30
+ */
31
+ setMaxSize(maxSize: number): void;
32
+ get size(): number;
33
+ get stats(): {
34
+ poolSize: number;
35
+ maxSize: number;
36
+ acquireCount: number;
37
+ releaseCount: number;
38
+ createCount: number;
39
+ utilization: number;
40
+ };
41
+ clear(): void;
42
+ }
@@ -0,0 +1,78 @@
1
+ // Generic Object Pool
2
+ // Reuses objects to avoid allocation/GC pressure on hot paths.
3
+ /**
4
+ * Generic object pool for reusable objects
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { ObjectPool } from '@morojs/moro';
9
+ *
10
+ * const pool = new ObjectPool(() => ({}), 100, obj => {
11
+ * for (const key in obj) delete obj[key];
12
+ * });
13
+ * const obj = pool.acquire();
14
+ * // ... use obj ...
15
+ * pool.release(obj);
16
+ * ```
17
+ */
18
+ export class ObjectPool {
19
+ pool = [];
20
+ factory;
21
+ reset;
22
+ maxSize;
23
+ acquireCount = 0;
24
+ releaseCount = 0;
25
+ createCount = 0;
26
+ constructor(factory, maxSize = 100, reset) {
27
+ this.factory = factory;
28
+ this.maxSize = maxSize;
29
+ this.reset = reset;
30
+ }
31
+ acquire() {
32
+ this.acquireCount++;
33
+ if (this.pool.length > 0) {
34
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
35
+ return this.pool.pop();
36
+ }
37
+ this.createCount++;
38
+ return this.factory();
39
+ }
40
+ release(obj) {
41
+ if (this.pool.length >= this.maxSize) {
42
+ return; // Pool is full, let it be garbage collected
43
+ }
44
+ this.releaseCount++;
45
+ // Reset object if reset function provided
46
+ if (this.reset) {
47
+ this.reset(obj);
48
+ }
49
+ this.pool.push(obj);
50
+ }
51
+ /**
52
+ * Adjust the pool's capacity. Shrinking drops surplus pooled objects
53
+ * immediately (they are left for garbage collection).
54
+ */
55
+ setMaxSize(maxSize) {
56
+ this.maxSize = Math.max(0, Math.floor(maxSize));
57
+ if (this.pool.length > this.maxSize) {
58
+ this.pool.length = this.maxSize;
59
+ }
60
+ }
61
+ get size() {
62
+ return this.pool.length;
63
+ }
64
+ get stats() {
65
+ return {
66
+ poolSize: this.pool.length,
67
+ maxSize: this.maxSize,
68
+ acquireCount: this.acquireCount,
69
+ releaseCount: this.releaseCount,
70
+ createCount: this.createCount,
71
+ utilization: this.maxSize > 0 ? this.pool.length / this.maxSize : 0,
72
+ };
73
+ }
74
+ clear() {
75
+ this.pool = [];
76
+ }
77
+ }
78
+ //# sourceMappingURL=object-pool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object-pool.js","sourceRoot":"","sources":["../../../src/core/pooling/object-pool.ts"],"names":[],"mappings":"AAAA,sBAAsB;AACtB,+DAA+D;AAE/D;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,UAAU;IACb,IAAI,GAAQ,EAAE,CAAC;IACN,OAAO,CAAU;IACjB,KAAK,CAAkC;IAChD,OAAO,CAAS;IAChB,YAAY,GAAG,CAAC,CAAC;IACjB,YAAY,GAAG,CAAC,CAAC;IACjB,WAAW,GAAG,CAAC,CAAC;IAExB,YAAY,OAAgB,EAAE,UAAkB,GAAG,EAAE,KAAwB;QAC3E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO;QACL,IAAI,CAAC,YAAY,EAAE,CAAC;QAEpB,IAAI,IAAI,CA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AO,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;SACpE,CAAC;IACJ,CAAC;IAED,KAAK;QACH,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;IACjB,CAAC;CACF","sourcesContent":["// Generic Object Pool\n// Reuses objects to avoid allocation/GC pressure on hot paths.\n\n/**\n * Generic object pool for reusable objects\n *\n * @example\n * ```ts\n * import { ObjectPool } from '@morojs/moro';\n *\n * const pool = new ObjectPool(() => ({}), 100, obj => {\n * for (const key in obj) delete obj[key];\n * });\n * const obj = pool.acquire();\n * // ... use obj ...\n * pool.release(obj);\n * ```\n */\nexport class ObjectPool<T> {\n private pool: T[] = [];\n private readonly factory: () => T;\n private readonly reset?: ((obj: T) => void) | undefined;\n private maxSize: number;\n private acquireCount = 0;\n private releaseCount = 0;\n private createCount = 0;\n\n constructor(factory: () => T, maxSize: number = 100, reset?: (obj: T) => void) {\n this.factory = factory;\n this.maxSize = maxSize;\n this.reset = reset;\n }\n\n acquire(): T {\n this.acquireCount++;\n\n if (this.pool.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.pool.pop()!;\n }\n\n this.createCount++;\n return this.factory();\n }\n\n release(obj: T): void {\n if (this.pool.length >= this.maxSize) {\n return; // Pool is full, let it be garbage collected\n }\n\n this.releaseCount++;\n\n // Reset object if reset function provided\n if (this.reset) {\n this.reset(obj);\n }\n\n this.pool.push(obj);\n }\n\n /**\n * Adjust the pool's capacity. Shrinking drops surplus pooled objects\n * immediately (they are left for garbage collection).\n */\n setMaxSize(maxSize: number): void {\n this.maxSize = Math.max(0, Math.floor(maxSize));\n if (this.pool.length > this.maxSize) {\n this.pool.length = this.maxSize;\n }\n }\n\n get size(): number {\n return this.pool.length;\n }\n\n get stats() {\n return {\n poolSize: this.pool.length,\n maxSize: this.maxSize,\n acquireCount: this.acquireCount,\n releaseCount: this.releaseCount,\n createCount: this.createCount,\n utilization: this.maxSize > 0 ? this.pool.length / this.maxSize : 0,\n };\n }\n\n clear(): void {\n this.pool = [];\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create-router.js","sourceRoot":"","sources":["../../../src/core/routing/create-router.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAW/E;;;;;;;;;GASG;AACH,MAAM,OAAO,UAAU;IACrB,gFAAgF;IACvE,aAAa,GAAG,IAAI,CAAC;IACtB,MAAM,GAAiB,EAAE,CAAC;IAC1B,iBAAiB,GAAiB,EAAE,CAAC;IAE7C,GAAG,CAAC,GAAG,UAAwB;QAC7B,KAAK,MAAM,EAAE,IAAI,UAAU;YAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,GAAG,CAAC,IAAY,EAAE,GAAG,QAAe;QAClC,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,IAAI,CAAC,IAAY,EAAE,GAAG,QAAe;QACnC,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC;IACD,GAAG,CAAC,IAAY,EAAE,GAAG,QAAe;QAClC,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,MAAM,CAAC,IAAY,EAAE,GAAG,QAAe;QACrC,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IACD,KAAK,CAAC,IAAY,EAAE,GAAG,QAAe;QACpC,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAChD,CAAC;I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,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;QACnF,MAAM,WAAW,GAAG,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC;YAChD,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/B,CAAC,CAAC,gBAAgB,CAAC;QAErB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChC,MAAM,QAAQ,GAAG,WAAW,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;YAC5F,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,CAAC,iBAAiB,EAAE,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;YAC7E,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,WAAW,EAO1B,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,kBAAkB,EAAE,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;CACF;AAED,uCAAuC;AACvC,MAAM,UAAU,YAAY;IAC1B,OAAO,IAAI,UAAU,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["// Standalone router — collects route registrations and mounts them onto an app\n// at a given prefix. Equivalent semantics to Express's Router(), so migrations\n// from Express become a one-token swap: `express.Router()` → `createRouter()`.\n\nimport type { HttpRequest, HttpResponse, Middleware } from '../../types/http.js';\n\ntype RouteEntry = {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';\n path: string;\n middlewares: Middleware[];\n handler: (req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n};\n\n/**\n * Standalone router. Collects routes and middlewares, then mounts them onto an\n * app at a given prefix via `app.use(prefix, router)` or `router.mount(app, prefix)`.\n *\n * @example\n * const r = createRouter();\n * r.get('/users', getUsers);\n * r.post('/users', createUser);\n * app.use('/api', r);\n */\nexport class MoroRouter {\n /** @internal — tag used by app.use(path, router) to detect router instances. */\n readonly _morojsRouter = true;\n private routes: RouteEntry[] = [];\n private globalMiddlewares: Middleware[] = [];\n\n use(...middleware: Middleware[]): this {\n for (const mw of middleware) this.globalMiddlewares.push(mw);\n return this;\n }\n\n get(path: string, ...handlers: any[]): this {\n return this.addRoute('GET', path, handlers);\n }\n post(path: string, ...handlers: any[]): this {\n return this.addRoute('POST', path, handlers);\n }\n put(path: string, ...handlers: any[]): this {\n return this.addRoute('PUT', path, handlers);\n }\n delete(path: string, ...handlers: any[]): this {\n return this.addRoute('DELETE', path, handlers);\n }\n patch(path: string, ...handlers: any[]): this {\n return this.addRoute('PATCH', path, handlers);\n }\n head(path: string, ...handlers: any[]): this {\n return this.addRoute('HEAD', path, handlers);\n }\n options(path: string, ...handlers: any[]): this {\n return this.addRoute('OPTIONS', path, handlers);\n }\n\n /** Register the same handler(s) for all HTTP methods on the path. */\n all(path: string, ...handlers: any[]): this {\n const methods: RouteEntry['method'][] = [\n 'GET',\n 'POST',\n 'PUT',\n 'DELETE',\n 'PATCH',\n 'HEAD',\n 'OPTIONS',\n ];\n for (const m of methods) this.addRoute(m, path, handlers);\n return this;\n }\n\n private addRoute(method: RouteEntry['method'], path: string, handlers: any[]): this {\n if (handlers.length === 0) {\n throw new Error(`${method} ${path}: handler is required`);\n }\n const handler = handlers[handlers.length - 1];\n const middlewares = handlers.slice(0, -1) as Middleware[];\n this.routes.push({ method, path, middlewares, handler });\n return this;\n }\n\n /** Mount all collected routes onto `app` at the given prefix. */\n mount(app: any, prefix = ''): void {\n const normalizedPrefix = prefix && !prefix.startsWith('/') ? `/${prefix}` : prefix;\n const cleanPrefix = normalizedPrefix.endsWith('/')\n ? normalizedPrefix.slice(0, -1)\n : normalizedPrefix;\n\n for (const route of this.routes) {\n const fullPath = cleanPrefix + (route.path.startsWith('/') ? route.path : `/${route.path}`);\n const combinedMiddleware = [...this.globalMiddlewares, ...route.middlewares];\n const method = route.method.toLowerCase() as\n | 'get'\n | 'post'\n | 'put'\n | 'delete'\n | 'patch'\n | 'head'\n | 'options';\n app[method](fullPath, route.handler, { middleware: combinedMiddleware });\n }\n }\n}\n\n/** Factory for a standalone router. */\nexport function createRouter(): MoroRouter {\n return new MoroRouter();\n}\n"]}
1
+ {"version":3,"file":"create-router.js","sourceRoot":"","sources":["../../../src/core/routing/create-router.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAW/E;;;;;;;;;GASG;AACH,MAAM,OAAO,UAAU;IACrB,gFAAgF;IACvE,aAAa,GAAG,IAAI,CAAC;IACtB,MAAM,GAAiB,EAAE,CAAC;IAC1B,iBAAiB,GAAiB,EAAE,CAAC;IAE7C,GAAG,CAAC,GAAG,UAAwB;QAC7B,KAAK,MAAM,EAAE,IAAI,UAAU;YAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,GAAG,CAAC,IAAY,EAAE,GAAG,QAAe;QAClC,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,IAAI,CAAC,IAAY,EAAE,GAAG,QAAe;QACnC,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC;IACD,GAAG,CAAC,IAAY,EAAE,GAAG,QAAe;QAClC,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,MAAM,CAAC,IAAY,EAAE,GAAG,QAAe;QACrC,OAAO,IAAI,CAAC,QAAQ,CA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EAAE,CAAC,CAAC;QACzD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,iEAAiE;IACjE,KAAK,CAAC,GAAQ,EAAE,MAAM,GAAG,EAAE;QACzB,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;QACnF,MAAM,WAAW,GAAG,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC;YAChD,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/B,CAAC,CAAC,gBAAgB,CAAC;QAErB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChC,MAAM,QAAQ,GAAG,WAAW,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;YAC5F,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,CAAC,iBAAiB,EAAE,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;YAC7E,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,WAAW,EAC2B,CAAC;YACnE,GAAG,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,kBAAkB,EAAE,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;CACF;AAED,uCAAuC;AACvC,MAAM,UAAU,YAAY;IAC1B,OAAO,IAAI,UAAU,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["// Standalone router — collects route registrations and mounts them onto an app\n// at a given prefix. Equivalent semantics to Express's Router(), so migrations\n// from Express become a one-token swap: `express.Router()` → `createRouter()`.\n\nimport type { HttpRequest, HttpResponse, Middleware } from '../../types/http.js';\n\ntype RouteEntry = {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';\n path: string;\n middlewares: Middleware[];\n handler: (req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n};\n\n/**\n * Standalone router. Collects routes and middlewares, then mounts them onto an\n * app at a given prefix via `app.use(prefix, router)` or `router.mount(app, prefix)`.\n *\n * @example\n * const r = createRouter();\n * r.get('/users', getUsers);\n * r.post('/users', createUser);\n * app.use('/api', r);\n */\nexport class MoroRouter {\n /** @internal — tag used by app.use(path, router) to detect router instances. */\n readonly _morojsRouter = true;\n private routes: RouteEntry[] = [];\n private globalMiddlewares: Middleware[] = [];\n\n use(...middleware: Middleware[]): this {\n for (const mw of middleware) this.globalMiddlewares.push(mw);\n return this;\n }\n\n get(path: string, ...handlers: any[]): this {\n return this.addRoute('GET', path, handlers);\n }\n post(path: string, ...handlers: any[]): this {\n return this.addRoute('POST', path, handlers);\n }\n put(path: string, ...handlers: any[]): this {\n return this.addRoute('PUT', path, handlers);\n }\n delete(path: string, ...handlers: any[]): this {\n return this.addRoute('DELETE', path, handlers);\n }\n patch(path: string, ...handlers: any[]): this {\n return this.addRoute('PATCH', path, handlers);\n }\n head(path: string, ...handlers: any[]): this {\n return this.addRoute('HEAD', path, handlers);\n }\n options(path: string, ...handlers: any[]): this {\n return this.addRoute('OPTIONS', path, handlers);\n }\n\n /** Register the same handler(s) for all HTTP methods on the path. */\n all(path: string, ...handlers: any[]): this {\n const methods: RouteEntry['method'][] = [\n 'GET',\n 'POST',\n 'PUT',\n 'DELETE',\n 'PATCH',\n 'HEAD',\n 'OPTIONS',\n ];\n for (const m of methods) this.addRoute(m, path, handlers);\n return this;\n }\n\n private addRoute(method: RouteEntry['method'], path: string, handlers: any[]): this {\n if (handlers.length === 0) {\n throw new Error(`${method} ${path}: handler is required`);\n }\n const handler = handlers[handlers.length - 1];\n const middlewares = handlers.slice(0, -1) as Middleware[];\n this.routes.push({ method, path, middlewares, handler });\n return this;\n }\n\n /** Mount all collected routes onto `app` at the given prefix. */\n mount(app: any, prefix = ''): void {\n const normalizedPrefix = prefix && !prefix.startsWith('/') ? `/${prefix}` : prefix;\n const cleanPrefix = normalizedPrefix.endsWith('/')\n ? normalizedPrefix.slice(0, -1)\n : normalizedPrefix;\n\n for (const route of this.routes) {\n const fullPath = cleanPrefix + (route.path.startsWith('/') ? route.path : `/${route.path}`);\n const combinedMiddleware = [...this.globalMiddlewares, ...route.middlewares];\n const method = route.method.toLowerCase() as\n 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options';\n app[method](fullPath, route.handler, { middleware: combinedMiddleware });\n }\n }\n}\n\n/** Factory for a standalone router. */\nexport function createRouter(): MoroRouter {\n return new MoroRouter();\n}\n"]}
@@ -1,48 +1,6 @@
1
1
  // Shared Path Matching Utility with Caching
2
2
  // Replaces 6 different pathToRegex implementations across the codebase
3
- /**
4
- * LRU Cache implementation for compiled paths
5
- */
6
- class LRUCache {
7
- cache = new Map();
8
- maxSize;
9
- constructor(maxSize = 1000) {
10
- this.maxSize = maxSize;
11
- }
12
- get(key) {
13
- const value = this.cache.get(key);
14
- if (value !== undefined) {
15
- // Move to end (most recently used)
16
- this.cache.delete(key);
17
- this.cache.set(key, value);
18
- }
19
- return value;
20
- }
21
- set(key, value) {
22
- // Remove if exists (to update position)
23
- if (this.cache.has(key)) {
24
- this.cache.delete(key);
25
- }
26
- // Add to end
27
- this.cache.set(key, value);
28
- // Evict oldest if over capacity
29
- if (this.cache.size > this.maxSize) {
30
- const firstKey = this.cache.keys().next().value;
31
- if (firstKey !== undefined) {
32
- this.cache.delete(firstKey);
33
- }
34
- }
35
- }
36
- has(key) {
37
- return this.cache.has(key);
38
- }
39
- clear() {
40
- this.cache.clear();
41
- }
42
- get size() {
43
- return this.cache.size;
44
- }
45
- }
3
+ import { LRUCache } from '../pooling/lru-cache.js';
46
4
  /**
47
5
  * PathMatcher - Single source of truth for path pattern compilation and matching
48
6
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AM,CAAC,UAAU,CAAC,KAAe;QAC/B,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC;QAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAW,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;;AAGH;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO;QACL,OAAO,EAAE,QAAQ,CAAC,OAAO,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC;QAC1E,UAAU,EAAE,QAAQ,CAAC,UAAU;KAChC,CAAC;AACJ,CAAC","sourcesContent":["// Shared Path Matching Utility with Caching\n// Replaces 6 different pathToRegex implementations across the codebase\n\nexport interface CompiledPath {\n pattern: RegExp | null;\n paramNames: string[];\n isStatic: boolean;\n path: string;\n segments: number;\n}\n\nexport interface MatchResult {\n params: Record<string, string>;\n}\n\n/**\n * LRU Cache implementation for compiled paths\n */\nclass LRUCache<K, V> {\n private cache = new Map<K, V>();\n private readonly maxSize: number;\n\n constructor(maxSize: number = 1000) {\n this.maxSize = maxSize;\n }\n\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n // Move to end (most recently used)\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n return value;\n }\n\n set(key: K, value: V): void {\n // Remove if exists (to update position)\n if (this.cache.has(key)) {\n this.cache.delete(key);\n }\n\n // Add to end\n this.cache.set(key, value);\n\n // Evict oldest if over capacity\n if (this.cache.size > this.maxSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) {\n this.cache.delete(firstKey);\n }\n }\n }\n\n has(key: K): boolean {\n return this.cache.has(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n/**\n * PathMatcher - Single source of truth for path pattern compilation and matching\n */\nexport class PathMatcher {\n private static readonly cache = new LRUCache<string, CompiledPath>(1000);\n private static compilationCount = 0;\n private static cacheHits = 0;\n private static cacheMisses = 0;\n\n // PERFORMANCE: Cache segment counts for 500%+ speedup on repeated paths\n private static readonly segmentCountCache = new Map<string, number>();\n private static readonly MAX_SEGMENT_CACHE_SIZE = 1000;\n\n /**\n * Compile a path pattern into an efficient matching structure\n * Results are cached for performance\n */\n static compile(path: string): CompiledPath {\n // Check cache first\n const cached = this.cache.get(path);\n if (cached) {\n this.cacheHits++;\n return cached;\n }\n\n this.cacheMisses++;\n this.compilationCount++;\n\n // Compile the pattern\n const compiled = this.compileInternal(path);\n this.cache.set(path, compiled);\n return compiled;\n }\n\n /**\n * Internal compilation logic\n */\n private static compileInternal(path: string): CompiledPath {\n const paramNames: string[] = [];\n const isStatic = !path.includes(':') && !path.includes('*');\n\n // Calculate segment count for optimization using shared utility\n const segments = PathMatcher.countSegments(path);\n\n if (isStatic) {\n // No regex needed for static routes\n return {\n pattern: null,\n paramNames: [],\n isStatic: true,\n path,\n segments,\n };\n }\n\n // Convert parameterized routes to regex\n // Match :paramName and capture the parameter name\n const regexPath = path\n .replace(/\\/:([^/]+)/g, (match, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n .replace(/\\//g, '\\\\/');\n\n return {\n pattern: new RegExp(`^${regexPath}$`),\n paramNames,\n isStatic: false,\n path,\n segments,\n };\n }\n\n /**\n * Match a request path against a compiled pattern\n * Returns match result with extracted parameters, or null if no match\n */\n static match(compiledPath: CompiledPath, requestPath: string): MatchResult | null {\n // Path for static routes - simple string comparison\n if (compiledPath.isStatic) {\n return compiledPath.path === requestPath ? { params: {} } : null;\n }\n\n // Dynamic route - use regex matching\n if (!compiledPath.pattern) {\n return null;\n }\n\n const matches = requestPath.match(compiledPath.pattern);\n if (!matches) {\n return null;\n }\n\n // Extract params - optimized with for loop instead of forEach\n const params: Record<string, string> = {};\n const paramNames = compiledPath.paramNames;\n const paramCount = paramNames.length;\n for (let i = 0; i < paramCount; i++) {\n params[paramNames[i] as string] = matches[i + 1] as string;\n }\n\n return { params };\n }\n\n /**\n * Compile and match in one operation (convenience method)\n */\n static compileAndMatch(pathPattern: string, requestPath: string): MatchResult | null {\n const compiled = this.compile(pathPattern);\n return this.match(compiled, requestPath);\n }\n\n /**\n * Check if a path pattern is static (no parameters)\n */\n static isStatic(path: string): boolean {\n return !path.includes(':') && !path.includes('*');\n }\n\n /**\n * Count segments in a path (optimized with caching)\n */\n static countSegments(path: string): number {\n // Check cache first - most paths are repeated\n const cached = this.segmentCountCache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n\n // Count segments manually (fast charCode comparison)\n let segmentCount = 0;\n const pathLen = path.length;\n let inSegment = false;\n\n for (let i = 0; i < pathLen; i++) {\n const char = path.charCodeAt(i);\n if (char === 47) {\n // '/' character\n inSegment = false;\n } else if (!inSegment) {\n inSegment = true;\n segmentCount++;\n }\n }\n\n // Cache result (limit cache size to prevent memory leaks)\n if (this.segmentCountCache.size < this.MAX_SEGMENT_CACHE_SIZE) {\n this.segmentCountCache.set(path, segmentCount);\n }\n\n return segmentCount;\n }\n\n /**\n * Get performance statistics\n */\n static getStats() {\n const totalRequests = this.cacheHits + this.cacheMisses;\n return {\n cacheSize: this.cache.size,\n cacheHits: this.cacheHits,\n cacheMisses: this.cacheMisses,\n hitRate: totalRequests > 0 ? this.cacheHits / totalRequests : 0,\n compilationCount: this.compilationCount,\n };\n }\n\n /**\n * Clear the cache (useful for testing)\n */\n static clearCache(): void {\n this.cache.clear();\n this.segmentCountCache.clear(); // Clear segment count cache too\n this.cacheHits = 0;\n this.cacheMisses = 0;\n }\n\n /**\n * Pre-compile multiple paths (cache warming)\n */\n static precompile(paths: string[]): void {\n const pathsLen = paths.length;\n for (let i = 0; i < pathsLen; i++) {\n this.compile(paths[i] as string);\n }\n }\n}\n\n/**\n * Legacy compatibility function - maps to PathMatcher.compile\n * @deprecated Use PathMatcher.compile instead\n */\nexport function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const compiled = PathMatcher.compile(path);\n return {\n pattern: compiled.pattern || new RegExp(`^${path.replace(/\\//g, '\\\\/')}$`),\n paramNames: compiled.paramNames,\n };\n}\n"]}
1
+ {"version":3,"file":"path-matcher.js","sourceRoot":"","sources":["../../../src/core/routing/path-matcher.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,uEAAuE;AAEvE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAcnD;;GAEG;AACH,MAAM,OAAO,WAAW;IACd,MAAM,CAAU,KAAK,GAAG,IAAI,QAAQ,CAAuB,IAAI,CAAC,CAAC;IACjE,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC;IAC5B,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC;IACrB,MAAM,CAAC,WAAW,GAAG,CAAC,CAAC;IAE/B,wEAAwE;IAChE,MAAM,CAAU,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC9D,MAAM,CAAU,sBAAsB,GAAG,IAAI,CAAC;IAEtD;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,IAAY;QACzB,oBAAoB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,CAAC,WAAW,EAAE,CAAC;QACnB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAExB,sBAAsB;QACtB,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,CA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AC,KAAK,EAAE,CAAC,CAAC,gCAAgC;QAChE,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;QACnB,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,UAAU,CAAC,KAAe;QAC/B,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC;QAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAW,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;;AAGH;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO;QACL,OAAO,EAAE,QAAQ,CAAC,OAAO,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC;QAC1E,UAAU,EAAE,QAAQ,CAAC,UAAU;KAChC,CAAC;AACJ,CAAC","sourcesContent":["// Shared Path Matching Utility with Caching\n// Replaces 6 different pathToRegex implementations across the codebase\n\nimport { LRUCache } from '../pooling/lru-cache.js';\n\nexport interface CompiledPath {\n pattern: RegExp | null;\n paramNames: string[];\n isStatic: boolean;\n path: string;\n segments: number;\n}\n\nexport interface MatchResult {\n params: Record<string, string>;\n}\n\n/**\n * PathMatcher - Single source of truth for path pattern compilation and matching\n */\nexport class PathMatcher {\n private static readonly cache = new LRUCache<string, CompiledPath>(1000);\n private static compilationCount = 0;\n private static cacheHits = 0;\n private static cacheMisses = 0;\n\n // PERFORMANCE: Cache segment counts for 500%+ speedup on repeated paths\n private static readonly segmentCountCache = new Map<string, number>();\n private static readonly MAX_SEGMENT_CACHE_SIZE = 1000;\n\n /**\n * Compile a path pattern into an efficient matching structure\n * Results are cached for performance\n */\n static compile(path: string): CompiledPath {\n // Check cache first\n const cached = this.cache.get(path);\n if (cached) {\n this.cacheHits++;\n return cached;\n }\n\n this.cacheMisses++;\n this.compilationCount++;\n\n // Compile the pattern\n const compiled = this.compileInternal(path);\n this.cache.set(path, compiled);\n return compiled;\n }\n\n /**\n * Internal compilation logic\n */\n private static compileInternal(path: string): CompiledPath {\n const paramNames: string[] = [];\n const isStatic = !path.includes(':') && !path.includes('*');\n\n // Calculate segment count for optimization using shared utility\n const segments = PathMatcher.countSegments(path);\n\n if (isStatic) {\n // No regex needed for static routes\n return {\n pattern: null,\n paramNames: [],\n isStatic: true,\n path,\n segments,\n };\n }\n\n // Convert parameterized routes to regex\n // Match :paramName and capture the parameter name\n const regexPath = path\n .replace(/\\/:([^/]+)/g, (match, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n .replace(/\\//g, '\\\\/');\n\n return {\n pattern: new RegExp(`^${regexPath}$`),\n paramNames,\n isStatic: false,\n path,\n segments,\n };\n }\n\n /**\n * Match a request path against a compiled pattern\n * Returns match result with extracted parameters, or null if no match\n */\n static match(compiledPath: CompiledPath, requestPath: string): MatchResult | null {\n // Path for static routes - simple string comparison\n if (compiledPath.isStatic) {\n return compiledPath.path === requestPath ? { params: {} } : null;\n }\n\n // Dynamic route - use regex matching\n if (!compiledPath.pattern) {\n return null;\n }\n\n const matches = requestPath.match(compiledPath.pattern);\n if (!matches) {\n return null;\n }\n\n // Extract params - optimized with for loop instead of forEach\n const params: Record<string, string> = {};\n const paramNames = compiledPath.paramNames;\n const paramCount = paramNames.length;\n for (let i = 0; i < paramCount; i++) {\n params[paramNames[i] as string] = matches[i + 1] as string;\n }\n\n return { params };\n }\n\n /**\n * Compile and match in one operation (convenience method)\n */\n static compileAndMatch(pathPattern: string, requestPath: string): MatchResult | null {\n const compiled = this.compile(pathPattern);\n return this.match(compiled, requestPath);\n }\n\n /**\n * Check if a path pattern is static (no parameters)\n */\n static isStatic(path: string): boolean {\n return !path.includes(':') && !path.includes('*');\n }\n\n /**\n * Count segments in a path (optimized with caching)\n */\n static countSegments(path: string): number {\n // Check cache first - most paths are repeated\n const cached = this.segmentCountCache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n\n // Count segments manually (fast charCode comparison)\n let segmentCount = 0;\n const pathLen = path.length;\n let inSegment = false;\n\n for (let i = 0; i < pathLen; i++) {\n const char = path.charCodeAt(i);\n if (char === 47) {\n // '/' character\n inSegment = false;\n } else if (!inSegment) {\n inSegment = true;\n segmentCount++;\n }\n }\n\n // Cache result (limit cache size to prevent memory leaks)\n if (this.segmentCountCache.size < this.MAX_SEGMENT_CACHE_SIZE) {\n this.segmentCountCache.set(path, segmentCount);\n }\n\n return segmentCount;\n }\n\n /**\n * Get performance statistics\n */\n static getStats() {\n const totalRequests = this.cacheHits + this.cacheMisses;\n return {\n cacheSize: this.cache.size,\n cacheHits: this.cacheHits,\n cacheMisses: this.cacheMisses,\n hitRate: totalRequests > 0 ? this.cacheHits / totalRequests : 0,\n compilationCount: this.compilationCount,\n };\n }\n\n /**\n * Clear the cache (useful for testing)\n */\n static clearCache(): void {\n this.cache.clear();\n this.segmentCountCache.clear(); // Clear segment count cache too\n this.cacheHits = 0;\n this.cacheMisses = 0;\n }\n\n /**\n * Pre-compile multiple paths (cache warming)\n */\n static precompile(paths: string[]): void {\n const pathsLen = paths.length;\n for (let i = 0; i < pathsLen; i++) {\n this.compile(paths[i] as string);\n }\n }\n}\n\n/**\n * Legacy compatibility function - maps to PathMatcher.compile\n * @deprecated Use PathMatcher.compile instead\n */\nexport function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const compiled = PathMatcher.compile(path);\n return {\n pattern: compiled.pattern || new RegExp(`^${path.replace(/\\//g, '\\\\/')}$`),\n paramNames: compiled.paramNames,\n };\n}\n"]}
@@ -27,4 +27,3 @@ export declare class HookManager extends EventEmitter {
27
27
  removeHook(event: string, fn?: HookFunction): this;
28
28
  getHooks(event?: string): Record<string, any>;
29
29
  }
30
- export { simpleMiddleware as middleware } from '../middleware/index.js';
@@ -316,6 +316,4 @@ export class HookManager extends EventEmitter {
316
316
  return allHooks;
317
317
  }
318
318
  }
319
- // Built-in middleware - now organized in individual files
320
- export { simpleMiddleware as middleware } from '../middleware/index.js';
321
319
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/core/utilities/hooks.ts"],"names":[],"mappings":"AAAA,uBAAuB;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,cAAc,EAAE,gBAAgB;IAChC,aAAa,EAAE,eAAe;IAC9B,eAAe,EAAE,iBAAiB;IAClC,cAAc,EAAE,gBAAgB;IAChC,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,MAAM,OAAO,WAAY,SAAQ,YAAY;IACnC,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC1C,WAAW,GAAG,IAAI,GAAG,EAA0B,CAAC;IAChD,UAAU,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC/C,MAAM,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IAEhD,2BAA2B;IAC3B,4DAA4D;IACpD,YAAY,GAAG,IAAI,GAAG,EAA0D,CAAC;IAEzF,2DAA2D;IACnD,cAAc,GAAG,IAAI,GAAG,EAAmB,CAAC;IAEpD,8EAA8E;IAC9E,gFAAgF;IACxE,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAEzC;QACE,KAAK,EAAE,CAAC;QACR,yBAAyB;QACzB,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QACnD,MAAM,YAAY,GAAG,eAAe,CAAC,MAAM,CAAC;QAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,EAA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1B,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;SAC1B,CAAC,CAAC;QAEH,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,QAAQ,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AAED,0DAA0D;AAC1D,OAAO,EAAE,gBAAgB,IAAI,UAAU,EAAE,MAAM,wBAAwB,CAAC","sourcesContent":["// Hook System for Moro\nimport { EventEmitter } from 'events';\nimport { HookFunction, HookContext } from '../../types/hooks.js';\nimport { createFrameworkLogger } from '../logger/index.js';\n\nexport const HOOK_EVENTS = {\n BEFORE_REQUEST: 'before:request',\n AFTER_REQUEST: 'after:request',\n BEFORE_RESPONSE: 'before:response',\n AFTER_RESPONSE: 'after:response',\n ERROR: 'error',\n} as const;\n\nexport class HookManager extends EventEmitter {\n private hooks = new Map<string, HookFunction[]>();\n private beforeHooks = new Map<string, HookFunction[]>();\n private afterHooks = new Map<string, HookFunction[]>();\n private logger = createFrameworkLogger('Hooks');\n\n // Cached execute functions\n // When no hooks are registered, replace execute() with noop\n private executeCache = new Map<string, (context: HookContext) => Promise<HookContext>>();\n\n // Track if hooks are synchronous to avoid Promise overhead\n private hookSyncStatus = new Map<string, boolean>();\n\n // Events that currently have at least one hook registered - lets callers skip\n // execute() entirely (no context object, no promise) when nothing is registered\n private activeEvents = new Set<string>();\n\n constructor() {\n super();\n // Initialize hook arrays\n const hookEventValues = Object.values(HOOK_EVENTS);\n const hookEventLen = hookEventValues.length;\n for (let i = 0; i < hookEventLen; i++) {\n const event = hookEventValues[i];\n if (event === undefined) continue;\n this.hooks.set(event, []);\n this.beforeHooks.set(event, []);\n this.afterHooks.set(event, []);\n // Initialize with noop functions\n this.updateExecuteCache(event);\n }\n }\n\n // Update cached execute function for an event\n private updateExecuteCache(event: string): void {\n const beforeHooks = this.beforeHooks.get(event) || [];\n const hooks = this.hooks.get(event) || [];\n const afterHooks = this.afterHooks.get(event) || [];\n\n // If no hooks registered, use noop for zero overhead\n if (beforeHooks.length === 0 && hooks.length === 0 && afterHooks.length === 0) {\n this.executeCache.set(event, async (context: HookContext) => context);\n this.hookSyncStatus.set(event, true); // Mark as sync (noop)\n this.activeEvents.delete(event);\n return;\n }\n\n this.activeEvents.add(event);\n\n // Detect if all hooks are synchronous\n const allSync = this.areHooksSynchronous(beforeHooks, hooks, afterHooks);\n this.hookSyncStatus.set(event, allSync);\n\n if (allSync) {\n // FAST PATH: Create synchronous version (no Promise overhead)\n // Cast to Promise return type to satisfy interface\n this.executeCache.set(event, ((context: HookContext) => {\n // Execute before hooks synchronously\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n try {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute main hooks synchronously\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n try {\n const hook = hooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute after hooks synchronously\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n try {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context as any; // Cast to satisfy Promise return\n }) as any);\n } else {\n // SLOW PATH: Use async version only when needed\n this.executeCache.set(event, async (context: HookContext) => {\n // Execute before hooks\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute main hooks\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n const hook = hooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute after hooks\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context;\n });\n }\n }\n\n // Detect if hooks are synchronous by checking function signatures\n private areHooksSynchronous(...hookArrays: HookFunction[][]): boolean {\n for (const hooks of hookArrays) {\n for (const hook of hooks) {\n // Check if function is async or returns a Promise\n if (hook.constructor.name === 'AsyncFunction') {\n return false;\n }\n // Additional heuristic: check if function name suggests async\n if (hook.name && (hook.name.includes('async') || hook.name.includes('Async'))) {\n return false;\n }\n }\n }\n return true; // Assume synchronous by default\n }\n\n // Register a hook for a specific event\n hook(event: string, fn: HookFunction): this {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.hooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register a before hook\n before(event: string, fn: HookFunction): this {\n if (!this.beforeHooks.has(event)) {\n this.beforeHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.beforeHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register an after hook\n after(event: string, fn: HookFunction): this {\n if (!this.afterHooks.has(event)) {\n this.afterHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.afterHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // O(1) check that lets hot paths skip execute() (and its context/promise\n // allocation) entirely when no hooks are registered for an event.\n // Note: EventEmitter listeners attached via .on(event) also count, since the\n // cached executors emit the event after running hooks.\n hasHooks(event: string): boolean {\n return this.activeEvents.has(event) || this.listenerCount(event) > 0;\n }\n\n // Execute hooks for an event - optimized with cached functions\n async execute(event: string, context: HookContext = {}): Promise<HookContext> {\n const executeFn = this.executeCache.get(event);\n if (executeFn) {\n return executeFn(context);\n }\n\n // Fallback for events not in cache (shouldn't happen in normal operation)\n this.updateExecuteCache(event);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.executeCache.get(event)!(context);\n }\n\n // Execute a single hook with error handling\n private async executeHook(hook: HookFunction, context: HookContext): Promise<void> {\n try {\n await hook(context);\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug('Hook attempted to set read-only headersSent property', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n return;\n }\n\n // For other errors, log and re-throw as before\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n throw error;\n }\n }\n\n // Remove hooks\n removeHook(event: string, fn?: HookFunction): this {\n if (!fn) {\n this.hooks.delete(event);\n this.beforeHooks.delete(event);\n this.afterHooks.delete(event);\n } else {\n const maps = [this.hooks, this.beforeHooks, this.afterHooks];\n const mapsLen = maps.length;\n for (let i = 0; i < mapsLen; i++) {\n const map = maps[i];\n if (map === undefined) continue;\n const hooks = map.get(event);\n if (hooks) {\n const index = hooks.indexOf(fn);\n if (index !== -1) {\n hooks.splice(index, 1);\n }\n }\n }\n }\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Get all registered hooks for debugging\n getHooks(event?: string): Record<string, any> {\n if (event) {\n return {\n before: this.beforeHooks.get(event) || [],\n main: this.hooks.get(event) || [],\n after: this.afterHooks.get(event) || [],\n };\n }\n\n const allHooks: Record<string, any> = {};\n const allEvents = new Set([\n ...this.hooks.keys(),\n ...this.beforeHooks.keys(),\n ...this.afterHooks.keys(),\n ]);\n\n allEvents.forEach(event => {\n allHooks[event] = this.getHooks(event);\n });\n\n return allHooks;\n }\n}\n\n// Built-in middleware - now organized in individual files\nexport { simpleMiddleware as middleware } from '../middleware/index.js';\n"]}
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/core/utilities/hooks.ts"],"names":[],"mappings":"AAAA,uBAAuB;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG;I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,CAAC,CAAC;oBAChC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;wBACjB,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,eAAe;QAC/C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,yCAAyC;IACzC,QAAQ,CAAC,KAAc;QACrB,IAAI,KAAK,EAAE,CAAC;YACV,OAAO;gBACL,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;gBACzC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;gBACjC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;aACxC,CAAC;QACJ,CAAC;QAED,MAAM,QAAQ,GAAwB,EAAE,CAAC;QACzC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;YACxB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;YACpB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;YAC1B,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;SAC1B,CAAC,CAAC;QAEH,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,QAAQ,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["// Hook System for Moro\nimport { EventEmitter } from 'events';\nimport { HookFunction, HookContext } from '../../types/hooks.js';\nimport { createFrameworkLogger } from '../logger/index.js';\n\nexport const HOOK_EVENTS = {\n BEFORE_REQUEST: 'before:request',\n AFTER_REQUEST: 'after:request',\n BEFORE_RESPONSE: 'before:response',\n AFTER_RESPONSE: 'after:response',\n ERROR: 'error',\n} as const;\n\nexport class HookManager extends EventEmitter {\n private hooks = new Map<string, HookFunction[]>();\n private beforeHooks = new Map<string, HookFunction[]>();\n private afterHooks = new Map<string, HookFunction[]>();\n private logger = createFrameworkLogger('Hooks');\n\n // Cached execute functions\n // When no hooks are registered, replace execute() with noop\n private executeCache = new Map<string, (context: HookContext) => Promise<HookContext>>();\n\n // Track if hooks are synchronous to avoid Promise overhead\n private hookSyncStatus = new Map<string, boolean>();\n\n // Events that currently have at least one hook registered - lets callers skip\n // execute() entirely (no context object, no promise) when nothing is registered\n private activeEvents = new Set<string>();\n\n constructor() {\n super();\n // Initialize hook arrays\n const hookEventValues = Object.values(HOOK_EVENTS);\n const hookEventLen = hookEventValues.length;\n for (let i = 0; i < hookEventLen; i++) {\n const event = hookEventValues[i];\n if (event === undefined) continue;\n this.hooks.set(event, []);\n this.beforeHooks.set(event, []);\n this.afterHooks.set(event, []);\n // Initialize with noop functions\n this.updateExecuteCache(event);\n }\n }\n\n // Update cached execute function for an event\n private updateExecuteCache(event: string): void {\n const beforeHooks = this.beforeHooks.get(event) || [];\n const hooks = this.hooks.get(event) || [];\n const afterHooks = this.afterHooks.get(event) || [];\n\n // If no hooks registered, use noop for zero overhead\n if (beforeHooks.length === 0 && hooks.length === 0 && afterHooks.length === 0) {\n this.executeCache.set(event, async (context: HookContext) => context);\n this.hookSyncStatus.set(event, true); // Mark as sync (noop)\n this.activeEvents.delete(event);\n return;\n }\n\n this.activeEvents.add(event);\n\n // Detect if all hooks are synchronous\n const allSync = this.areHooksSynchronous(beforeHooks, hooks, afterHooks);\n this.hookSyncStatus.set(event, allSync);\n\n if (allSync) {\n // FAST PATH: Create synchronous version (no Promise overhead)\n // Cast to Promise return type to satisfy interface\n this.executeCache.set(event, ((context: HookContext) => {\n // Execute before hooks synchronously\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n try {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute main hooks synchronously\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n try {\n const hook = hooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute after hooks synchronously\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n try {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context as any; // Cast to satisfy Promise return\n }) as any);\n } else {\n // SLOW PATH: Use async version only when needed\n this.executeCache.set(event, async (context: HookContext) => {\n // Execute before hooks\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute main hooks\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n const hook = hooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute after hooks\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context;\n });\n }\n }\n\n // Detect if hooks are synchronous by checking function signatures\n private areHooksSynchronous(...hookArrays: HookFunction[][]): boolean {\n for (const hooks of hookArrays) {\n for (const hook of hooks) {\n // Check if function is async or returns a Promise\n if (hook.constructor.name === 'AsyncFunction') {\n return false;\n }\n // Additional heuristic: check if function name suggests async\n if (hook.name && (hook.name.includes('async') || hook.name.includes('Async'))) {\n return false;\n }\n }\n }\n return true; // Assume synchronous by default\n }\n\n // Register a hook for a specific event\n hook(event: string, fn: HookFunction): this {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.hooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register a before hook\n before(event: string, fn: HookFunction): this {\n if (!this.beforeHooks.has(event)) {\n this.beforeHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.beforeHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register an after hook\n after(event: string, fn: HookFunction): this {\n if (!this.afterHooks.has(event)) {\n this.afterHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.afterHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // O(1) check that lets hot paths skip execute() (and its context/promise\n // allocation) entirely when no hooks are registered for an event.\n // Note: EventEmitter listeners attached via .on(event) also count, since the\n // cached executors emit the event after running hooks.\n hasHooks(event: string): boolean {\n return this.activeEvents.has(event) || this.listenerCount(event) > 0;\n }\n\n // Execute hooks for an event - optimized with cached functions\n async execute(event: string, context: HookContext = {}): Promise<HookContext> {\n const executeFn = this.executeCache.get(event);\n if (executeFn) {\n return executeFn(context);\n }\n\n // Fallback for events not in cache (shouldn't happen in normal operation)\n this.updateExecuteCache(event);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.executeCache.get(event)!(context);\n }\n\n // Execute a single hook with error handling\n private async executeHook(hook: HookFunction, context: HookContext): Promise<void> {\n try {\n await hook(context);\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug('Hook attempted to set read-only headersSent property', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n return;\n }\n\n // For other errors, log and re-throw as before\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n throw error;\n }\n }\n\n // Remove hooks\n removeHook(event: string, fn?: HookFunction): this {\n if (!fn) {\n this.hooks.delete(event);\n this.beforeHooks.delete(event);\n this.afterHooks.delete(event);\n } else {\n const maps = [this.hooks, this.beforeHooks, this.afterHooks];\n const mapsLen = maps.length;\n for (let i = 0; i < mapsLen; i++) {\n const map = maps[i];\n if (map === undefined) continue;\n const hooks = map.get(event);\n if (hooks) {\n const index = hooks.indexOf(fn);\n if (index !== -1) {\n hooks.splice(index, 1);\n }\n }\n }\n }\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Get all registered hooks for debugging\n getHooks(event?: string): Record<string, any> {\n if (event) {\n return {\n before: this.beforeHooks.get(event) || [],\n main: this.hooks.get(event) || [],\n after: this.afterHooks.get(event) || [],\n };\n }\n\n const allHooks: Record<string, any> = {};\n const allEvents = new Set([\n ...this.hooks.keys(),\n ...this.beforeHooks.keys(),\n ...this.afterHooks.keys(),\n ]);\n\n allEvents.forEach(event => {\n allHooks[event] = this.getHooks(event);\n });\n\n return allHooks;\n }\n}\n"]}
@@ -3,6 +3,5 @@ export { CircuitBreaker } from './circuit-breaker.js';
3
3
  export { HookManager, HOOK_EVENTS } from './hooks.js';
4
4
  export { isPackageAvailable, resolveUserPackage, createUserRequire } from './package-utils.js';
5
5
  export { buildModuleBasePath } from './module-path.js';
6
- export { middleware } from './hooks.js';
7
6
  export { response, ResponseBuilder } from './response-helpers.js';
8
7
  export type { ApiSuccessResponse, ApiErrorResponse, ApiResponse, ValidationErrorDetail as ResponseValidationErrorDetail, } from './response-helpers.js';
@@ -4,8 +4,6 @@ export { CircuitBreaker } from './circuit-breaker.js';
4
4
  export { HookManager, HOOK_EVENTS } from './hooks.js';
5
5
  export { isPackageAvailable, resolveUserPackage, createUserRequire } from './package-utils.js';
6
6
  export { buildModuleBasePath } from './module-path.js';
7
- // Re-export middleware from hooks
8
- export { middleware } from './hooks.js';
9
7
  // Standardized Response Helpers (namespace object only to avoid polluting global exports)
10
8
  export { response, ResponseBuilder } from './response-helpers.js';
11
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/utilities/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,SAAS,EACT,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC/F,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,kCAAkC;AAClC,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["// Core Utilities - Centralized Exports\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n} from './container.js';\nexport { CircuitBreaker } from './circuit-breaker.js';\nexport { HookManager, HOOK_EVENTS } from './hooks.js';\nexport { isPackageAvailable, resolveUserPackage, createUserRequire } from './package-utils.js';\nexport { buildModuleBasePath } from './module-path.js';\n\n// Re-export middleware from hooks\nexport { middleware } from './hooks.js';\n\n// Standardized Response Helpers (namespace object only to avoid polluting global exports)\nexport { response, ResponseBuilder } from './response-helpers.js';\n\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ValidationErrorDetail as ResponseValidationErrorDetail,\n} from './response-helpers.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/utilities/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,SAAS,EACT,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC/F,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["// Core Utilities - Centralized Exports\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n} from './container.js';\nexport { CircuitBreaker } from './circuit-breaker.js';\nexport { HookManager, HOOK_EVENTS } from './hooks.js';\nexport { isPackageAvailable, resolveUserPackage, createUserRequire } from './package-utils.js';\nexport { buildModuleBasePath } from './module-path.js';\n\n// Standardized Response Helpers (namespace object only to avoid polluting global exports)\nexport { response, ResponseBuilder } from './response-helpers.js';\n\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ValidationErrorDetail as ResponseValidationErrorDetail,\n} from './response-helpers.js';\n"]}