@morojs/moro 1.8.12 → 1.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +4 -2
  2. package/dist/core/cluster/thread-cluster.d.ts +25 -0
  3. package/dist/core/cluster/thread-cluster.js +95 -3
  4. package/dist/core/cluster/thread-cluster.js.map +1 -1
  5. package/dist/core/config/config-validator.js +15 -0
  6. package/dist/core/config/config-validator.js.map +1 -1
  7. package/dist/core/config/index.js +19 -2
  8. package/dist/core/config/index.js.map +1 -1
  9. package/dist/core/framework.d.ts +26 -0
  10. package/dist/core/framework.js +195 -6
  11. package/dist/core/framework.js.map +1 -1
  12. package/dist/core/http/http-server.d.ts +17 -0
  13. package/dist/core/http/http-server.js +21 -1
  14. package/dist/core/http/http-server.js.map +1 -1
  15. package/dist/core/http/http2-server.d.ts +13 -0
  16. package/dist/core/http/http2-server.js +11 -0
  17. package/dist/core/http/http2-server.js.map +1 -1
  18. package/dist/core/http/moro-engine-server.d.ts +28 -0
  19. package/dist/core/http/moro-engine-server.js +115 -11
  20. package/dist/core/http/moro-engine-server.js.map +1 -1
  21. package/dist/core/http/utils/body-type.d.ts +12 -0
  22. package/dist/core/http/utils/body-type.js +70 -0
  23. package/dist/core/http/utils/body-type.js.map +1 -0
  24. package/dist/core/http/utils/ssl-config.d.ts +11 -0
  25. package/dist/core/http/utils/ssl-config.js +3 -0
  26. package/dist/core/http/utils/ssl-config.js.map +1 -1
  27. package/dist/core/http/utils/uws-worker-clustering.js +5 -4
  28. package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
  29. package/dist/core/http/uws-http-server.d.ts +3 -0
  30. package/dist/core/http/uws-http-server.js +22 -1
  31. package/dist/core/http/uws-http-server.js.map +1 -1
  32. package/dist/core/middleware/built-in/body-parsers/index.d.ts +18 -0
  33. package/dist/core/middleware/built-in/body-parsers/index.js +41 -0
  34. package/dist/core/middleware/built-in/body-parsers/index.js.map +1 -1
  35. package/dist/core/middleware/built-in/cache/adapters/cache/redis.d.ts +32 -8
  36. package/dist/core/middleware/built-in/cache/adapters/cache/redis.js +117 -25
  37. package/dist/core/middleware/built-in/cache/adapters/cache/redis.js.map +1 -1
  38. package/dist/core/middleware/built-in/compression/core.js +5 -0
  39. package/dist/core/middleware/built-in/compression/core.js.map +1 -1
  40. package/dist/core/middleware/built-in/session/core.d.ts +1 -0
  41. package/dist/core/middleware/built-in/session/core.js.map +1 -1
  42. package/dist/core/middleware/built-in/static/core.d.ts +18 -0
  43. package/dist/core/middleware/built-in/static/core.js +128 -7
  44. package/dist/core/middleware/built-in/static/core.js.map +1 -1
  45. package/dist/core/networking/adapters/engine-adapter.d.ts +2 -2
  46. package/dist/core/networking/adapters/engine-adapter.js +40 -1
  47. package/dist/core/networking/adapters/engine-adapter.js.map +1 -1
  48. package/dist/core/networking/adapters/socketio-adapter.d.ts +2 -2
  49. package/dist/core/networking/adapters/socketio-adapter.js +10 -1
  50. package/dist/core/networking/adapters/socketio-adapter.js.map +1 -1
  51. package/dist/core/networking/adapters/uws-adapter.d.ts +2 -2
  52. package/dist/core/networking/adapters/uws-adapter.js +54 -3
  53. package/dist/core/networking/adapters/uws-adapter.js.map +1 -1
  54. package/dist/core/networking/adapters/ws-adapter.d.ts +9 -2
  55. package/dist/core/networking/adapters/ws-adapter.js +97 -12
  56. package/dist/core/networking/adapters/ws-adapter.js.map +1 -1
  57. package/dist/core/networking/websocket-adapter.d.ts +19 -1
  58. package/dist/core/networking/websocket-adapter.js.map +1 -1
  59. package/dist/core/routing/index.d.ts +12 -8
  60. package/dist/core/routing/index.js +7 -2
  61. package/dist/core/routing/index.js.map +1 -1
  62. package/dist/core/routing/unified-router.d.ts +46 -8
  63. package/dist/core/routing/unified-router.js +108 -32
  64. package/dist/core/routing/unified-router.js.map +1 -1
  65. package/dist/core/utilities/package-utils.d.ts +7 -0
  66. package/dist/core/utilities/package-utils.js +2 -0
  67. package/dist/core/utilities/package-utils.js.map +1 -1
  68. package/dist/core/workers/worker-manager.js +2 -2
  69. package/dist/core/workers/worker-manager.js.map +1 -1
  70. package/dist/index.d.ts +4 -3
  71. package/dist/index.js +2 -1
  72. package/dist/index.js.map +1 -1
  73. package/dist/moro.d.ts +12 -1
  74. package/dist/moro.js +63 -7
  75. package/dist/moro.js.map +1 -1
  76. package/dist/types/cache.d.ts +2 -0
  77. package/dist/types/cache.js.map +1 -1
  78. package/dist/types/config.d.ts +9 -0
  79. package/dist/types/config.js.map +1 -1
  80. package/dist/types/http.d.ts +6 -0
  81. package/dist/types/http.js.map +1 -1
  82. package/dist/types/session.d.ts +1 -0
  83. package/dist/types/session.js.map +1 -1
  84. package/package.json +1 -1
@@ -58,6 +58,9 @@ export interface EngineCapabilities {
58
58
  responseLimits: boolean;
59
59
  /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */
60
60
  tlsPolicy: boolean;
61
+ /** updateSsl(serverId, ssl) exists: certificate rotation without a restart
62
+ * (engine >= 1.1.8). Gates app.reloadTLS() on the engine. */
63
+ tlsReload: boolean;
61
64
  /** setStaticRoute()/clearStaticRoutes() exist. Used for a literal body
62
65
  * given to the route builder's .handler() when the route has nothing
63
66
  * else configured, because a static route bypasses middleware, hooks,
@@ -82,6 +85,10 @@ export interface EngineCapabilities {
82
85
  * and microtasks queued during dispatch run when the callback returns;
83
86
  * the adapter then needs no drain of its own (engine > 1.1.6). */
84
87
  callbackScope: boolean;
88
+ /** setParamRoute()/clearParamRoutes() exist (engine >= 1.1.9): a route
89
+ * with one variable path segment, echoed as the body, answered inside the
90
+ * engine. Used for param(name) handlers on bare routes. */
91
+ paramRoutes: boolean;
85
92
  /** I/O transport in use ('uv', 'uring'), when the engine reports it. */
86
93
  transport?: string;
87
94
  }
@@ -77,6 +77,7 @@ const CAP_KEYS = [
77
77
  'wsDeflate',
78
78
  'responseLimits',
79
79
  'tlsPolicy',
80
+ 'tlsReload',
80
81
  'staticRoutes',
81
82
  'responseTemplates',
82
83
  'asyncNotify',
@@ -84,6 +85,7 @@ const CAP_KEYS = [
84
85
  'fastCalls',
85
86
  'callbackScope',
86
87
  'batchDispatch',
88
+ 'paramRoutes',
87
89
  ];
88
90
  const NO_CAPABILITIES = Object.freeze(Object.fromEntries(CAP_KEYS.map(k => [k, false])));
89
91
  const capabilitiesCache = new WeakMap();
@@ -1 +1 @@
1
- {"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,2EAA2E;AAE3E,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;QACvE,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;IACvE,OAAO,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB;IAC/B,OAAO,aAAa,CA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AC9B,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,EAC/B,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,qDAAqD;IACrD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;IACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.1.x). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (reserved). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate. */\n wsDeflate: boolean;\n /** responseTimeoutMs / responseBackpressureLimit / maxUriSize are parsed. */\n responseLimits: boolean;\n /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */\n tlsPolicy: boolean;\n /** setStaticRoute()/clearStaticRoutes() exist. Used for a literal body\n * given to the route builder's .handler() when the route has nothing\n * else configured, because a static route bypasses middleware, hooks,\n * auth and validation by design. */\n staticRoutes: boolean;\n /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()\n * exist (engine >= 1.1.6): the adapter replays prepared header blocks for\n * the responses it emits itself. */\n responseTemplates: boolean;\n /** onAborted/onWritable are delivered on a later loop turn, never from\n * inside respond()/write()/end() (engine >= 1.1.6). */\n asyncNotify: boolean;\n /** A server left open at environment teardown is closed by the engine's\n * cleanup hook, so the engine may run inside worker threads that can be\n * terminate()d (engine >= 1.1.6). Gates thread-based clustering. */\n workerThreads: boolean;\n /** V8 fast API calls are installed on the hot entry points (informational). */\n fastCalls: boolean;\n /** Batched pipelined dispatch (onRequestBatch / getBatchBuffers / getPath). */\n batchDispatch: boolean;\n /** Every callback into JS runs inside a Node callback scope, so nextTicks\n * and microtasks queued during dispatch run when the callback returns;\n * the adapter then needs no drain of its own (engine > 1.1.6). */\n callbackScope: boolean;\n /** I/O transport in use ('uv', 'uring'), when the engine reports it. */\n transport?: string;\n}\n\n// One place to name every boolean flag: getEngineCapabilities coerces each\n// with `=== true`, and NO_CAPABILITIES is derived from the same list, so a\n// flag added here can never be read on one path and forgotten on the other.\nconst CAP_KEYS = [\n 'limits',\n 'tls',\n 'http2',\n 'wsDeflate',\n 'responseLimits',\n 'tlsPolicy',\n 'staticRoutes',\n 'responseTemplates',\n 'asyncNotify',\n 'workerThreads',\n 'fastCalls',\n 'callbackScope',\n 'batchDispatch',\n] as const;\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = Object.freeze(\n Object.fromEntries(CAP_KEYS.map(k => [k, false]))\n) as unknown as EngineCapabilities;\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n const next: Record<string, boolean | string> = {};\n for (const key of CAP_KEYS) next[key] = c[key] === true;\n if (typeof probe.transport === 'string') next.transport = probe.transport;\n caps = next as unknown as EngineCapabilities;\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
1
+ {"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,2EAA2E;AAE3E,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAmB;IACpD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC;QACvE,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,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M,UAAU,iCAAiC;IAC/C,YAAY,GAAG,SAAS,CAAC;IACzB,gBAAgB,GAAG,EAAE,CAAC;AACxB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAgB;IAClD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,0EAA0E;IAC1E,IACE,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,EAC/B,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,qDAAqD;IACrD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;IACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.1.x). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (reserved). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate. */\n wsDeflate: boolean;\n /** responseTimeoutMs / responseBackpressureLimit / maxUriSize are parsed. */\n responseLimits: boolean;\n /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */\n tlsPolicy: boolean;\n /** updateSsl(serverId, ssl) exists: certificate rotation without a restart\n * (engine >= 1.1.8). Gates app.reloadTLS() on the engine. */\n tlsReload: boolean;\n /** setStaticRoute()/clearStaticRoutes() exist. Used for a literal body\n * given to the route builder's .handler() when the route has nothing\n * else configured, because a static route bypasses middleware, hooks,\n * auth and validation by design. */\n staticRoutes: boolean;\n /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()\n * exist (engine >= 1.1.6): the adapter replays prepared header blocks for\n * the responses it emits itself. */\n responseTemplates: boolean;\n /** onAborted/onWritable are delivered on a later loop turn, never from\n * inside respond()/write()/end() (engine >= 1.1.6). */\n asyncNotify: boolean;\n /** A server left open at environment teardown is closed by the engine's\n * cleanup hook, so the engine may run inside worker threads that can be\n * terminate()d (engine >= 1.1.6). Gates thread-based clustering. */\n workerThreads: boolean;\n /** V8 fast API calls are installed on the hot entry points (informational). */\n fastCalls: boolean;\n /** Batched pipelined dispatch (onRequestBatch / getBatchBuffers / getPath). */\n batchDispatch: boolean;\n /** Every callback into JS runs inside a Node callback scope, so nextTicks\n * and microtasks queued during dispatch run when the callback returns;\n * the adapter then needs no drain of its own (engine > 1.1.6). */\n callbackScope: boolean;\n /** setParamRoute()/clearParamRoutes() exist (engine >= 1.1.9): a route\n * with one variable path segment, echoed as the body, answered inside the\n * engine. Used for param(name) handlers on bare routes. */\n paramRoutes: boolean;\n /** I/O transport in use ('uv', 'uring'), when the engine reports it. */\n transport?: string;\n}\n\n// One place to name every boolean flag: getEngineCapabilities coerces each\n// with `=== true`, and NO_CAPABILITIES is derived from the same list, so a\n// flag added here can never be read on one path and forgotten on the other.\nconst CAP_KEYS = [\n 'limits',\n 'tls',\n 'http2',\n 'wsDeflate',\n 'responseLimits',\n 'tlsPolicy',\n 'tlsReload',\n 'staticRoutes',\n 'responseTemplates',\n 'asyncNotify',\n 'workerThreads',\n 'fastCalls',\n 'callbackScope',\n 'batchDispatch',\n 'paramRoutes',\n] as const;\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = Object.freeze(\n Object.fromEntries(CAP_KEYS.map(k => [k, false]))\n) as unknown as EngineCapabilities;\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n const next: Record<string, boolean | string> = {};\n for (const key of CAP_KEYS) next[key] = c[key] === true;\n if (typeof probe.transport === 'string') next.transport = probe.transport;\n caps = next as unknown as EngineCapabilities;\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
@@ -2,7 +2,7 @@ import { requireBuiltin } from '../utilities/builtin.js';
2
2
  // worker_threads on first use (core/utilities/builtin.ts).
3
3
  const wt = () => requireBuiltin('worker_threads');
4
4
  import { createFrameworkLogger } from '../logger/index.js';
5
- import { cpus } from 'os';
5
+ import { usableCpuCount } from '../cluster/thread-cluster.js';
6
6
  import { isPackageAvailable } from '../utilities/package-utils.js';
7
7
  // WORKER_ENTRY resolves to worker.js, this file's compiled sibling in dist/**,
8
8
  // via import.meta in ./worker-entry.js. That ESM-only syntax is isolated in its
@@ -51,7 +51,7 @@ export class WorkerManager {
51
51
  handledFailures = new WeakSet();
52
52
  poolFailed = false;
53
53
  constructor(options = {}) {
54
- this.workerCount = options.workerCount || Math.max(1, cpus().length - 1); // Leave 1 core for main thread
54
+ this.workerCount = options.workerCount || Math.max(1, usableCpuCount() - 1); // Leave 1 core for main thread
55
55
  this.maxQueueSize = options.maxQueueSize || 1000;
56
56
  this.maxRestartAttempts = options.maxRestartAttempts ?? 10;
57
57
  this.restartBackoffMs = options.restartBackoffMs ?? 100;
@@ -1 +1 @@
1
- {"version":3,"file":"worker-manager.js","sourceRoot":"","sources":["../../../src/core/workers/worker-manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,2DAA2D;AAC3D,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,cAAc,CAAkC,gBAAgB,CAAC,CAAC;AACnF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,+EAA+E;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,sBAAsB;AACtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,cAAc,CAAC,CAAC;AAExD,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AAEtD,iDAAiD;AACjD,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,oFAAoF;AACpF,MAAM,cAAc,GAA2B,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG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AAQ,EAAE,EAAE;YACnD,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["// Worker Thread Manager - Offload CPU-intensive operations\nimport type { Worker } from 'worker_threads';\nimport { requireBuiltin } from '../utilities/builtin.js';\n\n// worker_threads on first use (core/utilities/builtin.ts).\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { cpus } from 'os';\nimport { isPackageAvailable } from '../utilities/package-utils.js';\n// WORKER_ENTRY resolves to worker.js, this file's compiled sibling in dist/**,\n// via import.meta in ./worker-entry.js. That ESM-only syntax is isolated in its\n// own module (mapped to a stub in jest.config) so importing WorkerManager under\n// ts-jest's CommonJS transform never hits a load-time import.meta SyntaxError.\nimport { WORKER_ENTRY } from './worker-entry.js';\n\n// Optional JWT import\nconst jwtAvailable = isPackageAvailable('jsonwebtoken');\n\nconst logger = createFrameworkLogger('WorkerManager');\n\n// Upper bound on the exponential restart backoff\nconst MAX_RESTART_BACKOFF_MS = 5000;\n\n// Hoisted constants — avoids object allocation inside sort comparator on every call\nconst PRIORITY_ORDER: Record<string, number> = { high: 3, normal: 2, low: 1 };\n\n// Simple counter for task IDs — avoids expensive crypto.randomBytes for non-security IDs\nlet taskIdCounter = 0;\n\n/**\n * Worker task definitions\n */\nexport interface WorkerTask {\n id: string;\n type: string;\n data: any;\n priority?: 'low' | 'normal' | 'high';\n timeout?: number;\n}\n\n/**\n * Worker result\n */\nexport interface WorkerResult {\n taskId: string;\n success: boolean;\n data?: any;\n error?: string;\n executionTime: number;\n}\n\n/**\n * Active task tracking\n */\ninterface ActiveTask {\n resolve: CallableFunction;\n reject: CallableFunction;\n timeout: NodeJS.Timeout | null;\n // The worker a task was dispatched to (set once it leaves the queue). Used so a\n // crashed worker only rejects its own in-flight tasks, not everyone else's.\n assignedWorker?: Worker;\n}\n\n/**\n * Built-in worker tasks\n */\nexport const WORKER_TASKS = {\n JWT_VERIFY: 'jwt:verify',\n JWT_SIGN: 'jwt:sign',\n CRYPTO_HASH: 'crypto:hash',\n CRYPTO_ENCRYPT: 'crypto:encrypt',\n CRYPTO_DECRYPT: 'crypto:decrypt',\n DATA_COMPRESS: 'data:compress',\n DATA_DECOMPRESS: 'data:decompress',\n IMAGE_PROCESS: 'image:process',\n HEAVY_COMPUTATION: 'computation:heavy',\n JSON_TRANSFORM: 'json:transform',\n} as const;\n\n/**\n * Worker Thread Manager\n * Manages a pool of worker threads for CPU-intensive operations\n */\nexport class WorkerManager {\n private workers: Map<number, Worker> = new Map();\n private taskQueue: WorkerTask[] = [];\n private activeTasks: Map<string, ActiveTask> = new Map();\n private workerCount: number;\n private maxQueueSize: number;\n private isShuttingDown = false;\n private maxRestartAttempts: number;\n private restartBackoffMs: number;\n private restartAttempts = 0;\n private restartTimers = new Set<NodeJS.Timeout>();\n private handledFailures = new WeakSet<Worker>();\n private poolFailed = false;\n\n constructor(\n options: {\n workerCount?: number;\n maxQueueSize?: number;\n maxRestartAttempts?: number;\n restartBackoffMs?: number;\n } = {}\n ) {\n this.workerCount = options.workerCount || Math.max(1, cpus().length - 1); // Leave 1 core for main thread\n this.maxQueueSize = options.maxQueueSize || 1000;\n this.maxRestartAttempts = options.maxRestartAttempts ?? 10;\n this.restartBackoffMs = options.restartBackoffMs ?? 100;\n\n this.initializeWorkers();\n }\n\n /**\n * Initialize worker threads\n */\n private initializeWorkers(): void {\n for (let i = 0; i < this.workerCount; i++) {\n this.createWorker();\n }\n\n logger.info(`Initialized ${this.workerCount} worker threads`, 'WorkerInit', {\n totalWorkers: this.workerCount,\n maxQueueSize: this.maxQueueSize,\n });\n }\n\n /**\n * Create a single worker thread\n */\n private createWorker(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n let worker: Worker;\n try {\n worker = new (wt().Worker)(WORKER_ENTRY, {\n workerData: { type: 'worker' },\n });\n } catch (error) {\n // Spawning can fail synchronously (e.g. a missing entry file). Treat it the\n // same as a runtime failure so we back off instead of throwing.\n logger.error('Failed to spawn worker thread', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n this.scheduleRestart();\n return;\n }\n\n worker.on('message', (result: WorkerResult) => {\n // A successful message proves the pool is healthy; reset the restart budget.\n this.restartAttempts = 0;\n this.handleWorkerResult(result);\n });\n\n worker.on('error', error => {\n logger.error('Worker thread error', 'WorkerError', { error: error.message });\n this.handleWorkerFailure(worker);\n });\n\n worker.on('exit', code => {\n if (code !== 0 && !this.isShuttingDown) {\n logger.warn(`Worker exited with code ${code}, restarting`, 'WorkerExit');\n this.handleWorkerFailure(worker);\n }\n });\n\n this.workers.set(worker.threadId, worker);\n logger.debug(`Created worker thread ${worker.threadId}`, 'WorkerCreate');\n }\n\n /**\n * Handle a crashed worker: reject only the tasks that were assigned to it and\n * schedule a backed-off restart. A failed worker emits both 'error' and 'exit',\n * so this is guarded to run at most once per worker.\n */\n private handleWorkerFailure(worker: Worker): void {\n if (this.handledFailures.has(worker)) {\n return;\n }\n this.handledFailures.add(worker);\n\n this.workers.delete(worker.threadId);\n\n if (this.isShuttingDown) {\n return;\n }\n\n // Reject only the tasks that were dispatched to this specific worker. Tasks\n // still queued (or running on other workers) are intentionally left alone.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.assignedWorker === worker) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker thread failed'));\n this.activeTasks.delete(taskId);\n }\n }\n\n this.scheduleRestart();\n }\n\n /**\n * Schedule a replacement worker with exponential backoff, capping the number of\n * consecutive restart attempts so a persistently broken worker entry can never\n * spin into an unbounded restart loop.\n */\n private scheduleRestart(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n this.restartAttempts++;\n\n if (this.restartAttempts > this.maxRestartAttempts) {\n this.failPool();\n return;\n }\n\n const delay = Math.min(\n this.restartBackoffMs * 2 ** (this.restartAttempts - 1),\n MAX_RESTART_BACKOFF_MS\n );\n\n logger.warn(\n `Scheduling worker restart in ${delay}ms (attempt ${this.restartAttempts}/${this.maxRestartAttempts})`,\n 'WorkerRestart'\n );\n\n const timer = setTimeout(() => {\n this.restartTimers.delete(timer);\n this.createWorker();\n }, delay);\n\n // Don't keep the process alive purely for a pending restart\n timer.unref();\n this.restartTimers.add(timer);\n }\n\n /**\n * Give up after too many failed restarts: fail every outstanding task cleanly\n * (rejecting their promises) instead of looping forever.\n */\n private failPool(): void {\n if (this.poolFailed) {\n return;\n }\n this.poolFailed = true;\n\n logger.error(\n `Worker pool failed to recover after ${this.maxRestartAttempts} restart attempts`,\n 'WorkerPoolFailed'\n );\n\n const error = new Error(\n `Worker pool is unavailable after ${this.maxRestartAttempts} failed restart attempts`\n );\n\n // Every queued task also has an activeTasks entry, so this rejects both\n // in-flight and queued work.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(error);\n this.activeTasks.delete(taskId);\n }\n\n this.taskQueue.length = 0;\n }\n\n /**\n * Execute a task on a worker thread\n */\n async executeTask<T = any>(task: WorkerTask): Promise<T> {\n if (this.isShuttingDown) {\n throw new Error('Worker manager is shutting down');\n }\n\n if (this.poolFailed) {\n throw new Error('Worker pool is unavailable (too many worker failures)');\n }\n\n return new Promise<T>((resolve, reject) => {\n // Check queue size limit\n if (this.taskQueue.length >= this.maxQueueSize) {\n reject(new Error('Worker queue is full'));\n return;\n }\n\n // Add to queue\n this.taskQueue.push(task);\n\n // Set up promise handlers\n const timeout = task.timeout\n ? setTimeout(() => {\n this.activeTasks.delete(task.id);\n reject(new Error(`Task ${task.id} timed out`));\n }, task.timeout)\n : null;\n\n // Don't keep process alive for worker timeouts\n if (timeout) {\n timeout.unref();\n }\n\n this.activeTasks.set(task.id, { resolve, reject, timeout });\n\n // Try to assign task to available worker\n this.processQueue();\n });\n }\n\n /**\n * Process the task queue\n */\n private processQueue(): void {\n // Sort queue by priority (high first)\n this.taskQueue.sort(\n (a, b) =>\n (PRIORITY_ORDER[b.priority || 'normal'] ?? 0) -\n (PRIORITY_ORDER[a.priority || 'normal'] ?? 0)\n );\n\n // Assign tasks to available workers\n for (const [threadId, worker] of this.workers.entries()) {\n if (this.taskQueue.length === 0) break;\n\n // Check if worker is available (not currently processing)\n // For simplicity, we'll send tasks and let workers handle queuing\n const task = this.taskQueue.shift();\n if (task) {\n // Record the assignment so a crashed worker only rejects its own tasks.\n const taskInfo = this.activeTasks.get(task.id);\n if (taskInfo) {\n taskInfo.assignedWorker = worker;\n }\n worker.postMessage(task);\n logger.debug(`Assigned task ${task.id} to worker ${threadId}`, 'TaskAssigned');\n }\n }\n }\n\n /**\n * Handle result from worker thread\n */\n private handleWorkerResult(result: WorkerResult): void {\n const taskInfo = this.activeTasks.get(result.taskId);\n if (!taskInfo) {\n logger.warn(`Received result for unknown task ${result.taskId}`, 'UnknownTaskResult');\n return;\n }\n\n // Clear timeout\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n\n // Remove from active tasks\n this.activeTasks.delete(result.taskId);\n\n // Handle result\n if (result.success) {\n logger.debug(`Task ${result.taskId} completed in ${result.executionTime}ms`, 'TaskCompleted');\n taskInfo.resolve(result.data);\n } else {\n logger.error(`Task ${result.taskId} failed: ${result.error}`, 'TaskFailed');\n taskInfo.reject(new Error(result.error || 'Task failed'));\n }\n\n // Process next task in queue\n this.processQueue();\n }\n\n /**\n * Shutdown all workers\n */\n async shutdown(): Promise<void> {\n this.isShuttingDown = true;\n\n // Cancel any pending worker restarts\n for (const timer of this.restartTimers) {\n clearTimeout(timer);\n }\n this.restartTimers.clear();\n\n // Reject all pending tasks\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker manager shutting down'));\n }\n\n // Terminate all workers\n const shutdownPromises = Array.from(this.workers.values()).map(\n worker =>\n new Promise<void>(resolve => {\n worker.once('exit', () => resolve());\n void worker.terminate();\n })\n );\n\n await Promise.all(shutdownPromises);\n this.workers.clear();\n this.activeTasks.clear();\n this.taskQueue.length = 0;\n\n logger.info('Worker manager shutdown complete', 'WorkerShutdown');\n }\n\n /**\n * Get worker statistics\n */\n getStats() {\n return {\n workerCount: this.workers.size,\n activeTasks: this.activeTasks.size,\n queuedTasks: this.taskQueue.length,\n isShuttingDown: this.isShuttingDown,\n };\n }\n}\n\n// Singleton instance\nlet workerManagerInstance: WorkerManager | null = null;\n\n/**\n * Get or create the worker manager instance\n */\nexport function getWorkerManager(options?: {\n workerCount?: number;\n maxQueueSize?: number;\n}): WorkerManager {\n if (!workerManagerInstance) {\n workerManagerInstance = new WorkerManager(options);\n }\n return workerManagerInstance;\n}\n\n/**\n * Execute task on worker thread (convenience function)\n */\nexport async function executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n const manager = getWorkerManager();\n return manager.executeTask<T>(task);\n}\n\n/**\n * Built-in task helpers\n */\nexport const workerTasks = {\n /**\n * JWT verification (CPU-intensive)\n */\n async verifyJWT(token: string, secret: string, options?: any): Promise<any> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT verification requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-verify-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_VERIFY,\n data: { token, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * JWT signing (CPU-intensive)\n */\n async signJWT(payload: any, secret: string, options?: any): Promise<string> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT signing requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-sign-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_SIGN,\n data: { payload, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * Crypto hash (CPU-intensive)\n */\n async hash(data: string, algorithm = 'sha256'): Promise<string> {\n return executeOnWorker({\n id: `crypto-hash-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.CRYPTO_HASH,\n data: { data, algorithm },\n priority: 'normal',\n timeout: 10000,\n });\n },\n\n /**\n * Data compression (CPU-intensive for large payloads)\n */\n async compress(\n data: string | Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-compress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_COMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n // Buffers cross the thread boundary as plain Uint8Array\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Data decompression (CPU-intensive for large payloads)\n */\n async decompress(\n data: Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-decompress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_DECOMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Heavy computation example\n */\n async heavyComputation(data: any): Promise<any> {\n return executeOnWorker({\n id: `computation-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.HEAVY_COMPUTATION,\n data,\n priority: 'normal',\n timeout: 30000,\n });\n },\n\n /**\n * JSON transformation (can be CPU-intensive for large objects)\n */\n async transformJSON(data: any, transformer: (data: any) => any): Promise<any> {\n return executeOnWorker({\n id: `json-transform-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JSON_TRANSFORM,\n data: { data, transformer: transformer.toString() },\n priority: 'normal',\n timeout: 15000,\n });\n },\n};\n"]}
1
+ {"version":3,"file":"worker-manager.js","sourceRoot":"","sources":["../../../src/core/workers/worker-manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,2DAA2D;AAC3D,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,cAAc,CAAkC,gBAAgB,CAAC,CAAC;AACnF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,+EAA+E;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,sBAAsB;AACtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,cAAc,CAAC,CAAC;AAExD,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AAEtD,iDAAiD;AACjD,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,oFAAoF;AACpF,MAAM,cAAc,GAA2B,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;AAE9E,yFAAyF;AACzF,IAAI,aAAa,GAAG,CAAC,CAAC;AAoCtB;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;IAChC,aAAa,EAAE,eAAe;IAC9B,eAAe,EAAE,iBAAiB;IAClC,aAAa,EAAE,eAAe;IAC9B,iBAAiB,EAAE,mBAAmB;IACtC,cAAc,EAAE,gBAAgB;CACxB,CAAC;AAEX;;;GAGG;AAC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AAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,MAAM,EAAE;YACxD,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAChE,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,gBAAgB,CAAC,IAAS;QAC9B,OAAO,eAAe,CAAC;YACrB,EAAE,EAAE,eAAe,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE;YAClD,IAAI,EAAE,YAAY,CAAC,iBAAiB;YACpC,IAAI;YACJ,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,IAAS,EAAE,WAA+B;QAC5D,OAAO,eAAe,CAAC;YACrB,EAAE,EAAE,kBAAkB,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE;YACrD,IAAI,EAAE,YAAY,CAAC,cAAc;YACjC,IAAI,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE,EAAE;YACnD,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["// Worker Thread Manager - Offload CPU-intensive operations\nimport type { Worker } from 'worker_threads';\nimport { requireBuiltin } from '../utilities/builtin.js';\n\n// worker_threads on first use (core/utilities/builtin.ts).\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { usableCpuCount } from '../cluster/thread-cluster.js';\nimport { isPackageAvailable } from '../utilities/package-utils.js';\n// WORKER_ENTRY resolves to worker.js, this file's compiled sibling in dist/**,\n// via import.meta in ./worker-entry.js. That ESM-only syntax is isolated in its\n// own module (mapped to a stub in jest.config) so importing WorkerManager under\n// ts-jest's CommonJS transform never hits a load-time import.meta SyntaxError.\nimport { WORKER_ENTRY } from './worker-entry.js';\n\n// Optional JWT import\nconst jwtAvailable = isPackageAvailable('jsonwebtoken');\n\nconst logger = createFrameworkLogger('WorkerManager');\n\n// Upper bound on the exponential restart backoff\nconst MAX_RESTART_BACKOFF_MS = 5000;\n\n// Hoisted constants — avoids object allocation inside sort comparator on every call\nconst PRIORITY_ORDER: Record<string, number> = { high: 3, normal: 2, low: 1 };\n\n// Simple counter for task IDs — avoids expensive crypto.randomBytes for non-security IDs\nlet taskIdCounter = 0;\n\n/**\n * Worker task definitions\n */\nexport interface WorkerTask {\n id: string;\n type: string;\n data: any;\n priority?: 'low' | 'normal' | 'high';\n timeout?: number;\n}\n\n/**\n * Worker result\n */\nexport interface WorkerResult {\n taskId: string;\n success: boolean;\n data?: any;\n error?: string;\n executionTime: number;\n}\n\n/**\n * Active task tracking\n */\ninterface ActiveTask {\n resolve: CallableFunction;\n reject: CallableFunction;\n timeout: NodeJS.Timeout | null;\n // The worker a task was dispatched to (set once it leaves the queue). Used so a\n // crashed worker only rejects its own in-flight tasks, not everyone else's.\n assignedWorker?: Worker;\n}\n\n/**\n * Built-in worker tasks\n */\nexport const WORKER_TASKS = {\n JWT_VERIFY: 'jwt:verify',\n JWT_SIGN: 'jwt:sign',\n CRYPTO_HASH: 'crypto:hash',\n CRYPTO_ENCRYPT: 'crypto:encrypt',\n CRYPTO_DECRYPT: 'crypto:decrypt',\n DATA_COMPRESS: 'data:compress',\n DATA_DECOMPRESS: 'data:decompress',\n IMAGE_PROCESS: 'image:process',\n HEAVY_COMPUTATION: 'computation:heavy',\n JSON_TRANSFORM: 'json:transform',\n} as const;\n\n/**\n * Worker Thread Manager\n * Manages a pool of worker threads for CPU-intensive operations\n */\nexport class WorkerManager {\n private workers: Map<number, Worker> = new Map();\n private taskQueue: WorkerTask[] = [];\n private activeTasks: Map<string, ActiveTask> = new Map();\n private workerCount: number;\n private maxQueueSize: number;\n private isShuttingDown = false;\n private maxRestartAttempts: number;\n private restartBackoffMs: number;\n private restartAttempts = 0;\n private restartTimers = new Set<NodeJS.Timeout>();\n private handledFailures = new WeakSet<Worker>();\n private poolFailed = false;\n\n constructor(\n options: {\n workerCount?: number;\n maxQueueSize?: number;\n maxRestartAttempts?: number;\n restartBackoffMs?: number;\n } = {}\n ) {\n this.workerCount = options.workerCount || Math.max(1, usableCpuCount() - 1); // Leave 1 core for main thread\n this.maxQueueSize = options.maxQueueSize || 1000;\n this.maxRestartAttempts = options.maxRestartAttempts ?? 10;\n this.restartBackoffMs = options.restartBackoffMs ?? 100;\n\n this.initializeWorkers();\n }\n\n /**\n * Initialize worker threads\n */\n private initializeWorkers(): void {\n for (let i = 0; i < this.workerCount; i++) {\n this.createWorker();\n }\n\n logger.info(`Initialized ${this.workerCount} worker threads`, 'WorkerInit', {\n totalWorkers: this.workerCount,\n maxQueueSize: this.maxQueueSize,\n });\n }\n\n /**\n * Create a single worker thread\n */\n private createWorker(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n let worker: Worker;\n try {\n worker = new (wt().Worker)(WORKER_ENTRY, {\n workerData: { type: 'worker' },\n });\n } catch (error) {\n // Spawning can fail synchronously (e.g. a missing entry file). Treat it the\n // same as a runtime failure so we back off instead of throwing.\n logger.error('Failed to spawn worker thread', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n this.scheduleRestart();\n return;\n }\n\n worker.on('message', (result: WorkerResult) => {\n // A successful message proves the pool is healthy; reset the restart budget.\n this.restartAttempts = 0;\n this.handleWorkerResult(result);\n });\n\n worker.on('error', error => {\n logger.error('Worker thread error', 'WorkerError', { error: error.message });\n this.handleWorkerFailure(worker);\n });\n\n worker.on('exit', code => {\n if (code !== 0 && !this.isShuttingDown) {\n logger.warn(`Worker exited with code ${code}, restarting`, 'WorkerExit');\n this.handleWorkerFailure(worker);\n }\n });\n\n this.workers.set(worker.threadId, worker);\n logger.debug(`Created worker thread ${worker.threadId}`, 'WorkerCreate');\n }\n\n /**\n * Handle a crashed worker: reject only the tasks that were assigned to it and\n * schedule a backed-off restart. A failed worker emits both 'error' and 'exit',\n * so this is guarded to run at most once per worker.\n */\n private handleWorkerFailure(worker: Worker): void {\n if (this.handledFailures.has(worker)) {\n return;\n }\n this.handledFailures.add(worker);\n\n this.workers.delete(worker.threadId);\n\n if (this.isShuttingDown) {\n return;\n }\n\n // Reject only the tasks that were dispatched to this specific worker. Tasks\n // still queued (or running on other workers) are intentionally left alone.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.assignedWorker === worker) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker thread failed'));\n this.activeTasks.delete(taskId);\n }\n }\n\n this.scheduleRestart();\n }\n\n /**\n * Schedule a replacement worker with exponential backoff, capping the number of\n * consecutive restart attempts so a persistently broken worker entry can never\n * spin into an unbounded restart loop.\n */\n private scheduleRestart(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n this.restartAttempts++;\n\n if (this.restartAttempts > this.maxRestartAttempts) {\n this.failPool();\n return;\n }\n\n const delay = Math.min(\n this.restartBackoffMs * 2 ** (this.restartAttempts - 1),\n MAX_RESTART_BACKOFF_MS\n );\n\n logger.warn(\n `Scheduling worker restart in ${delay}ms (attempt ${this.restartAttempts}/${this.maxRestartAttempts})`,\n 'WorkerRestart'\n );\n\n const timer = setTimeout(() => {\n this.restartTimers.delete(timer);\n this.createWorker();\n }, delay);\n\n // Don't keep the process alive purely for a pending restart\n timer.unref();\n this.restartTimers.add(timer);\n }\n\n /**\n * Give up after too many failed restarts: fail every outstanding task cleanly\n * (rejecting their promises) instead of looping forever.\n */\n private failPool(): void {\n if (this.poolFailed) {\n return;\n }\n this.poolFailed = true;\n\n logger.error(\n `Worker pool failed to recover after ${this.maxRestartAttempts} restart attempts`,\n 'WorkerPoolFailed'\n );\n\n const error = new Error(\n `Worker pool is unavailable after ${this.maxRestartAttempts} failed restart attempts`\n );\n\n // Every queued task also has an activeTasks entry, so this rejects both\n // in-flight and queued work.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(error);\n this.activeTasks.delete(taskId);\n }\n\n this.taskQueue.length = 0;\n }\n\n /**\n * Execute a task on a worker thread\n */\n async executeTask<T = any>(task: WorkerTask): Promise<T> {\n if (this.isShuttingDown) {\n throw new Error('Worker manager is shutting down');\n }\n\n if (this.poolFailed) {\n throw new Error('Worker pool is unavailable (too many worker failures)');\n }\n\n return new Promise<T>((resolve, reject) => {\n // Check queue size limit\n if (this.taskQueue.length >= this.maxQueueSize) {\n reject(new Error('Worker queue is full'));\n return;\n }\n\n // Add to queue\n this.taskQueue.push(task);\n\n // Set up promise handlers\n const timeout = task.timeout\n ? setTimeout(() => {\n this.activeTasks.delete(task.id);\n reject(new Error(`Task ${task.id} timed out`));\n }, task.timeout)\n : null;\n\n // Don't keep process alive for worker timeouts\n if (timeout) {\n timeout.unref();\n }\n\n this.activeTasks.set(task.id, { resolve, reject, timeout });\n\n // Try to assign task to available worker\n this.processQueue();\n });\n }\n\n /**\n * Process the task queue\n */\n private processQueue(): void {\n // Sort queue by priority (high first)\n this.taskQueue.sort(\n (a, b) =>\n (PRIORITY_ORDER[b.priority || 'normal'] ?? 0) -\n (PRIORITY_ORDER[a.priority || 'normal'] ?? 0)\n );\n\n // Assign tasks to available workers\n for (const [threadId, worker] of this.workers.entries()) {\n if (this.taskQueue.length === 0) break;\n\n // Check if worker is available (not currently processing)\n // For simplicity, we'll send tasks and let workers handle queuing\n const task = this.taskQueue.shift();\n if (task) {\n // Record the assignment so a crashed worker only rejects its own tasks.\n const taskInfo = this.activeTasks.get(task.id);\n if (taskInfo) {\n taskInfo.assignedWorker = worker;\n }\n worker.postMessage(task);\n logger.debug(`Assigned task ${task.id} to worker ${threadId}`, 'TaskAssigned');\n }\n }\n }\n\n /**\n * Handle result from worker thread\n */\n private handleWorkerResult(result: WorkerResult): void {\n const taskInfo = this.activeTasks.get(result.taskId);\n if (!taskInfo) {\n logger.warn(`Received result for unknown task ${result.taskId}`, 'UnknownTaskResult');\n return;\n }\n\n // Clear timeout\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n\n // Remove from active tasks\n this.activeTasks.delete(result.taskId);\n\n // Handle result\n if (result.success) {\n logger.debug(`Task ${result.taskId} completed in ${result.executionTime}ms`, 'TaskCompleted');\n taskInfo.resolve(result.data);\n } else {\n logger.error(`Task ${result.taskId} failed: ${result.error}`, 'TaskFailed');\n taskInfo.reject(new Error(result.error || 'Task failed'));\n }\n\n // Process next task in queue\n this.processQueue();\n }\n\n /**\n * Shutdown all workers\n */\n async shutdown(): Promise<void> {\n this.isShuttingDown = true;\n\n // Cancel any pending worker restarts\n for (const timer of this.restartTimers) {\n clearTimeout(timer);\n }\n this.restartTimers.clear();\n\n // Reject all pending tasks\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker manager shutting down'));\n }\n\n // Terminate all workers\n const shutdownPromises = Array.from(this.workers.values()).map(\n worker =>\n new Promise<void>(resolve => {\n worker.once('exit', () => resolve());\n void worker.terminate();\n })\n );\n\n await Promise.all(shutdownPromises);\n this.workers.clear();\n this.activeTasks.clear();\n this.taskQueue.length = 0;\n\n logger.info('Worker manager shutdown complete', 'WorkerShutdown');\n }\n\n /**\n * Get worker statistics\n */\n getStats() {\n return {\n workerCount: this.workers.size,\n activeTasks: this.activeTasks.size,\n queuedTasks: this.taskQueue.length,\n isShuttingDown: this.isShuttingDown,\n };\n }\n}\n\n// Singleton instance\nlet workerManagerInstance: WorkerManager | null = null;\n\n/**\n * Get or create the worker manager instance\n */\nexport function getWorkerManager(options?: {\n workerCount?: number;\n maxQueueSize?: number;\n}): WorkerManager {\n if (!workerManagerInstance) {\n workerManagerInstance = new WorkerManager(options);\n }\n return workerManagerInstance;\n}\n\n/**\n * Execute task on worker thread (convenience function)\n */\nexport async function executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n const manager = getWorkerManager();\n return manager.executeTask<T>(task);\n}\n\n/**\n * Built-in task helpers\n */\nexport const workerTasks = {\n /**\n * JWT verification (CPU-intensive)\n */\n async verifyJWT(token: string, secret: string, options?: any): Promise<any> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT verification requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-verify-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_VERIFY,\n data: { token, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * JWT signing (CPU-intensive)\n */\n async signJWT(payload: any, secret: string, options?: any): Promise<string> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT signing requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-sign-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_SIGN,\n data: { payload, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * Crypto hash (CPU-intensive)\n */\n async hash(data: string, algorithm = 'sha256'): Promise<string> {\n return executeOnWorker({\n id: `crypto-hash-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.CRYPTO_HASH,\n data: { data, algorithm },\n priority: 'normal',\n timeout: 10000,\n });\n },\n\n /**\n * Data compression (CPU-intensive for large payloads)\n */\n async compress(\n data: string | Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-compress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_COMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n // Buffers cross the thread boundary as plain Uint8Array\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Data decompression (CPU-intensive for large payloads)\n */\n async decompress(\n data: Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-decompress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_DECOMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Heavy computation example\n */\n async heavyComputation(data: any): Promise<any> {\n return executeOnWorker({\n id: `computation-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.HEAVY_COMPUTATION,\n data,\n priority: 'normal',\n timeout: 30000,\n });\n },\n\n /**\n * JSON transformation (can be CPU-intensive for large objects)\n */\n async transformJSON(data: any, transformer: (data: any) => any): Promise<any> {\n return executeOnWorker({\n id: `json-transform-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JSON_TRANSFORM,\n data: { data, transformer: transformer.toString() },\n priority: 'normal',\n timeout: 15000,\n });\n },\n};\n"]}
package/dist/index.d.ts CHANGED
@@ -57,11 +57,12 @@ export { normalizeValidationError } from './core/validation/schema-interface.js'
57
57
  export { joi, yup, fn as customValidator, classValidator } from './core/validation/adapters.js';
58
58
  export { defineModule, ModuleLoader, ModuleDiscovery, autoDiscoverModuleDirectories, } from './core/modules/index.js';
59
59
  export type { ModuleDefinition, ModuleRoute, ModuleSocket, ModuleConfig } from './types/module.js';
60
- export type { WebSocketAdapter, WebSocketAdapterOptions, WebSocketNamespace, WebSocketConnection, WebSocketEmitter, WebSocketMiddleware, WebSocketEventHandler, } from './core/networking/websocket-adapter.js';
60
+ export type { WebSocketAdapter, WebSocketAdapterOptions, WebSocketNamespace, WebSocketConnection, WebSocketNamespaceOptions, WebSocketEmitter, WebSocketMiddleware, WebSocketEventHandler, } from './core/networking/websocket-adapter.js';
61
61
  export { SocketIOAdapter, WSAdapter, UWebSocketsAdapter, } from './core/networking/adapters/index.js';
62
62
  export { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';
63
63
  export { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';
64
- export type { RouteBuilder, RouteSchema, CompiledRoute, HttpMethod, AuthConfig, RateLimitConfig, CacheConfig, MiddlewarePhases, ExecutionPhase, StaticBody, StaticResponse, } from './core/routing/index.js';
64
+ export type { RouteBuilder, RouteSchema, CompiledRoute, HttpMethod, AuthConfig, RateLimitConfig, CacheConfig, MiddlewarePhases, ExecutionPhase, StaticBody, StaticResponse, ParamEcho, ParamRouteReply, } from './core/routing/index.js';
65
+ export { param } from './core/routing/index.js';
65
66
  export { DocumentationSystem, AppDocumentationManager, createDocumentationSystem, generateDocsFromIntelligentRoutes, } from './core/docs/index.js';
66
67
  export type { DocsConfig } from './core/docs/index.js';
67
68
  export { getConfig, createModuleConfig, getEnvVar, getEnvArray, getEnvJson, isDevelopment, isProduction, isStaging, requireEnvVars, envVar, getConfigValue, } from './core/config/utils.js';
@@ -75,7 +76,7 @@ export { JobScheduler, JobHealthChecker, CronParser, parseInterval, formatDurati
75
76
  export type { JobSchedule, JobOptions, SimpleJobOptions, JobFunction, JobMetrics, SchedulerStats, JobHealth, JobHealthStatus, JobContext, JobExecution, JobState, JobSchedulerOptions, ExecutionContext, ExecutionResult, } from './core/jobs/index.js';
76
77
  export { MiddlewareManager } from './core/middleware/index.js';
77
78
  export type { MiddlewareInterface, MoroMiddleware } from './core/middleware/index.js';
78
- export { json, urlencoded } from './core/middleware/built-in/body-parsers/index.js';
79
+ export { json, urlencoded, raw, text } from './core/middleware/built-in/body-parsers/index.js';
79
80
  export { createRouter, createRouter as Router, MoroRouter } from './core/routing/create-router.js';
80
81
  export type * from './types/core.js';
81
82
  export type * from './types/http.js';
package/dist/index.js CHANGED
@@ -44,6 +44,7 @@ export { SocketIOAdapter, WSAdapter, UWebSocketsAdapter, } from './core/networki
44
44
  // Intelligent Routing System
45
45
  export { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';
46
46
  export { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';
47
+ export { param } from './core/routing/index.js';
47
48
  // Documentation System
48
49
  export { DocumentationSystem, AppDocumentationManager, createDocumentationSystem, generateDocsFromIntelligentRoutes, } from './core/docs/index.js';
49
50
  // Configuration utilities
@@ -57,7 +58,7 @@ export { JobScheduler, JobHealthChecker, CronParser, parseInterval, formatDurati
57
58
  // Middleware System
58
59
  export { MiddlewareManager } from './core/middleware/index.js';
59
60
  // Body parsers
60
- export { json, urlencoded } from './core/middleware/built-in/body-parsers/index.js';
61
+ export { json, urlencoded, raw, text } from './core/middleware/built-in/body-parsers/index.js';
61
62
  // Standalone router — `createRouter()` is the canonical factory; `Router` is an
62
63
  // alias kept callable without `new` so Express-style named imports
63
64
  // (`import { Router } from '...'`; `const r = Router();`) work unchanged.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EACL,IAAI,EACJ,IAAI,IAAI,QAAQ,EAChB,SAAS,EACT,aAAa,EACb,aAAa,EACb,eAAe,EACf,eAAe,EACf,MAAM,EACN,UAAU,GACX,MAAM,WAAW,CAAC;AAwBnB,qCAAqC;AACrC,OAAO,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAEjF,uCAAuC;AACvC,OAAO,EACL,IAAI,EACJ,SAAS,EACT,SAAS,EACT,YAAY,EACZ,SAAS,EACT,cAAc,EACd,SAAS,EACT,WAAW;AACX,wEAAwE;AACxE,mEAAmE;AACnE,WAAW,EACX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,EACjB,cAAc,EACd,cAAc,EACd,sBAAsB,EACtB,sBAAsB,EACtB,gBAAgB,GACjB,MAAM,+CAA+C,CAAC;AAEvD,aAAa;AACb,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,aAAa,EACb,cAAc,EACd,aAAa,EACb,YAAY,EACZ,SAAS,EACT,SAAS,GACV,MAAM,sBAAsB,CAAC;AAmB9B,oBAAoB;AACpB,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAG/D,eAAe;AACf,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,kDAAkD,CAAC;AAEpF,gFAAgF;AAChF,mEAAmE;AACnE,0EAA0E;AAC1E,OAAO,EAAE,YAAY,EAAE,YAAY,IAAI,MAAM,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAanG,WAAW;AACX,cAAc,oDAAoD,CAAC;AACnE,cAAc,kDAAkD,CAAC;AACjE,cAAc,mCAAmC,CAAC;AAqClD,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE9D,kBAAkB;AAClB,OAAO,EACL,QAAQ,EACR,qBAAqB,EACrB,eAAe,EACf,wBAAwB,EACxB,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,aAAa,GACd,MAAM,+BAA+B,CAAC","sourcesContent":["// MoroJS Framework - Main Entry Point\nexport {\n Moro,\n Moro as MoroCore,\n createApp,\n createAppNode,\n createAppEdge,\n createAppLambda,\n createAppWorker,\n getApp,\n RouteGroup,\n} from './moro.js';\n\nexport type { MoroOptions } from './core/framework.js';\n\n// Export auth types and middleware\nexport type {\n AuthOptions,\n AuthProvider,\n AuthUser,\n AuthSession,\n AuthRequest,\n AuthAccount,\n AuthJWT,\n AuthCallbacks,\n AuthEvents,\n AuthPages,\n AuthAdapter,\n OAuthProvider,\n CredentialsProvider,\n EmailProvider,\n SignInOptions,\n SignOutOptions,\n} from './types/auth.js';\n\n// Export native @auth/morojs adapter\nexport { createAuthMiddleware, MoroJSAuth } from './core/auth/morojs-adapter.js';\n\n// Export Auth middleware and providers\nexport {\n auth,\n providers,\n twoFactor,\n organization,\n anonymous,\n accountLinking,\n rateLimit,\n bearerToken,\n // Route guards and helpers (referenced by the auth docs as package-root\n // imports; must be re-exported here to be part of the public API).\n requireAuth,\n requireRole,\n requirePermission,\n requireAdmin,\n authUtils,\n authResponses,\n extendedProviders,\n enterpriseProviders,\n} from './core/middleware/built-in/auth/index.js';\nexport type {\n TwoFactorAuthOptions,\n OrganizationOptions,\n AnonymousOptions,\n AccountLinkingOptions,\n RateLimitOptions,\n BearerTokenOptions,\n} from './core/middleware/built-in/auth/index.js';\n\n// Runtime system exports\nexport type {\n RuntimeType,\n RuntimeAdapter,\n RuntimeConfig,\n RuntimeHttpResponse,\n} from './types/runtime.js';\n\nexport {\n NodeRuntimeAdapter,\n VercelEdgeAdapter,\n AWSLambdaAdapter,\n CloudflareWorkersAdapter,\n createRuntimeAdapter,\n createNodeHandler,\n createEdgeHandler,\n createLambdaHandler,\n createWorkerHandler,\n} from './core/runtime/index.js';\n\n// Runtime-specific types\nexport type {\n LambdaEvent,\n LambdaContext,\n LambdaResponse,\n} from './core/runtime/aws-lambda-adapter.js';\nexport type { WorkersEnv, WorkersContext } from './core/runtime/cloudflare-workers-adapter.js';\n\n// Core exports\nexport { MoroHttpServer, UWebSocketsHttpServer, MoroEngineServer } from './core/http/index.js';\nexport { middleware } from './core/middleware/built-in/index.js';\n\n// Re-declared (not re-exported) so the @deprecated tag reaches consumers:\n// TypeScript does not propagate deprecation through `export { x } from '...'`,\n// only through an actual declaration. Framework-internal code imports\n// builtInMiddleware from ./core/middleware/built-in/index.js directly, where\n// the declaration carries no tag, so this flags user code only.\nimport { builtInMiddleware as builtInMiddlewareImpl } from './core/middleware/built-in/index.js';\n/** @deprecated Use `middleware` instead. `builtInMiddleware` will be removed in a future release. */\nexport const builtInMiddleware = builtInMiddlewareImpl;\n\n// Worker Threads (CPU-intensive task offloading)\nexport { WorkerManager, getWorkerManager, workerTasks } from './core/workers/index.js';\nexport type { WorkerTask, WorkerResult } from './core/workers/index.js';\n\n// Object Pooling & Caching\nexport { ObjectPool, LRUCache, ObjectPoolManager } from './core/pooling/index.js';\n\n// Networking System\nexport { WebSocketManager, ServiceRegistry } from './core/networking/index.js';\nexport type { ServiceInfo, ServiceDiscoveryOptions } from './core/networking/service-discovery.js';\n\n// Utilities and Container System\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n CircuitBreaker,\n HookManager,\n HOOK_EVENTS,\n isPackageAvailable,\n resolveUserPackage,\n createUserRequire,\n // Standardized Response Helpers (namespace object only)\n response,\n ResponseBuilder,\n} from './core/utilities/index.js';\n\n// Response helper types\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ResponseValidationErrorDetail,\n} from './core/utilities/index.js';\n\n// Event System\nexport { MoroEventBus } from './core/events/index.js';\nexport type {\n EventContext,\n EventPayload,\n EventBusOptions,\n ModuleEventBus,\n GlobalEventBus,\n EventMetrics,\n SystemEvents,\n EventHandler,\n} from './types/events.js';\n\n// Logger System\nexport { createFrameworkLogger, logger } from './core/logger/index.js';\n\n// Universal Validation System\nexport {\n validate,\n body,\n query,\n params,\n combineSchemas,\n z,\n handleValidationError,\n normalizeErrors,\n} from './core/validation/index.js';\n\nexport type {\n ValidationConfig,\n ValidationResult,\n ValidationErrorDetail,\n ValidatedRequest,\n ValidationErrorHandler,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorDetailType,\n} from './core/validation/index.js';\n\n// Validation Interfaces and Adapters\nexport type {\n ValidationSchema,\n ValidationError,\n InferSchemaType,\n} from './core/validation/schema-interface.js';\nexport { normalizeValidationError } from './core/validation/schema-interface.js';\nexport { joi, yup, fn as customValidator, classValidator } from './core/validation/adapters.js';\n\n// Module System\nexport {\n defineModule,\n ModuleLoader,\n ModuleDiscovery,\n autoDiscoverModuleDirectories,\n} from './core/modules/index.js';\nexport type { ModuleDefinition, ModuleRoute, ModuleSocket, ModuleConfig } from './types/module.js';\n\n// WebSocket Adapter System\nexport type {\n WebSocketAdapter,\n WebSocketAdapterOptions,\n WebSocketNamespace,\n WebSocketConnection,\n WebSocketEmitter,\n WebSocketMiddleware,\n WebSocketEventHandler,\n} from './core/networking/websocket-adapter.js';\n\n// Built-in WebSocket Adapters\nexport {\n SocketIOAdapter,\n WSAdapter,\n UWebSocketsAdapter,\n} from './core/networking/adapters/index.js';\n\n// Intelligent Routing System\nexport { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';\nexport { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';\nexport type {\n RouteBuilder,\n RouteSchema,\n CompiledRoute,\n HttpMethod,\n AuthConfig,\n RateLimitConfig,\n CacheConfig,\n MiddlewarePhases,\n ExecutionPhase,\n StaticBody,\n StaticResponse,\n} from './core/routing/index.js';\n\n// Documentation System\nexport {\n DocumentationSystem,\n AppDocumentationManager,\n createDocumentationSystem,\n generateDocsFromIntelligentRoutes,\n} from './core/docs/index.js';\nexport type { DocsConfig } from './core/docs/index.js';\n\n// Configuration utilities\nexport {\n getConfig,\n createModuleConfig,\n getEnvVar,\n getEnvArray,\n getEnvJson,\n isDevelopment,\n isProduction,\n isStaging,\n requireEnvVars,\n envVar,\n getConfigValue,\n} from './core/config/utils.js';\n\nexport {\n initializeConfig,\n getGlobalConfig,\n isConfigInitialized,\n resetConfig,\n} from './core/config/index.js';\n\n// Export configuration types for TypeScript users\nexport type { AppConfig, DeepPartial, OriginFunction } from './core/config/index.js';\n\n// GraphQL System - Only export types and adapter\n// The core classes are lazy-loaded internally via app.graphqlInit()\nexport type {\n GraphQLContext,\n GraphQLResolver,\n GraphQLSubscriptionResolver,\n GraphQLSchemaBuilderOptions,\n GraphQLResolvers,\n GraphQLExecutionOptions,\n GraphQLOptions,\n GraphQLPlugin,\n GraphQLRequestContext,\n GraphQLRequestListener,\n GraphQLRequest,\n GraphQLResponse,\n GraphQLMetrics,\n GraphQLSubscriptionOptions,\n DataLoaderOptions,\n ComplexityEstimator,\n QueryComplexityOptions,\n DepthLimitOptions,\n} from './core/graphql/types.js';\n\nexport type { GraphQLAdapter, GraphQLStats } from './core/graphql/adapter.js';\nexport { GraphQLJsAdapter } from './core/graphql/adapters/graphql-js-adapter.js';\n\n// GraphQL helpers (these don't import graphql directly at module level)\nexport {\n createPothosBuilder,\n isPothosAvailable,\n isPothosSchema,\n pothosToSchema,\n createComplexityPlugin,\n createDepthLimitPlugin,\n createDataLoader,\n} from './core/middleware/built-in/graphql/helpers.js';\n\n// Job System\nexport {\n JobScheduler,\n JobHealthChecker,\n CronParser,\n parseInterval,\n formatDuration,\n everyInterval,\n cronSchedule,\n oneTimeAt,\n createJob,\n} from './core/jobs/index.js';\n\nexport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n JobHealthStatus,\n JobContext,\n JobExecution,\n JobState,\n JobSchedulerOptions,\n ExecutionContext,\n ExecutionResult,\n} from './core/jobs/index.js';\n\n// Middleware System\nexport { MiddlewareManager } from './core/middleware/index.js';\nexport type { MiddlewareInterface, MoroMiddleware } from './core/middleware/index.js';\n\n// Body parsers\nexport { json, urlencoded } from './core/middleware/built-in/body-parsers/index.js';\n\n// Standalone router — `createRouter()` is the canonical factory; `Router` is an\n// alias kept callable without `new` so Express-style named imports\n// (`import { Router } from '...'`; `const r = Router();`) work unchanged.\nexport { createRouter, createRouter as Router, MoroRouter } from './core/routing/create-router.js';\n\n// Types\nexport type * from './types/core.js';\nexport type * from './types/http.js';\nexport type * from './types/hooks.js';\nexport type * from './types/cache.js';\nexport type * from './types/cdn.js';\nexport type * from './types/database.js';\nexport type * from './types/logger.js';\nexport type * from './types/session.js';\nexport type * from './types/discovery.js';\n\n// Adapters\nexport * from './core/middleware/built-in/cache/adapters/index.js';\nexport * from './core/middleware/built-in/cdn/adapters/index.js';\nexport * from './core/database/adapters/index.js';\n\n// Re-export commonly used types for convenience\nexport type { CacheAdapter, CacheOptions, CacheStrategy } from './types/cache.js';\nexport type { CDNAdapter, CDNOptions } from './types/cdn.js';\nexport type { DatabaseAdapter, DatabaseTransaction, DatabaseConfig } from './types/database.js';\nexport type { CookieOptions } from './types/http.js';\n\n// gRPC System - Lazy loaded, only types exported\nexport type {\n GrpcOptions,\n GrpcCall,\n GrpcCallback,\n GrpcMetadata,\n GrpcError,\n GrpcStatusCode,\n GrpcCredentials,\n GrpcServer,\n GrpcClient,\n GrpcClientOptions,\n GrpcInterceptor,\n ServiceImplementation,\n ServiceDefinition,\n ServiceRegistration,\n MethodDefinition,\n UnaryHandler,\n ServerStreamingHandler,\n ClientStreamingHandler,\n BidirectionalStreamingHandler,\n GrpcHandler,\n GrpcStats,\n HealthCheckStatus,\n HealthCheckResponse,\n ProtoLoadOptions,\n} from './core/grpc/types.js';\n\nexport type { GrpcAdapter } from './core/grpc/grpc-adapter.js';\nexport { GrpcJsAdapter } from './core/grpc/adapters/index.js';\n\n// gRPC Middleware\nexport {\n grpcAuth,\n grpcRequirePermission,\n grpcRequireRole,\n extractTokenFromMetadata,\n grpcLogger,\n grpcSimpleLogger,\n grpcDetailedLogger,\n grpcValidate,\n grpcValidateHandler,\n} from './core/grpc/index.js';\n\n// Mail System - Lazy loaded, only types exported\nexport type {\n MailConfig,\n MailOptions,\n MailResult,\n MailAdapter,\n MailAdapterType,\n EmailAddress,\n EmailAttachment,\n TemplateConfig,\n TemplateEngine,\n MailQueueConfig,\n NodemailerConnection,\n SendGridConnection,\n SESConnection,\n ResendConnection,\n} from './core/mail/types.js';\n\nexport { BaseMailAdapter } from './core/mail/mail-adapter.js';\nexport {\n ConsoleAdapter,\n NodemailerAdapter,\n SendGridAdapter,\n SESAdapter,\n ResendAdapter,\n} from './core/mail/adapters/index.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,OAAO,EACL,IAAI,EACJ,IAAI,IAAI,QAAQ,EAChB,SAAS,EACT,aAAa,EACb,aAAa,EACb,eAAe,EACf,eAAe,EACf,MAAM,EACN,UAAU,GACX,MAAM,WAAW,CAAC;AAwBnB,qCAAqC;AACrC,OAAO,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAEjF,uCAAuC;AACvC,OAAO,EACL,IAAI,EACJ,SAAS,EACT,SAAS,EACT,YAAY,EACZ,SAAS,EACT,cAAc,EACd,SAAS,EACT,WAAW;AACX,wEAAwE;AACxE,mEAAmE;AACnE,WAAW,EACX,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,0CAA0C,CAAC;AAkBlD,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,wBAAwB,EACxB,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AAUjC,eAAe;AACf,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC/F,OAAO,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AAEjE,0EAA0E;AAC1E,+EAA+E;AAC/E,sEAAsE;AACtE,6EAA6E;AAC7E,gEAAgE;AAChE,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AACjG,qGAAqG;AACrG,MAAM,CAAC,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;AAEvD,iDA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c,kDAAkD,CAAC;AACjE,cAAc,mCAAmC,CAAC;AAqClD,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE9D,kBAAkB;AAClB,OAAO,EACL,QAAQ,EACR,qBAAqB,EACrB,eAAe,EACf,wBAAwB,EACxB,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,aAAa,GACd,MAAM,+BAA+B,CAAC","sourcesContent":["// MoroJS Framework - Main Entry Point\nexport {\n Moro,\n Moro as MoroCore,\n createApp,\n createAppNode,\n createAppEdge,\n createAppLambda,\n createAppWorker,\n getApp,\n RouteGroup,\n} from './moro.js';\n\nexport type { MoroOptions } from './core/framework.js';\n\n// Export auth types and middleware\nexport type {\n AuthOptions,\n AuthProvider,\n AuthUser,\n AuthSession,\n AuthRequest,\n AuthAccount,\n AuthJWT,\n AuthCallbacks,\n AuthEvents,\n AuthPages,\n AuthAdapter,\n OAuthProvider,\n CredentialsProvider,\n EmailProvider,\n SignInOptions,\n SignOutOptions,\n} from './types/auth.js';\n\n// Export native @auth/morojs adapter\nexport { createAuthMiddleware, MoroJSAuth } from './core/auth/morojs-adapter.js';\n\n// Export Auth middleware and providers\nexport {\n auth,\n providers,\n twoFactor,\n organization,\n anonymous,\n accountLinking,\n rateLimit,\n bearerToken,\n // Route guards and helpers (referenced by the auth docs as package-root\n // imports; must be re-exported here to be part of the public API).\n requireAuth,\n requireRole,\n requirePermission,\n requireAdmin,\n authUtils,\n authResponses,\n extendedProviders,\n enterpriseProviders,\n} from './core/middleware/built-in/auth/index.js';\nexport type {\n TwoFactorAuthOptions,\n OrganizationOptions,\n AnonymousOptions,\n AccountLinkingOptions,\n RateLimitOptions,\n BearerTokenOptions,\n} from './core/middleware/built-in/auth/index.js';\n\n// Runtime system exports\nexport type {\n RuntimeType,\n RuntimeAdapter,\n RuntimeConfig,\n RuntimeHttpResponse,\n} from './types/runtime.js';\n\nexport {\n NodeRuntimeAdapter,\n VercelEdgeAdapter,\n AWSLambdaAdapter,\n CloudflareWorkersAdapter,\n createRuntimeAdapter,\n createNodeHandler,\n createEdgeHandler,\n createLambdaHandler,\n createWorkerHandler,\n} from './core/runtime/index.js';\n\n// Runtime-specific types\nexport type {\n LambdaEvent,\n LambdaContext,\n LambdaResponse,\n} from './core/runtime/aws-lambda-adapter.js';\nexport type { WorkersEnv, WorkersContext } from './core/runtime/cloudflare-workers-adapter.js';\n\n// Core exports\nexport { MoroHttpServer, UWebSocketsHttpServer, MoroEngineServer } from './core/http/index.js';\nexport { middleware } from './core/middleware/built-in/index.js';\n\n// Re-declared (not re-exported) so the @deprecated tag reaches consumers:\n// TypeScript does not propagate deprecation through `export { x } from '...'`,\n// only through an actual declaration. Framework-internal code imports\n// builtInMiddleware from ./core/middleware/built-in/index.js directly, where\n// the declaration carries no tag, so this flags user code only.\nimport { builtInMiddleware as builtInMiddlewareImpl } from './core/middleware/built-in/index.js';\n/** @deprecated Use `middleware` instead. `builtInMiddleware` will be removed in a future release. */\nexport const builtInMiddleware = builtInMiddlewareImpl;\n\n// Worker Threads (CPU-intensive task offloading)\nexport { WorkerManager, getWorkerManager, workerTasks } from './core/workers/index.js';\nexport type { WorkerTask, WorkerResult } from './core/workers/index.js';\n\n// Object Pooling & Caching\nexport { ObjectPool, LRUCache, ObjectPoolManager } from './core/pooling/index.js';\n\n// Networking System\nexport { WebSocketManager, ServiceRegistry } from './core/networking/index.js';\nexport type { ServiceInfo, ServiceDiscoveryOptions } from './core/networking/service-discovery.js';\n\n// Utilities and Container System\nexport {\n Container,\n FunctionalContainer,\n TypedServiceReference,\n ServiceScope,\n ServiceLifecycle,\n withLogging,\n withCaching,\n withRetry,\n withTimeout,\n CircuitBreaker,\n HookManager,\n HOOK_EVENTS,\n isPackageAvailable,\n resolveUserPackage,\n createUserRequire,\n // Standardized Response Helpers (namespace object only)\n response,\n ResponseBuilder,\n} from './core/utilities/index.js';\n\n// Response helper types\nexport type {\n ApiSuccessResponse,\n ApiErrorResponse,\n ApiResponse,\n ResponseValidationErrorDetail,\n} from './core/utilities/index.js';\n\n// Event System\nexport { MoroEventBus } from './core/events/index.js';\nexport type {\n EventContext,\n EventPayload,\n EventBusOptions,\n ModuleEventBus,\n GlobalEventBus,\n EventMetrics,\n SystemEvents,\n EventHandler,\n} from './types/events.js';\n\n// Logger System\nexport { createFrameworkLogger, logger } from './core/logger/index.js';\n\n// Universal Validation System\nexport {\n validate,\n body,\n query,\n params,\n combineSchemas,\n z,\n handleValidationError,\n normalizeErrors,\n} from './core/validation/index.js';\n\nexport type {\n ValidationConfig,\n ValidationResult,\n ValidationErrorDetail,\n ValidatedRequest,\n ValidationErrorHandler,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorDetailType,\n} from './core/validation/index.js';\n\n// Validation Interfaces and Adapters\nexport type {\n ValidationSchema,\n ValidationError,\n InferSchemaType,\n} from './core/validation/schema-interface.js';\nexport { normalizeValidationError } from './core/validation/schema-interface.js';\nexport { joi, yup, fn as customValidator, classValidator } from './core/validation/adapters.js';\n\n// Module System\nexport {\n defineModule,\n ModuleLoader,\n ModuleDiscovery,\n autoDiscoverModuleDirectories,\n} from './core/modules/index.js';\nexport type { ModuleDefinition, ModuleRoute, ModuleSocket, ModuleConfig } from './types/module.js';\n\n// WebSocket Adapter System\nexport type {\n WebSocketAdapter,\n WebSocketAdapterOptions,\n WebSocketNamespace,\n WebSocketConnection,\n WebSocketNamespaceOptions,\n WebSocketEmitter,\n WebSocketMiddleware,\n WebSocketEventHandler,\n} from './core/networking/websocket-adapter.js';\n\n// Built-in WebSocket Adapters\nexport {\n SocketIOAdapter,\n WSAdapter,\n UWebSocketsAdapter,\n} from './core/networking/adapters/index.js';\n\n// Intelligent Routing System\nexport { createRoute, defineRoute, EXECUTION_PHASES } from './core/routing/index.js';\nexport { IntelligentRoutingManager, RouteRegistry } from './core/routing/app-integration.js';\nexport type {\n RouteBuilder,\n RouteSchema,\n CompiledRoute,\n HttpMethod,\n AuthConfig,\n RateLimitConfig,\n CacheConfig,\n MiddlewarePhases,\n ExecutionPhase,\n StaticBody,\n StaticResponse,\n ParamEcho,\n ParamRouteReply,\n} from './core/routing/index.js';\nexport { param } from './core/routing/index.js';\n\n// Documentation System\nexport {\n DocumentationSystem,\n AppDocumentationManager,\n createDocumentationSystem,\n generateDocsFromIntelligentRoutes,\n} from './core/docs/index.js';\nexport type { DocsConfig } from './core/docs/index.js';\n\n// Configuration utilities\nexport {\n getConfig,\n createModuleConfig,\n getEnvVar,\n getEnvArray,\n getEnvJson,\n isDevelopment,\n isProduction,\n isStaging,\n requireEnvVars,\n envVar,\n getConfigValue,\n} from './core/config/utils.js';\n\nexport {\n initializeConfig,\n getGlobalConfig,\n isConfigInitialized,\n resetConfig,\n} from './core/config/index.js';\n\n// Export configuration types for TypeScript users\nexport type { AppConfig, DeepPartial, OriginFunction } from './core/config/index.js';\n\n// GraphQL System - Only export types and adapter\n// The core classes are lazy-loaded internally via app.graphqlInit()\nexport type {\n GraphQLContext,\n GraphQLResolver,\n GraphQLSubscriptionResolver,\n GraphQLSchemaBuilderOptions,\n GraphQLResolvers,\n GraphQLExecutionOptions,\n GraphQLOptions,\n GraphQLPlugin,\n GraphQLRequestContext,\n GraphQLRequestListener,\n GraphQLRequest,\n GraphQLResponse,\n GraphQLMetrics,\n GraphQLSubscriptionOptions,\n DataLoaderOptions,\n ComplexityEstimator,\n QueryComplexityOptions,\n DepthLimitOptions,\n} from './core/graphql/types.js';\n\nexport type { GraphQLAdapter, GraphQLStats } from './core/graphql/adapter.js';\nexport { GraphQLJsAdapter } from './core/graphql/adapters/graphql-js-adapter.js';\n\n// GraphQL helpers (these don't import graphql directly at module level)\nexport {\n createPothosBuilder,\n isPothosAvailable,\n isPothosSchema,\n pothosToSchema,\n createComplexityPlugin,\n createDepthLimitPlugin,\n createDataLoader,\n} from './core/middleware/built-in/graphql/helpers.js';\n\n// Job System\nexport {\n JobScheduler,\n JobHealthChecker,\n CronParser,\n parseInterval,\n formatDuration,\n everyInterval,\n cronSchedule,\n oneTimeAt,\n createJob,\n} from './core/jobs/index.js';\n\nexport type {\n JobSchedule,\n JobOptions,\n SimpleJobOptions,\n JobFunction,\n JobMetrics,\n SchedulerStats,\n JobHealth,\n JobHealthStatus,\n JobContext,\n JobExecution,\n JobState,\n JobSchedulerOptions,\n ExecutionContext,\n ExecutionResult,\n} from './core/jobs/index.js';\n\n// Middleware System\nexport { MiddlewareManager } from './core/middleware/index.js';\nexport type { MiddlewareInterface, MoroMiddleware } from './core/middleware/index.js';\n\n// Body parsers\nexport { json, urlencoded, raw, text } from './core/middleware/built-in/body-parsers/index.js';\n\n// Standalone router — `createRouter()` is the canonical factory; `Router` is an\n// alias kept callable without `new` so Express-style named imports\n// (`import { Router } from '...'`; `const r = Router();`) work unchanged.\nexport { createRouter, createRouter as Router, MoroRouter } from './core/routing/create-router.js';\n\n// Types\nexport type * from './types/core.js';\nexport type * from './types/http.js';\nexport type * from './types/hooks.js';\nexport type * from './types/cache.js';\nexport type * from './types/cdn.js';\nexport type * from './types/database.js';\nexport type * from './types/logger.js';\nexport type * from './types/session.js';\nexport type * from './types/discovery.js';\n\n// Adapters\nexport * from './core/middleware/built-in/cache/adapters/index.js';\nexport * from './core/middleware/built-in/cdn/adapters/index.js';\nexport * from './core/database/adapters/index.js';\n\n// Re-export commonly used types for convenience\nexport type { CacheAdapter, CacheOptions, CacheStrategy } from './types/cache.js';\nexport type { CDNAdapter, CDNOptions } from './types/cdn.js';\nexport type { DatabaseAdapter, DatabaseTransaction, DatabaseConfig } from './types/database.js';\nexport type { CookieOptions } from './types/http.js';\n\n// gRPC System - Lazy loaded, only types exported\nexport type {\n GrpcOptions,\n GrpcCall,\n GrpcCallback,\n GrpcMetadata,\n GrpcError,\n GrpcStatusCode,\n GrpcCredentials,\n GrpcServer,\n GrpcClient,\n GrpcClientOptions,\n GrpcInterceptor,\n ServiceImplementation,\n ServiceDefinition,\n ServiceRegistration,\n MethodDefinition,\n UnaryHandler,\n ServerStreamingHandler,\n ClientStreamingHandler,\n BidirectionalStreamingHandler,\n GrpcHandler,\n GrpcStats,\n HealthCheckStatus,\n HealthCheckResponse,\n ProtoLoadOptions,\n} from './core/grpc/types.js';\n\nexport type { GrpcAdapter } from './core/grpc/grpc-adapter.js';\nexport { GrpcJsAdapter } from './core/grpc/adapters/index.js';\n\n// gRPC Middleware\nexport {\n grpcAuth,\n grpcRequirePermission,\n grpcRequireRole,\n extractTokenFromMetadata,\n grpcLogger,\n grpcSimpleLogger,\n grpcDetailedLogger,\n grpcValidate,\n grpcValidateHandler,\n} from './core/grpc/index.js';\n\n// Mail System - Lazy loaded, only types exported\nexport type {\n MailConfig,\n MailOptions,\n MailResult,\n MailAdapter,\n MailAdapterType,\n EmailAddress,\n EmailAttachment,\n TemplateConfig,\n TemplateEngine,\n MailQueueConfig,\n NodemailerConnection,\n SendGridConnection,\n SESConnection,\n ResendConnection,\n} from './core/mail/types.js';\n\nexport { BaseMailAdapter } from './core/mail/mail-adapter.js';\nexport {\n ConsoleAdapter,\n NodemailerAdapter,\n SendGridAdapter,\n SESAdapter,\n ResendAdapter,\n} from './core/mail/adapters/index.js';\n"]}
package/dist/moro.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { Moro as MoroCore } from './core/framework.js';
2
+ import type { WebSocketNamespaceOptions } from './core/networking/websocket-adapter.js';
3
+ import type { SSLConfigInput } from './core/http/utils/ssl-config.js';
2
4
  import { HttpRequest, HttpResponse } from './core/http/index.js';
3
5
  import { ModuleConfig } from './types/module.js';
4
6
  import { MoroOptions } from './types/core.js';
@@ -184,7 +186,7 @@ export declare class Moro extends EventEmitter {
184
186
  decorate(name: string, value: any): this;
185
187
  loadModule(moduleOrPath: ModuleConfig | string): Promise<this>;
186
188
  database(adapter: any): this;
187
- websocket(namespace: string, handlers: Record<string, CallableFunction>): this;
189
+ websocket(namespace: string, handlers: Record<string, CallableFunction>, options?: WebSocketNamespaceOptions): this;
188
190
  private processWebSocketRegistration;
189
191
  private processQueuedWebSocketRegistrations;
190
192
  listen(callback?: () => void): void;
@@ -216,6 +218,15 @@ export declare class Moro extends EventEmitter {
216
218
  get hooks(): import("./index.js").HookManager;
217
219
  get core(): MoroCore;
218
220
  get engine(): ReturnType<MoroCore['getServerKind']>;
221
+ /**
222
+ * Rotate the TLS certificate/key on the running listener without a restart.
223
+ * With no argument the key/cert files from `server.ssl` are re-read; with
224
+ * one, the given material (either ssl shape) replaces them. The new pair is
225
+ * validated first, so a bad file leaves the current certificate serving and
226
+ * rejects. Connections already established are untouched. `server.ssl.watch`
227
+ * calls this automatically when the files change.
228
+ */
229
+ reloadTLS(ssl?: SSLConfigInput): Promise<void>;
219
230
  getServerKind(): ReturnType<MoroCore['getServerKind']>;
220
231
  getContainer(): import("./index.js").Container;
221
232
  forceCleanup(): void;
package/dist/moro.js CHANGED
@@ -671,32 +671,61 @@ export class Moro extends EventEmitter {
671
671
  this.coreFramework.registerDatabase(adapter);
672
672
  return this;
673
673
  }
674
- // WebSocket helper with events
675
- websocket(namespace, handlers) {
674
+ // WebSocket helper with events.
675
+ //
676
+ // Default framing: every frame is a JSON `{ event, data }` envelope and each
677
+ // handler key is an event name. With `{ raw: true }` frames are delivered
678
+ // as-is: `message` gets each text frame as a string, `binary` each binary
679
+ // frame as a Buffer, and a string/Buffer returned from the handler (or
680
+ // `socket.send()`) is the reply frame - what a plain-WebSocket client
681
+ // (browsers, load testers, non-Moro peers) speaks.
682
+ websocket(namespace, handlers, options = {}) {
676
683
  // Queue the registration to be processed after adapter initialization
677
- const registration = { namespace, handlers, processed: false };
684
+ const registration = { namespace, handlers, options, processed: false };
678
685
  this.queuedWebSocketRegistrations.push(registration);
679
686
  // Try to process immediately if adapter is already ready
680
687
  const adapter = this.coreFramework.getWebSocketAdapter();
681
688
  if (adapter && !registration.processed) {
682
689
  // Adapter is ready, process immediately
683
- this.processWebSocketRegistration(namespace, handlers, adapter);
690
+ this.processWebSocketRegistration(namespace, handlers, adapter, options);
684
691
  registration.processed = true;
685
692
  }
686
693
  // Otherwise, it will be processed when the server starts
687
694
  return this;
688
695
  }
689
- processWebSocketRegistration(namespace, handlers, adapter) {
696
+ processWebSocketRegistration(namespace, handlers, adapter, options = {}) {
690
697
  this.emit('websocket:registering', { namespace, handlers });
691
- const ns = adapter.createNamespace(namespace);
698
+ const ns = adapter.createNamespace(namespace, options);
699
+ const raw = options.raw === true;
700
+ const isFrame = (v) => typeof v === 'string' ||
701
+ Buffer.isBuffer(v) ||
702
+ v instanceof ArrayBuffer ||
703
+ ArrayBuffer.isView(v);
692
704
  Object.entries(handlers).forEach(([event, handler]) => {
693
705
  ns.on('connection', (socket) => {
694
706
  this.emit('websocket:connection', { namespace, event, socket });
707
+ if (event === 'connection') {
708
+ // The documented `connection: socket => ...` hook runs once per
709
+ // socket at open (it is not a client-sendable event name).
710
+ Promise.resolve()
711
+ .then(() => handler(socket))
712
+ .catch((error) => this.emit('websocket:error', { namespace, event, error }));
713
+ return;
714
+ }
695
715
  socket.on(event, (data, callback) => {
696
716
  this.emit('websocket:event', { namespace, event, data });
697
717
  Promise.resolve(handler(socket, data))
698
718
  .then((result) => {
699
719
  this.emit('websocket:response', { namespace, event, result });
720
+ if (raw) {
721
+ // Raw framing: the return value IS the reply frame
722
+ if (isFrame(result))
723
+ socket.send?.(result);
724
+ else if (result !== undefined && result !== null) {
725
+ socket.send?.(JSON.stringify(result));
726
+ }
727
+ return;
728
+ }
700
729
  if (callback)
701
730
  callback(result);
702
731
  else if (result)
@@ -704,6 +733,10 @@ export class Moro extends EventEmitter {
704
733
  })
705
734
  .catch((error) => {
706
735
  this.emit('websocket:error', { namespace, event, error });
736
+ // A raw peer has no envelope to carry an error object; the
737
+ // failure is surfaced through the websocket:error event only.
738
+ if (raw)
739
+ return;
707
740
  const errorResponse = { success: false, error: error.message };
708
741
  if (callback)
709
742
  callback(errorResponse);
@@ -736,7 +769,7 @@ export class Moro extends EventEmitter {
736
769
  // Process all unprocessed registrations
737
770
  for (const registration of this.queuedWebSocketRegistrations) {
738
771
  if (!registration.processed) {
739
- this.processWebSocketRegistration(registration.namespace, registration.handlers, adapter);
772
+ this.processWebSocketRegistration(registration.namespace, registration.handlers, adapter, registration.options);
740
773
  registration.processed = true;
741
774
  }
742
775
  }
@@ -1221,6 +1254,18 @@ export class Moro extends EventEmitter {
1221
1254
  get engine() {
1222
1255
  return this.coreFramework.getServerKind();
1223
1256
  }
1257
+ /**
1258
+ * Rotate the TLS certificate/key on the running listener without a restart.
1259
+ * With no argument the key/cert files from `server.ssl` are re-read; with
1260
+ * one, the given material (either ssl shape) replaces them. The new pair is
1261
+ * validated first, so a bad file leaves the current certificate serving and
1262
+ * rejects. Connections already established are untouched. `server.ssl.watch`
1263
+ * calls this automatically when the files change.
1264
+ */
1265
+ async reloadTLS(ssl) {
1266
+ await this.coreFramework.reloadTLS(ssl);
1267
+ this.emit('tls:reloaded', { source: ssl ? 'argument' : 'files' });
1268
+ }
1224
1269
  getServerKind() {
1225
1270
  return this.coreFramework.getServerKind();
1226
1271
  }
@@ -1312,6 +1357,16 @@ export class Moro extends EventEmitter {
1312
1357
  }
1313
1358
  }
1314
1359
  }
1360
+ // Same for param(name) handlers on bare single-parameter routes: the
1361
+ // engine echoes the segment itself (engine >= 1.1.9).
1362
+ if (typeof httpServer.setParamRoute === 'function') {
1363
+ for (const schema of router.getAllRoutes()) {
1364
+ const echo = schema.paramEcho;
1365
+ if (echo) {
1366
+ httpServer.setParamRoute(schema.method, echo.prefix, echo.suffix, echo.status, echo.headers);
1367
+ }
1368
+ }
1369
+ }
1315
1370
  // Servers with a native router (uWS) additionally get fast-path routes
1316
1371
  // registered directly on it - evaluated at listen so late-loaded routes
1317
1372
  // are included; error handling shares the unified router's semantics
@@ -2251,6 +2306,7 @@ export class Moro extends EventEmitter {
2251
2306
  // timer firing. (closeIdle/closeAllConnections exist on the Node http
2252
2307
  // server; the uWS/engine backends ignore the optional calls.)
2253
2308
  server?.closeIdleConnections?.();
2309
+ this.coreFramework.stopTlsWatch();
2254
2310
  await Promise.race([
2255
2311
  new Promise(resolve => {
2256
2312
  httpServer.close(() => {