@forinda/kickjs 3.0.7 → 3.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{application-BwLUFfQy.mjs → application-Cx7ysduz.mjs} +5 -5
- package/dist/{application-BwLUFfQy.mjs.map → application-Cx7ysduz.mjs.map} +1 -1
- package/dist/{bootstrap-DV13o-cB.mjs → bootstrap-BoZYtuO7.mjs} +6 -6
- package/dist/{bootstrap-DV13o-cB.mjs.map → bootstrap-BoZYtuO7.mjs.map} +1 -1
- package/dist/{chunk-DXYGQY5w.mjs → chunk-CRY9H55I.mjs} +1 -1
- package/dist/config/index.mjs +3 -3
- package/dist/{config-BizkbnKi.mjs → config-CX1Xo3is.mjs} +3 -3
- package/dist/{config-BizkbnKi.mjs.map → config-CX1Xo3is.mjs.map} +1 -1
- package/dist/{container-DrJQ6Zgx.mjs → container-qU5VqCDl.mjs} +3 -3
- package/dist/{container-DrJQ6Zgx.mjs.map → container-qU5VqCDl.mjs.map} +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +3 -3
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-DEFm-pvP.mjs → core-Dff8TsH9.mjs} +4 -4
- package/dist/{core-DEFm-pvP.mjs.map → core-Dff8TsH9.mjs.map} +1 -1
- package/dist/{env-BDN9v7Yx.mjs → env-C0PEyw21.mjs} +4 -4
- package/dist/{env-BDN9v7Yx.mjs.map → env-C0PEyw21.mjs.map} +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +1 -1
- package/dist/http/middleware/spa.mjs +3 -3
- package/dist/http/middleware/upload.mjs +1 -1
- package/dist/http/middleware/validate.d.mts +6 -1
- package/dist/http/middleware/validate.d.mts.map +1 -1
- package/dist/http/middleware/validate.mjs +21 -23
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.mjs +4 -4
- package/dist/index.mjs +9 -9
- package/dist/{metadata-CGOLNICI.mjs → metadata-BLB2BbI7.mjs} +2 -2
- package/dist/{metadata-CGOLNICI.mjs.map → metadata-BLB2BbI7.mjs.map} +1 -1
- package/dist/{query-Baxld1NB.mjs → query-BNcR0osa.mjs} +2 -2
- package/dist/{query-Baxld1NB.mjs.map → query-BNcR0osa.mjs.map} +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v3.0.
|
|
2
|
+
* @forinda/kickjs v3.0.8
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -10,10 +10,10 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { METADATA } from "./core/interfaces.mjs";
|
|
12
12
|
import { Logger, createLogger } from "./core/logger.mjs";
|
|
13
|
-
import { t as getClassMeta } from "./metadata-
|
|
14
|
-
import { t as Container } from "./container-
|
|
13
|
+
import { t as getClassMeta } from "./metadata-BLB2BbI7.mjs";
|
|
14
|
+
import { t as Container } from "./container-qU5VqCDl.mjs";
|
|
15
15
|
import { normalizePath } from "./core/path.mjs";
|
|
16
|
-
import "./core-
|
|
16
|
+
import "./core-Dff8TsH9.mjs";
|
|
17
17
|
import { requestId } from "./http/middleware/request-id.mjs";
|
|
18
18
|
import { errorHandler, notFoundHandler } from "./http/middleware/error-handler.mjs";
|
|
19
19
|
import http from "node:http";
|
|
@@ -450,4 +450,4 @@ var Application = class {
|
|
|
450
450
|
//#endregion
|
|
451
451
|
export { requestStore as i, requestScopeMiddleware as n, getRequestStore as r, Application as t };
|
|
452
452
|
|
|
453
|
-
//# sourceMappingURL=application-
|
|
453
|
+
//# sourceMappingURL=application-Cx7ysduz.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"application-BwLUFfQy.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/application.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /** Per-request singleton cache for REQUEST-scoped services */\n instances: Map<any, any>\n /** Per-request values set by middleware (auth user, tenant, etc.) */\n values: Map<any, any>\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n","import crypto from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n */\nexport function requestScopeMiddleware() {\n return (req: Request, _res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store: RequestStore = {\n requestId,\n instances: new Map(),\n values: new Map(),\n }\n requestStore.run(store, () => next())\n }\n}\n","import http from 'node:http'\nimport express, { type Express, type RequestHandler } from 'express'\nimport {\n Container,\n createLogger,\n Logger,\n normalizePath,\n METADATA,\n type AppModuleClass,\n type AppAdapter,\n type AdapterContext,\n type AdapterMiddleware,\n type KickPlugin,\n type RouteDefinition,\n} from '../core'\nimport { getClassMeta } from '../core/metadata'\nimport { requestId } from './middleware/request-id'\nimport { notFoundHandler, errorHandler } from './middleware/error-handler'\nimport { requestScopeMiddleware } from './middleware/request-scope'\nimport { requestStore, getRequestStore } from './request-store'\n\nconst log = createLogger('Application')\n\n/**\n * A middleware entry in the declarative pipeline.\n * Can be a bare handler or an object with path scoping.\n */\nexport type MiddlewareEntry = RequestHandler | { path: string; handler: RequestHandler }\n\nexport interface ApplicationOptions {\n /** Feature modules to load */\n modules: AppModuleClass[]\n /** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */\n adapters?: AppAdapter[]\n /** Server port (falls back to PORT env var, then 3000) */\n port?: number\n /** Global API prefix (default: '/api') */\n apiPrefix?: string\n /** Default API version (default: 1) — routes become /{prefix}/v{version}/{path} */\n defaultVersion?: number\n\n /**\n * Global middleware pipeline. Declared in order.\n * Replaces the hardcoded middleware stack — you control exactly what runs.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * middleware: [\n * helmet(),\n * cors(),\n * compression(),\n * morgan('dev'),\n * express.json({ limit: '1mb' }),\n * ],\n * })\n * ```\n *\n * If omitted, a sensible default is applied:\n * requestId(), express.json({ limit: '100kb' })\n */\n middleware?: MiddlewareEntry[]\n\n /** Plugins that bundle modules, adapters, middleware, and DI bindings */\n plugins?: KickPlugin[]\n\n /** Express `trust proxy` setting */\n trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean)\n /** Maximum JSON body size (only used when middleware is not provided) */\n jsonLimit?: string | number\n /**\n * Log route summary on startup. Default: true in dev, false in production.\n * Set to `true` to always log, `false` to always suppress.\n */\n logRoutesTable?: boolean\n /**\n * Maximum time (ms) to wait for graceful shutdown before forcing exit.\n * Default: 30000 (30 seconds). Set to 0 to disable forced exit.\n */\n shutdownTimeout?: number\n\n /**\n * Enable cluster mode for multi-core utilization.\n *\n * When enabled, the primary process forks worker processes that share the\n * same port via Node's built-in `cluster` module (OS load balancing).\n *\n * - `true` — use all available CPU cores\n * - `{ workers: N }` — use exactly N workers\n *\n * Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is\n * forwarded to all workers.\n *\n * @example\n * ```ts\n * bootstrap({ modules, cluster: true })\n * bootstrap({ modules, cluster: { workers: 4 } })\n * ```\n */\n cluster?: boolean | { workers?: number }\n\n /**\n * Custom 404 handler for unmatched routes. Receives the raw Express\n * `(req, res, next)` args. When omitted, the built-in handler returns\n * `{ message: 'Not Found' }` with status 404.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onNotFound: (req, res) => {\n * res.status(404).json({ error: 'Route not found', path: req.originalUrl })\n * },\n * })\n * ```\n */\n onNotFound?: (req: any, res: any, next: any) => void\n\n /**\n * Custom global error handler. Receives `(err, req, res, next)` — the\n * standard Express error-handling signature. When omitted, the built-in\n * handler formats ZodError, HttpException, and unexpected errors.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onError: (err, req, res, next) => {\n * logger.error(err)\n * res.status(err.status ?? 500).json({ error: err.message })\n * },\n * })\n * ```\n */\n onError?: (err: any, req: any, res: any, next: any) => void\n\n /**\n * Security defaults applied automatically unless opted out.\n *\n * When not specified, secure defaults are applied:\n * - Helmet security headers are auto-injected\n * - JSON body limit defaults to 1MB\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * security: {\n * helmet: false, // disable auto-helmet\n * },\n * })\n * ```\n */\n security?: {\n /** Auto-inject helmet security headers. Default: true */\n helmet?: boolean\n }\n}\n\n/**\n * The main application class. Wires together Express, the DI container,\n * feature modules, adapters, and the middleware pipeline.\n */\nexport class Application {\n private app: Express\n private container: Container\n private httpServer: http.Server | null = null\n private adapters: AppAdapter[]\n\n private plugins: KickPlugin[]\n\n /** Number of HTTP requests currently being processed */\n private _inFlightRequests = 0\n /** Whether the application is draining (shutting down gracefully) */\n private _draining = false\n /** Whether shutdown has already been initiated (prevents double-shutdown) */\n private _shutdownInitiated = false\n /** Resolvers waiting for in-flight requests to reach zero */\n private _drainResolvers: Array<() => void> = []\n\n constructor(private readonly options: ApplicationOptions) {\n this.app = express()\n this.container = Container.getInstance()\n this.plugins = options.plugins ?? []\n this.adapters = [\n // Plugin adapters first\n ...this.plugins.flatMap((p) => p.adapters?.() ?? []),\n ...(options.adapters ?? []),\n ]\n // Wire the request store provider so Container can resolve REQUEST-scoped deps\n Container._requestStoreProvider = () => requestStore.getStore() ?? null\n // Wire logger context provider so logs auto-include requestId\n Logger._contextProvider = () => {\n const store = requestStore.getStore()\n if (!store) return null\n const ctx: Record<string, any> = { requestId: store.requestId }\n const traceId = store.values.get('traceId')\n if (traceId) ctx.traceId = traceId\n const spanId = store.values.get('spanId')\n if (spanId) ctx.spanId = spanId\n return ctx\n }\n }\n\n /** Whether the application is currently draining in-flight requests */\n get isDraining(): boolean {\n return this._draining\n }\n\n /** Number of HTTP requests currently being processed */\n get inFlightRequests(): number {\n return this._inFlightRequests\n }\n\n /** Get the DI container instance */\n getContainer(): Container {\n return this.container\n }\n\n /**\n * Express request handler — delegates to the internal Express app.\n *\n * Used by the Vite dev-server plugin to route requests through KickJS:\n * ```ts\n * const mod = await ssrLoadModule('virtual:kickjs/app')\n * mod.app.handle(req, res, next)\n * ```\n *\n * Also works as a standard Node.js request handler for production:\n * ```ts\n * http.createServer(app.handle.bind(app))\n * ```\n */\n handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n if (next) {\n this.app(req as any, res as any, next)\n } else {\n this.app(req as any, res as any)\n }\n }\n\n /**\n * Full setup pipeline:\n * 1. Adapter beforeMount hooks (early routes — docs, health)\n * 2. Adapter middleware (phase: beforeGlobal)\n * 3. Global middleware (user-declared or defaults)\n * 4. Adapter middleware (phase: afterGlobal)\n * 5. Module registration + DI bootstrap\n * 6. Adapter middleware (phase: beforeRoutes)\n * 7. Module route mounting\n * 8. Adapter middleware (phase: afterRoutes)\n * 9. Error handlers (notFound + global)\n * 10. Adapter beforeStart hooks\n */\n /** Build the adapter context object (shared across all hooks) */\n private adapterCtx(server?: any): AdapterContext {\n const env = process.env.NODE_ENV ?? 'development'\n return {\n app: this.app,\n container: this.container,\n server,\n env,\n isProduction: env === 'production',\n }\n }\n\n /** Call an adapter hook, awaiting async hooks and catching errors */\n private async callHook(\n hook: ((ctx: AdapterContext) => void | Promise<void>) | undefined,\n ctx: AdapterContext,\n ): Promise<void> {\n if (!hook) return\n try {\n const result = hook(ctx)\n if (result && typeof (result as Promise<void>).then === 'function') {\n await result\n }\n } catch (err) {\n log.error(err, 'Adapter hook failed')\n }\n }\n\n async setup(): Promise<void> {\n log.debug('Bootstrapping application...')\n\n // Collect adapter middleware by phase\n const adapterMw = this.collectAdapterMiddleware()\n\n // Expose the Application instance on the Express app for adapter discovery\n ;(this.app as any).__kickApp = this\n\n const ctx = this.adapterCtx()\n\n // ── 1. Adapter beforeMount hooks ──────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeMount?.bind(adapter), ctx)\n }\n\n // ── 2. Hardened defaults ──────────────────────────────────────────\n this.app.disable('x-powered-by')\n this.app.set('trust proxy', this.options.trustProxy ?? false)\n\n // ── 2a. In-flight request tracking ──────────────────────────────\n this.app.use(this.requestTrackingMiddleware())\n\n // ── 2b. Health check endpoints (before middleware, at root) ──────\n this.mountHealthEndpoints()\n\n // ── 2c. Request scope (AsyncLocalStorage) ────────────────────────\n this.app.use(requestScopeMiddleware())\n\n // ── 3. Adapter middleware: beforeGlobal ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeGlobal)\n\n // ── 3b. Plugin registration ──────────────────────────────────────\n for (const plugin of this.plugins) {\n plugin.register?.(this.container)\n }\n\n // ── 3c. Plugin middleware ─────────────────────────────────────────\n for (const plugin of this.plugins) {\n try {\n const mw = plugin.middleware?.() ?? []\n for (const handler of mw) {\n this.app.use(handler)\n }\n } catch (err) {\n log.error(err, `Plugin middleware failed: ${(plugin as any).name ?? 'unknown'}`)\n }\n }\n\n // ── 4. Global middleware ─────────────────────────────────────────\n // Auto-inject helmet unless opted out\n const autoHelmet = this.options.security?.helmet !== false\n if (autoHelmet) {\n try {\n const { helmet: helmetFn } = await import('./middleware/helmet')\n this.app.use(helmetFn())\n } catch {\n // helmet middleware not available — skip silently\n }\n }\n\n if (this.options.middleware) {\n // User-declared pipeline — full control\n for (const entry of this.options.middleware) {\n this.mountMiddlewareEntry(entry)\n }\n } else {\n // Sensible defaults when no middleware declared\n this.app.use(requestId())\n this.app.use(express.json({ limit: this.options.jsonLimit ?? '1mb' }))\n }\n\n // ── 5. Adapter middleware: afterGlobal ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterGlobal)\n\n // ── 6. Module registration + DI bootstrap ────────────────────────\n // Plugin modules first, then user modules\n const allModuleClasses = [\n ...this.plugins.flatMap((p) => p.modules?.() ?? []),\n ...this.options.modules,\n ]\n const modules = allModuleClasses.map((ModuleClass) => {\n const mod = new ModuleClass()\n // `register()` is optional — modules whose classes are entirely\n // decorator-managed (@Service, @Controller, @Repository) don't need it.\n mod.register?.(this.container)\n return mod\n })\n this.container.bootstrap()\n\n // ── 7. Adapter middleware: beforeRoutes ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeRoutes)\n\n // ── 8. Mount module routes with versioning ───────────────────────\n const apiPrefix = this.options.apiPrefix ?? '/api'\n const defaultVersion = this.options.defaultVersion ?? 1\n const shouldLogRoutes = this.options.logRoutesTable ?? process.env.NODE_ENV !== 'production'\n\n // Collect route metadata during mounting (avoids calling mod.routes() twice)\n const mountedRoutes: Array<{ controller: any; mountPath: string }> = []\n\n for (const mod of modules) {\n const result = mod.routes()\n if (!result) continue // Non-HTTP modules (queues, cron) may return null\n\n const routeSets = Array.isArray(result) ? result : [result]\n\n for (const route of routeSets) {\n const version = route.version ?? defaultVersion\n const mountPath = `${apiPrefix}/v${version}${normalizePath(route.path)}`\n this.app.use(mountPath, route.router)\n\n // Notify adapters (e.g. SwaggerAdapter for OpenAPI spec generation)\n if (route.controller) {\n for (const adapter of this.adapters) {\n try {\n adapter.onRouteMount?.(route.controller, mountPath)\n } catch (err) {\n log.error(err, `adapter.onRouteMount() failed for ${mountPath}`)\n }\n }\n if (shouldLogRoutes) {\n mountedRoutes.push({ controller: route.controller, mountPath })\n }\n }\n }\n }\n\n // ── 8b. Log route summary ─────────────────────────────────────────\n if (shouldLogRoutes && mountedRoutes.length > 0) {\n const methodOrder = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']\n const methodRank = (m: string) => {\n const i = methodOrder.indexOf(m)\n return i === -1 ? 99 : i\n }\n\n let totalRoutes = 0\n log.debug('Routes:')\n\n for (const { controller, mountPath } of mountedRoutes) {\n const defs: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controller,\n [],\n )\n if (defs.length === 0) continue\n\n const counts: Record<string, number> = {}\n for (const def of defs) {\n const m = def.method.toUpperCase()\n counts[m] = (counts[m] || 0) + 1\n }\n totalRoutes += defs.length\n\n const methods = Object.entries(counts)\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([m, n]) => `${n} ${m}`)\n .join(', ')\n const name = controller.name || 'Controller'\n log.debug(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)\n }\n\n log.debug(` Total: ${totalRoutes} routes`)\n }\n\n // ── 9. Adapter middleware: afterRoutes ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterRoutes)\n\n // ── 10. Error handlers ───────────────────────────────────────────\n this.app.use(this.options.onNotFound ?? notFoundHandler())\n this.app.use(this.options.onError ?? errorHandler())\n\n // ── 11. Adapter beforeStart hooks ────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeStart?.bind(adapter), ctx)\n }\n }\n\n /** Register modules and DI without starting the HTTP server (used by kick tinker) */\n async registerOnly(): Promise<void> {\n await this.setup()\n }\n\n /**\n * Start the HTTP server.\n *\n * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`\n * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real\n * `http.Server` through `afterStart({ server })` — zero adapter changes needed.\n *\n * In **production**: creates its own `http.Server` and binds to the port.\n */\n async start(): Promise<void> {\n await this.setup()\n\n const g = globalThis as any\n\n if (g.__kickjs_httpServer) {\n // ── DEV MODE: Vite owns the http.Server ──────────────────────\n // Don't create a new server or listen — Vite is already listening.\n // Just wire up adapters with the Vite-created server.\n this.httpServer = g.__kickjs_httpServer\n log.debug('Attached to Vite dev server')\n\n for (const adapter of this.adapters) {\n const ctx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), ctx)\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n return\n }\n\n // ── PRODUCTION: Create and own the http.Server ─────────────────\n const port = this.options.port ?? parseInt(process.env.PORT || '3000', 10)\n this.httpServer = http.createServer(this.app)\n\n this.httpServer.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n log.error(\n `Port ${port} is already in use. Kill the existing process or use a different port:\\n` +\n ` PORT=${port + 1} kick dev\\n` +\n ` lsof -i :${port} # find what's using it\\n` +\n ` kill <PID> # stop it`,\n )\n process.exit(1)\n }\n throw err\n })\n\n // Wrap listen in a Promise so afterStart/onReady errors propagate\n await new Promise<void>((resolve, reject) => {\n this.httpServer!.listen(port, async () => {\n try {\n log.info(`Server running on http://localhost:${port}`)\n\n for (const adapter of this.adapters) {\n const afterCtx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), afterCtx)\n }\n\n // Plugin onReady hooks\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n resolve()\n } catch (err) {\n reject(err)\n }\n })\n })\n }\n\n /** HMR rebuild: swap Express handler without restarting the server */\n async rebuild(): Promise<void> {\n // Build the new app fully before swapping — if setup() throws,\n // the old app keeps running so the server stays responsive.\n const prevApp = this.app\n const prevContainer = this.container\n\n try {\n Container.reset()\n this.container = Container.getInstance()\n this.app = express()\n await this.setup()\n } catch (err) {\n log.error(err, 'HMR rebuild failed, keeping previous app')\n // Restore previous state so the server stays responsive\n this.app = prevApp\n this.container = prevContainer\n return\n }\n\n if (this.httpServer) {\n this.httpServer.removeAllListeners('request')\n this.httpServer.on('request', this.app)\n log.debug('HMR: Express app rebuilt and swapped')\n }\n }\n\n /**\n * Graceful shutdown with request draining.\n *\n * 1. Stops accepting new connections (server.close())\n * 2. Waits for in-flight requests to complete (up to shutdownTimeout)\n * 3. Calls adapter.shutdown() for all registered adapters\n * 4. Force-closes after timeout\n *\n * Safe to call multiple times — subsequent calls return the same promise.\n */\n async shutdown(): Promise<void> {\n // Prevent double-shutdown — return immediately if already initiated\n if (this._shutdownInitiated) {\n log.debug('Shutdown already in progress, skipping duplicate call')\n return\n }\n this._shutdownInitiated = true\n this._draining = true\n\n log.debug('Shutting down — draining in-flight requests...')\n\n const timeoutMs = this.options.shutdownTimeout ?? 30_000\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // Start a force-exit timer if timeout is configured\n const forceExitPromise =\n timeoutMs > 0\n ? new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n timer.unref()\n })\n : new Promise<never>(() => {}) // never resolves — no forced exit\n\n try {\n // Step 1: Stop accepting new connections.\n // server.close() prevents new connections. Its callback fires only when\n // ALL existing connections are fully closed, so we do NOT await it here —\n // we track request draining separately via the tracking middleware.\n if (this.httpServer) {\n this.httpServer.close(() => {})\n }\n\n // Step 2: Wait for in-flight requests to drain (or timeout)\n if (this._inFlightRequests > 0) {\n log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`)\n const drainPromise = new Promise<'drained'>((resolve) => {\n this._drainResolvers.push(() => resolve('drained'))\n })\n\n const result = await Promise.race([drainPromise, forceExitPromise])\n if (result === 'timeout') {\n log.warn(\n `Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`,\n )\n } else {\n log.debug('All in-flight requests completed')\n }\n }\n\n // Step 3: Run all plugin + adapter shutdowns concurrently\n const results = await Promise.allSettled([\n ...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())),\n ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.())),\n ])\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error({ err: result.reason }, 'Adapter shutdown failed')\n }\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n getExpressApp(): Express {\n return this.app\n }\n\n /** Get registered adapters — used by DevToolsAdapter for peer discovery */\n getAdapters(): AppAdapter[] {\n return this.adapters\n }\n\n getHttpServer(): http.Server | null {\n return this.httpServer\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n private collectAdapterMiddleware() {\n const result = {\n beforeGlobal: [] as AdapterMiddleware[],\n afterGlobal: [] as AdapterMiddleware[],\n beforeRoutes: [] as AdapterMiddleware[],\n afterRoutes: [] as AdapterMiddleware[],\n }\n\n for (const adapter of this.adapters) {\n const entries = adapter.middleware?.() ?? []\n for (const entry of entries) {\n const phase = entry.phase ?? 'afterGlobal'\n result[phase].push(entry)\n }\n }\n\n return result\n }\n\n private mountMiddlewareList(entries: AdapterMiddleware[]): void {\n for (const entry of entries) {\n if (entry.path) {\n this.app.use(entry.path, entry.handler)\n } else {\n this.app.use(entry.handler)\n }\n }\n }\n\n private mountMiddlewareEntry(entry: MiddlewareEntry): void {\n if (typeof entry === 'function') {\n this.app.use(entry)\n } else {\n this.app.use(entry.path, entry.handler)\n }\n }\n\n /** Middleware that tracks in-flight requests for graceful draining */\n private requestTrackingMiddleware(): RequestHandler {\n return (_req, res, next) => {\n this._inFlightRequests++\n const onFinish = () => {\n res.removeListener('finish', onFinish)\n res.removeListener('close', onFinish)\n this._inFlightRequests--\n // If draining and no more in-flight requests, resolve all waiters\n if (this._draining && this._inFlightRequests === 0) {\n for (const resolve of this._drainResolvers) {\n resolve()\n }\n this._drainResolvers = []\n }\n }\n res.on('finish', onFinish)\n res.on('close', onFinish)\n next()\n }\n }\n\n /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */\n private mountHealthEndpoints(): void {\n this.app.get('/health/live', (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', uptime: process.uptime() })\n } else {\n res.json({ status: 'ok', uptime: process.uptime() })\n }\n })\n\n this.app.get('/health/ready', async (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', checks: [] })\n return\n }\n const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck)\n const checks = await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck!()))\n const results = checks.map((c, i) => {\n if (c.status === 'fulfilled') return c.value\n return { name: adaptersWithHealth[i].name ?? 'unknown', status: 'down' as const }\n })\n const healthy = results.every((r) => r.status === 'up')\n res.status(healthy ? 200 : 503).json({\n status: healthy ? 'ready' : 'degraded',\n checks: results,\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,eAAe,IAAI,mBAAiC;;;;;AAMjE,SAAgB,kBAAgC;CAC9C,MAAM,QAAQ,aAAa,UAAU;AACrC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,kGACD;AAEH,QAAO;;;;;;;;;;AChBT,SAAgB,yBAAyB;AACvC,SAAQ,KAAc,MAAgB,SAAuB;EAC3D,MAAM,kBAAkB,IAAI,QAAQ;EAGpC,MAAM,QAAsB;GAC1B,YAFC,MAAM,QAAQ,gBAAgB,GAAG,gBAAgB,KAAK,oBAAoB,OAAO,YAAY;GAG9F,2BAAW,IA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,EAAE;KAAE,CAAC;AACxD;;GAEF,MAAM,qBAAqB,KAAK,SAAS,QAAQ,MAAM,EAAE,cAAc;GAEvE,MAAM,WADS,MAAM,QAAQ,WAAW,mBAAmB,KAAK,MAAM,EAAE,eAAgB,CAAC,CAAC,EACnE,KAAK,GAAG,MAAM;AACnC,QAAI,EAAE,WAAW,YAAa,QAAO,EAAE;AACvC,WAAO;KAAE,MAAM,mBAAmB,GAAG,QAAQ;KAAW,QAAQ;KAAiB;KACjF;GACF,MAAM,UAAU,QAAQ,OAAO,MAAM,EAAE,WAAW,KAAK;AACvD,OAAI,OAAO,UAAU,MAAM,IAAI,CAAC,KAAK;IACnC,QAAQ,UAAU,UAAU;IAC5B,QAAQ;IACT,CAAC;IACF"}
|
|
1
|
+
{"version":3,"file":"application-Cx7ysduz.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/application.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /** Per-request singleton cache for REQUEST-scoped services */\n instances: Map<any, any>\n /** Per-request values set by middleware (auth user, tenant, etc.) */\n values: Map<any, any>\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n","import crypto from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n */\nexport function requestScopeMiddleware() {\n return (req: Request, _res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store: RequestStore = {\n requestId,\n instances: new Map(),\n values: new Map(),\n }\n requestStore.run(store, () => next())\n }\n}\n","import http from 'node:http'\nimport express, { type Express, type RequestHandler } from 'express'\nimport {\n Container,\n createLogger,\n Logger,\n normalizePath,\n METADATA,\n type AppModuleClass,\n type AppAdapter,\n type AdapterContext,\n type AdapterMiddleware,\n type KickPlugin,\n type RouteDefinition,\n} from '../core'\nimport { getClassMeta } from '../core/metadata'\nimport { requestId } from './middleware/request-id'\nimport { notFoundHandler, errorHandler } from './middleware/error-handler'\nimport { requestScopeMiddleware } from './middleware/request-scope'\nimport { requestStore, getRequestStore } from './request-store'\n\nconst log = createLogger('Application')\n\n/**\n * A middleware entry in the declarative pipeline.\n * Can be a bare handler or an object with path scoping.\n */\nexport type MiddlewareEntry = RequestHandler | { path: string; handler: RequestHandler }\n\nexport interface ApplicationOptions {\n /** Feature modules to load */\n modules: AppModuleClass[]\n /** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */\n adapters?: AppAdapter[]\n /** Server port (falls back to PORT env var, then 3000) */\n port?: number\n /** Global API prefix (default: '/api') */\n apiPrefix?: string\n /** Default API version (default: 1) — routes become /{prefix}/v{version}/{path} */\n defaultVersion?: number\n\n /**\n * Global middleware pipeline. Declared in order.\n * Replaces the hardcoded middleware stack — you control exactly what runs.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * middleware: [\n * helmet(),\n * cors(),\n * compression(),\n * morgan('dev'),\n * express.json({ limit: '1mb' }),\n * ],\n * })\n * ```\n *\n * If omitted, a sensible default is applied:\n * requestId(), express.json({ limit: '100kb' })\n */\n middleware?: MiddlewareEntry[]\n\n /** Plugins that bundle modules, adapters, middleware, and DI bindings */\n plugins?: KickPlugin[]\n\n /** Express `trust proxy` setting */\n trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean)\n /** Maximum JSON body size (only used when middleware is not provided) */\n jsonLimit?: string | number\n /**\n * Log route summary on startup. Default: true in dev, false in production.\n * Set to `true` to always log, `false` to always suppress.\n */\n logRoutesTable?: boolean\n /**\n * Maximum time (ms) to wait for graceful shutdown before forcing exit.\n * Default: 30000 (30 seconds). Set to 0 to disable forced exit.\n */\n shutdownTimeout?: number\n\n /**\n * Enable cluster mode for multi-core utilization.\n *\n * When enabled, the primary process forks worker processes that share the\n * same port via Node's built-in `cluster` module (OS load balancing).\n *\n * - `true` — use all available CPU cores\n * - `{ workers: N }` — use exactly N workers\n *\n * Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is\n * forwarded to all workers.\n *\n * @example\n * ```ts\n * bootstrap({ modules, cluster: true })\n * bootstrap({ modules, cluster: { workers: 4 } })\n * ```\n */\n cluster?: boolean | { workers?: number }\n\n /**\n * Custom 404 handler for unmatched routes. Receives the raw Express\n * `(req, res, next)` args. When omitted, the built-in handler returns\n * `{ message: 'Not Found' }` with status 404.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onNotFound: (req, res) => {\n * res.status(404).json({ error: 'Route not found', path: req.originalUrl })\n * },\n * })\n * ```\n */\n onNotFound?: (req: any, res: any, next: any) => void\n\n /**\n * Custom global error handler. Receives `(err, req, res, next)` — the\n * standard Express error-handling signature. When omitted, the built-in\n * handler formats ZodError, HttpException, and unexpected errors.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onError: (err, req, res, next) => {\n * logger.error(err)\n * res.status(err.status ?? 500).json({ error: err.message })\n * },\n * })\n * ```\n */\n onError?: (err: any, req: any, res: any, next: any) => void\n\n /**\n * Security defaults applied automatically unless opted out.\n *\n * When not specified, secure defaults are applied:\n * - Helmet security headers are auto-injected\n * - JSON body limit defaults to 1MB\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * security: {\n * helmet: false, // disable auto-helmet\n * },\n * })\n * ```\n */\n security?: {\n /** Auto-inject helmet security headers. Default: true */\n helmet?: boolean\n }\n}\n\n/**\n * The main application class. Wires together Express, the DI container,\n * feature modules, adapters, and the middleware pipeline.\n */\nexport class Application {\n private app: Express\n private container: Container\n private httpServer: http.Server | null = null\n private adapters: AppAdapter[]\n\n private plugins: KickPlugin[]\n\n /** Number of HTTP requests currently being processed */\n private _inFlightRequests = 0\n /** Whether the application is draining (shutting down gracefully) */\n private _draining = false\n /** Whether shutdown has already been initiated (prevents double-shutdown) */\n private _shutdownInitiated = false\n /** Resolvers waiting for in-flight requests to reach zero */\n private _drainResolvers: Array<() => void> = []\n\n constructor(private readonly options: ApplicationOptions) {\n this.app = express()\n this.container = Container.getInstance()\n this.plugins = options.plugins ?? []\n this.adapters = [\n // Plugin adapters first\n ...this.plugins.flatMap((p) => p.adapters?.() ?? []),\n ...(options.adapters ?? []),\n ]\n // Wire the request store provider so Container can resolve REQUEST-scoped deps\n Container._requestStoreProvider = () => requestStore.getStore() ?? null\n // Wire logger context provider so logs auto-include requestId\n Logger._contextProvider = () => {\n const store = requestStore.getStore()\n if (!store) return null\n const ctx: Record<string, any> = { requestId: store.requestId }\n const traceId = store.values.get('traceId')\n if (traceId) ctx.traceId = traceId\n const spanId = store.values.get('spanId')\n if (spanId) ctx.spanId = spanId\n return ctx\n }\n }\n\n /** Whether the application is currently draining in-flight requests */\n get isDraining(): boolean {\n return this._draining\n }\n\n /** Number of HTTP requests currently being processed */\n get inFlightRequests(): number {\n return this._inFlightRequests\n }\n\n /** Get the DI container instance */\n getContainer(): Container {\n return this.container\n }\n\n /**\n * Express request handler — delegates to the internal Express app.\n *\n * Used by the Vite dev-server plugin to route requests through KickJS:\n * ```ts\n * const mod = await ssrLoadModule('virtual:kickjs/app')\n * mod.app.handle(req, res, next)\n * ```\n *\n * Also works as a standard Node.js request handler for production:\n * ```ts\n * http.createServer(app.handle.bind(app))\n * ```\n */\n handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n if (next) {\n this.app(req as any, res as any, next)\n } else {\n this.app(req as any, res as any)\n }\n }\n\n /**\n * Full setup pipeline:\n * 1. Adapter beforeMount hooks (early routes — docs, health)\n * 2. Adapter middleware (phase: beforeGlobal)\n * 3. Global middleware (user-declared or defaults)\n * 4. Adapter middleware (phase: afterGlobal)\n * 5. Module registration + DI bootstrap\n * 6. Adapter middleware (phase: beforeRoutes)\n * 7. Module route mounting\n * 8. Adapter middleware (phase: afterRoutes)\n * 9. Error handlers (notFound + global)\n * 10. Adapter beforeStart hooks\n */\n /** Build the adapter context object (shared across all hooks) */\n private adapterCtx(server?: any): AdapterContext {\n const env = process.env.NODE_ENV ?? 'development'\n return {\n app: this.app,\n container: this.container,\n server,\n env,\n isProduction: env === 'production',\n }\n }\n\n /** Call an adapter hook, awaiting async hooks and catching errors */\n private async callHook(\n hook: ((ctx: AdapterContext) => void | Promise<void>) | undefined,\n ctx: AdapterContext,\n ): Promise<void> {\n if (!hook) return\n try {\n const result = hook(ctx)\n if (result && typeof (result as Promise<void>).then === 'function') {\n await result\n }\n } catch (err) {\n log.error(err, 'Adapter hook failed')\n }\n }\n\n async setup(): Promise<void> {\n log.debug('Bootstrapping application...')\n\n // Collect adapter middleware by phase\n const adapterMw = this.collectAdapterMiddleware()\n\n // Expose the Application instance on the Express app for adapter discovery\n ;(this.app as any).__kickApp = this\n\n const ctx = this.adapterCtx()\n\n // ── 1. Adapter beforeMount hooks ──────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeMount?.bind(adapter), ctx)\n }\n\n // ── 2. Hardened defaults ──────────────────────────────────────────\n this.app.disable('x-powered-by')\n this.app.set('trust proxy', this.options.trustProxy ?? false)\n\n // ── 2a. In-flight request tracking ──────────────────────────────\n this.app.use(this.requestTrackingMiddleware())\n\n // ── 2b. Health check endpoints (before middleware, at root) ──────\n this.mountHealthEndpoints()\n\n // ── 2c. Request scope (AsyncLocalStorage) ────────────────────────\n this.app.use(requestScopeMiddleware())\n\n // ── 3. Adapter middleware: beforeGlobal ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeGlobal)\n\n // ── 3b. Plugin registration ──────────────────────────────────────\n for (const plugin of this.plugins) {\n plugin.register?.(this.container)\n }\n\n // ── 3c. Plugin middleware ─────────────────────────────────────────\n for (const plugin of this.plugins) {\n try {\n const mw = plugin.middleware?.() ?? []\n for (const handler of mw) {\n this.app.use(handler)\n }\n } catch (err) {\n log.error(err, `Plugin middleware failed: ${(plugin as any).name ?? 'unknown'}`)\n }\n }\n\n // ── 4. Global middleware ─────────────────────────────────────────\n // Auto-inject helmet unless opted out\n const autoHelmet = this.options.security?.helmet !== false\n if (autoHelmet) {\n try {\n const { helmet: helmetFn } = await import('./middleware/helmet')\n this.app.use(helmetFn())\n } catch {\n // helmet middleware not available — skip silently\n }\n }\n\n if (this.options.middleware) {\n // User-declared pipeline — full control\n for (const entry of this.options.middleware) {\n this.mountMiddlewareEntry(entry)\n }\n } else {\n // Sensible defaults when no middleware declared\n this.app.use(requestId())\n this.app.use(express.json({ limit: this.options.jsonLimit ?? '1mb' }))\n }\n\n // ── 5. Adapter middleware: afterGlobal ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterGlobal)\n\n // ── 6. Module registration + DI bootstrap ────────────────────────\n // Plugin modules first, then user modules\n const allModuleClasses = [\n ...this.plugins.flatMap((p) => p.modules?.() ?? []),\n ...this.options.modules,\n ]\n const modules = allModuleClasses.map((ModuleClass) => {\n const mod = new ModuleClass()\n // `register()` is optional — modules whose classes are entirely\n // decorator-managed (@Service, @Controller, @Repository) don't need it.\n mod.register?.(this.container)\n return mod\n })\n this.container.bootstrap()\n\n // ── 7. Adapter middleware: beforeRoutes ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeRoutes)\n\n // ── 8. Mount module routes with versioning ───────────────────────\n const apiPrefix = this.options.apiPrefix ?? '/api'\n const defaultVersion = this.options.defaultVersion ?? 1\n const shouldLogRoutes = this.options.logRoutesTable ?? process.env.NODE_ENV !== 'production'\n\n // Collect route metadata during mounting (avoids calling mod.routes() twice)\n const mountedRoutes: Array<{ controller: any; mountPath: string }> = []\n\n for (const mod of modules) {\n const result = mod.routes()\n if (!result) continue // Non-HTTP modules (queues, cron) may return null\n\n const routeSets = Array.isArray(result) ? result : [result]\n\n for (const route of routeSets) {\n const version = route.version ?? defaultVersion\n const mountPath = `${apiPrefix}/v${version}${normalizePath(route.path)}`\n this.app.use(mountPath, route.router)\n\n // Notify adapters (e.g. SwaggerAdapter for OpenAPI spec generation)\n if (route.controller) {\n for (const adapter of this.adapters) {\n try {\n adapter.onRouteMount?.(route.controller, mountPath)\n } catch (err) {\n log.error(err, `adapter.onRouteMount() failed for ${mountPath}`)\n }\n }\n if (shouldLogRoutes) {\n mountedRoutes.push({ controller: route.controller, mountPath })\n }\n }\n }\n }\n\n // ── 8b. Log route summary ─────────────────────────────────────────\n if (shouldLogRoutes && mountedRoutes.length > 0) {\n const methodOrder = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']\n const methodRank = (m: string) => {\n const i = methodOrder.indexOf(m)\n return i === -1 ? 99 : i\n }\n\n let totalRoutes = 0\n log.debug('Routes:')\n\n for (const { controller, mountPath } of mountedRoutes) {\n const defs: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controller,\n [],\n )\n if (defs.length === 0) continue\n\n const counts: Record<string, number> = {}\n for (const def of defs) {\n const m = def.method.toUpperCase()\n counts[m] = (counts[m] || 0) + 1\n }\n totalRoutes += defs.length\n\n const methods = Object.entries(counts)\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([m, n]) => `${n} ${m}`)\n .join(', ')\n const name = controller.name || 'Controller'\n log.debug(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)\n }\n\n log.debug(` Total: ${totalRoutes} routes`)\n }\n\n // ── 9. Adapter middleware: afterRoutes ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterRoutes)\n\n // ── 10. Error handlers ───────────────────────────────────────────\n this.app.use(this.options.onNotFound ?? notFoundHandler())\n this.app.use(this.options.onError ?? errorHandler())\n\n // ── 11. Adapter beforeStart hooks ────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeStart?.bind(adapter), ctx)\n }\n }\n\n /** Register modules and DI without starting the HTTP server (used by kick tinker) */\n async registerOnly(): Promise<void> {\n await this.setup()\n }\n\n /**\n * Start the HTTP server.\n *\n * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`\n * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real\n * `http.Server` through `afterStart({ server })` — zero adapter changes needed.\n *\n * In **production**: creates its own `http.Server` and binds to the port.\n */\n async start(): Promise<void> {\n await this.setup()\n\n const g = globalThis as any\n\n if (g.__kickjs_httpServer) {\n // ── DEV MODE: Vite owns the http.Server ──────────────────────\n // Don't create a new server or listen — Vite is already listening.\n // Just wire up adapters with the Vite-created server.\n this.httpServer = g.__kickjs_httpServer\n log.debug('Attached to Vite dev server')\n\n for (const adapter of this.adapters) {\n const ctx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), ctx)\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n return\n }\n\n // ── PRODUCTION: Create and own the http.Server ─────────────────\n const port = this.options.port ?? parseInt(process.env.PORT || '3000', 10)\n this.httpServer = http.createServer(this.app)\n\n this.httpServer.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n log.error(\n `Port ${port} is already in use. Kill the existing process or use a different port:\\n` +\n ` PORT=${port + 1} kick dev\\n` +\n ` lsof -i :${port} # find what's using it\\n` +\n ` kill <PID> # stop it`,\n )\n process.exit(1)\n }\n throw err\n })\n\n // Wrap listen in a Promise so afterStart/onReady errors propagate\n await new Promise<void>((resolve, reject) => {\n this.httpServer!.listen(port, async () => {\n try {\n log.info(`Server running on http://localhost:${port}`)\n\n for (const adapter of this.adapters) {\n const afterCtx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), afterCtx)\n }\n\n // Plugin onReady hooks\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n resolve()\n } catch (err) {\n reject(err)\n }\n })\n })\n }\n\n /** HMR rebuild: swap Express handler without restarting the server */\n async rebuild(): Promise<void> {\n // Build the new app fully before swapping — if setup() throws,\n // the old app keeps running so the server stays responsive.\n const prevApp = this.app\n const prevContainer = this.container\n\n try {\n Container.reset()\n this.container = Container.getInstance()\n this.app = express()\n await this.setup()\n } catch (err) {\n log.error(err, 'HMR rebuild failed, keeping previous app')\n // Restore previous state so the server stays responsive\n this.app = prevApp\n this.container = prevContainer\n return\n }\n\n if (this.httpServer) {\n this.httpServer.removeAllListeners('request')\n this.httpServer.on('request', this.app)\n log.debug('HMR: Express app rebuilt and swapped')\n }\n }\n\n /**\n * Graceful shutdown with request draining.\n *\n * 1. Stops accepting new connections (server.close())\n * 2. Waits for in-flight requests to complete (up to shutdownTimeout)\n * 3. Calls adapter.shutdown() for all registered adapters\n * 4. Force-closes after timeout\n *\n * Safe to call multiple times — subsequent calls return the same promise.\n */\n async shutdown(): Promise<void> {\n // Prevent double-shutdown — return immediately if already initiated\n if (this._shutdownInitiated) {\n log.debug('Shutdown already in progress, skipping duplicate call')\n return\n }\n this._shutdownInitiated = true\n this._draining = true\n\n log.debug('Shutting down — draining in-flight requests...')\n\n const timeoutMs = this.options.shutdownTimeout ?? 30_000\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // Start a force-exit timer if timeout is configured\n const forceExitPromise =\n timeoutMs > 0\n ? new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n timer.unref()\n })\n : new Promise<never>(() => {}) // never resolves — no forced exit\n\n try {\n // Step 1: Stop accepting new connections.\n // server.close() prevents new connections. Its callback fires only when\n // ALL existing connections are fully closed, so we do NOT await it here —\n // we track request draining separately via the tracking middleware.\n if (this.httpServer) {\n this.httpServer.close(() => {})\n }\n\n // Step 2: Wait for in-flight requests to drain (or timeout)\n if (this._inFlightRequests > 0) {\n log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`)\n const drainPromise = new Promise<'drained'>((resolve) => {\n this._drainResolvers.push(() => resolve('drained'))\n })\n\n const result = await Promise.race([drainPromise, forceExitPromise])\n if (result === 'timeout') {\n log.warn(\n `Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`,\n )\n } else {\n log.debug('All in-flight requests completed')\n }\n }\n\n // Step 3: Run all plugin + adapter shutdowns concurrently\n const results = await Promise.allSettled([\n ...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())),\n ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.())),\n ])\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error({ err: result.reason }, 'Adapter shutdown failed')\n }\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n getExpressApp(): Express {\n return this.app\n }\n\n /** Get registered adapters — used by DevToolsAdapter for peer discovery */\n getAdapters(): AppAdapter[] {\n return this.adapters\n }\n\n getHttpServer(): http.Server | null {\n return this.httpServer\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n private collectAdapterMiddleware() {\n const result = {\n beforeGlobal: [] as AdapterMiddleware[],\n afterGlobal: [] as AdapterMiddleware[],\n beforeRoutes: [] as AdapterMiddleware[],\n afterRoutes: [] as AdapterMiddleware[],\n }\n\n for (const adapter of this.adapters) {\n const entries = adapter.middleware?.() ?? []\n for (const entry of entries) {\n const phase = entry.phase ?? 'afterGlobal'\n result[phase].push(entry)\n }\n }\n\n return result\n }\n\n private mountMiddlewareList(entries: AdapterMiddleware[]): void {\n for (const entry of entries) {\n if (entry.path) {\n this.app.use(entry.path, entry.handler)\n } else {\n this.app.use(entry.handler)\n }\n }\n }\n\n private mountMiddlewareEntry(entry: MiddlewareEntry): void {\n if (typeof entry === 'function') {\n this.app.use(entry)\n } else {\n this.app.use(entry.path, entry.handler)\n }\n }\n\n /** Middleware that tracks in-flight requests for graceful draining */\n private requestTrackingMiddleware(): RequestHandler {\n return (_req, res, next) => {\n this._inFlightRequests++\n const onFinish = () => {\n res.removeListener('finish', onFinish)\n res.removeListener('close', onFinish)\n this._inFlightRequests--\n // If draining and no more in-flight requests, resolve all waiters\n if (this._draining && this._inFlightRequests === 0) {\n for (const resolve of this._drainResolvers) {\n resolve()\n }\n this._drainResolvers = []\n }\n }\n res.on('finish', onFinish)\n res.on('close', onFinish)\n next()\n }\n }\n\n /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */\n private mountHealthEndpoints(): void {\n this.app.get('/health/live', (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', uptime: process.uptime() })\n } else {\n res.json({ status: 'ok', uptime: process.uptime() })\n }\n })\n\n this.app.get('/health/ready', async (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', checks: [] })\n return\n }\n const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck)\n const checks = await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck!()))\n const results = checks.map((c, i) => {\n if (c.status === 'fulfilled') return c.value\n return { name: adaptersWithHealth[i].name ?? 'unknown', status: 'down' as const }\n })\n const healthy = results.every((r) => r.status === 'up')\n res.status(healthy ? 200 : 503).json({\n status: healthy ? 'ready' : 'degraded',\n checks: results,\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,eAAe,IAAI,mBAAiC;;;;;AAMjE,SAAgB,kBAAgC;CAC9C,MAAM,QAAQ,aAAa,UAAU;AACrC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,kGACD;AAEH,QAAO;;;;;;;;;;AChBT,SAAgB,yBAAyB;AACvC,SAAQ,KAAc,MAAgB,SAAuB;EAC3D,MAAM,kBAAkB,IAAI,QAAQ;EAGpC,MAAM,QAAsB;GAC1B,YAFC,MA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AI,KAAK,WAAW;AAClB,QAAI,OAAO,IAAI,CAAC,KAAK;KAAE,QAAQ;KAAY,QAAQ,EAAE;KAAE,CAAC;AACxD;;GAEF,MAAM,qBAAqB,KAAK,SAAS,QAAQ,MAAM,EAAE,cAAc;GAEvE,MAAM,WADS,MAAM,QAAQ,WAAW,mBAAmB,KAAK,MAAM,EAAE,eAAgB,CAAC,CAAC,EACnE,KAAK,GAAG,MAAM;AACnC,QAAI,EAAE,WAAW,YAAa,QAAO,EAAE;AACvC,WAAO;KAAE,MAAM,mBAAmB,GAAG,QAAQ;KAAW,QAAQ;KAAiB;KACjF;GACF,MAAM,UAAU,QAAQ,OAAO,MAAM,EAAE,WAAW,KAAK;AACvD,OAAI,OAAO,UAAU,MAAM,IAAI,CAAC,KAAK;IACnC,QAAQ,UAAU,UAAU;IAC5B,QAAQ;IACT,CAAC;IACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v3.0.
|
|
2
|
+
* @forinda/kickjs v3.0.8
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,11 +9,11 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import { createLogger } from "./core/logger.mjs";
|
|
12
|
-
import { t as Container } from "./container-
|
|
13
|
-
import "./core-
|
|
12
|
+
import { t as Container } from "./container-qU5VqCDl.mjs";
|
|
13
|
+
import "./core-Dff8TsH9.mjs";
|
|
14
14
|
import { reactive, ref } from "./core/reactivity.mjs";
|
|
15
|
-
import { t as Application } from "./application-
|
|
16
|
-
import { a as reloadEnv } from "./env-
|
|
15
|
+
import { t as Application } from "./application-Cx7ysduz.mjs";
|
|
16
|
+
import { a as reloadEnv } from "./env-C0PEyw21.mjs";
|
|
17
17
|
import cluster from "node:cluster";
|
|
18
18
|
import os from "node:os";
|
|
19
19
|
//#region src/http/cluster.ts
|
|
@@ -189,4 +189,4 @@ async function bootstrap(options) {
|
|
|
189
189
|
//#endregion
|
|
190
190
|
export { isClusterPrimary as n, bootstrap as t };
|
|
191
191
|
|
|
192
|
-
//# sourceMappingURL=bootstrap-
|
|
192
|
+
//# sourceMappingURL=bootstrap-BoZYtuO7.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap-DV13o-cB.mjs","names":["log"],"sources":["../src/http/cluster.ts","../src/http/bootstrap.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n cluster.fork()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n cluster.fork()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","import cluster from 'node:cluster'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers ────────────────────────────────────────────\n if (!g.__kickBootstrapped) {\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n })\n\n if (!g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;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,OAAO;AAEjB,QAAO"}
|
|
1
|
+
{"version":3,"file":"bootstrap-BoZYtuO7.mjs","names":["log"],"sources":["../src/http/cluster.ts","../src/http/bootstrap.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n cluster.fork()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n cluster.fork()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","import cluster from 'node:cluster'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers ────────────────────────────────────────────\n if (!g.__kickBootstrapped) {\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n })\n\n if (!g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,MAAMA,QAAM,aAAa,UAAU;;AAgBnC,SAAgB,mBAA4B;AAC1C,QAAO,QAAQ;;;;;;;;;;;;;;;;AAiBjB,SAAgB,oBAAoB,MAA4B;CAC9D,MAAM,aAAa,K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*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import { a as reloadEnv, i as loadEnv, n as defineEnv, o as resetEnvCache, r as getEnv, t as baseEnvSchema } from "../env-
|
|
12
|
-
import { n as createConfigService, t as ConfigService } from "../config-
|
|
11
|
+
import { a as reloadEnv, i as loadEnv, n as defineEnv, o as resetEnvCache, r as getEnv, t as baseEnvSchema } from "../env-C0PEyw21.mjs";
|
|
12
|
+
import { n as createConfigService, t as ConfigService } from "../config-CX1Xo3is.mjs";
|
|
13
13
|
export { ConfigService, baseEnvSchema, createConfigService, defineEnv, getEnv, loadEnv, reloadEnv, resetEnvCache };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v3.0.
|
|
2
|
+
* @forinda/kickjs v3.0.8
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import { Service } from "./core/decorators.mjs";
|
|
12
|
-
import { a as reloadEnv, i as loadEnv } from "./env-
|
|
12
|
+
import { a as reloadEnv, i as loadEnv } from "./env-C0PEyw21.mjs";
|
|
13
13
|
//#region \0@oxc-project+runtime@0.122.0/helpers/decorate.js
|
|
14
14
|
function __decorate(decorators, target, key, desc) {
|
|
15
15
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
@@ -132,4 +132,4 @@ function createConfigService(schema) {
|
|
|
132
132
|
//#endregion
|
|
133
133
|
export { createConfigService as n, ConfigService as t };
|
|
134
134
|
|
|
135
|
-
//# sourceMappingURL=config-
|
|
135
|
+
//# sourceMappingURL=config-CX1Xo3is.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-
|
|
1
|
+
{"version":3,"file":"config-CX1Xo3is.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T> {\n return this.env[key] as ConfigValue<K, T>\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller('/users')\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K] {\n return this.env[key]\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+CO,IAAA,gBAAA,MAAM,cAAc;;;;;;;;;;;;;;CAczB,IAAY,MAA2B;AACrC,SAAO,SAAS;;;;;;;;;;;CAYlB,IAA+B,KAAsC;AACnE,SAAO,KAAK,IAAI;;;;;;;CAQlB,SAAuF;AACrF,SAAO,OAAO,OAAO,EAAE,GAAG,KAAK,KAAK,CAAC;;;CAIvC,SAAe;AACb,aAAW;AAEX,WAAS;;CAGX,eAAwB;AACtB,SAAO,KAAK,IAAI,aAAa;;CAG/B,gBAAyB;AACvB,SAAO,KAAK,IAAI,aAAa;;CAG/B,SAAkB;AAChB,SAAO,KAAK,IAAI,aAAa;;;4BAzDhC,SAAS,CAAA,EAAA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGV,SAAgB,oBAAgD,QAAW;CAGzE,IAAA,sBAAA,MACM,oBAAwD;;EAE5D,IAAY,MAAY;AACtB,UAAO,QAAQ,OAAO;;EAGxB,IAAmC,KAAiB;AAClD,UAAO,KAAK,IAAI;;EAGlB,SAAyB;AACvB,UAAO,OAAO,OAAO,EAAE,GAAG,KAAK,KAAK,CAAC;;EAGvC,SAAe;AACb,cAAW;AACX,WAAQ,OAAO;;EAGjB,eAAwB;AACtB,UAAO,KAAK,IAAI,aAAa;;EAG/B,gBAAyB;AACvB,UAAO,KAAK,IAAI,aAAa;;EAG/B,SAAkB;AAChB,UAAO,KAAK,IAAI,aAAa;;;mCA7BhC,SAAS,CAAA,EAAA,oBAAA;AAiCV,QAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v3.0.
|
|
2
|
+
* @forinda/kickjs v3.0.8
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { METADATA, Scope } from "./core/interfaces.mjs";
|
|
12
12
|
import { createLogger } from "./core/logger.mjs";
|
|
13
|
-
import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "./metadata-
|
|
13
|
+
import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "./metadata-BLB2BbI7.mjs";
|
|
14
14
|
import "reflect-metadata";
|
|
15
15
|
//#region src/core/token.ts
|
|
16
16
|
/**
|
|
@@ -493,4 +493,4 @@ var Container = class Container {
|
|
|
493
493
|
//#endregion
|
|
494
494
|
export { isInjectionToken as a, createToken as i, tokenName as n, INJECTION_TOKEN as r, Container as t };
|
|
495
495
|
|
|
496
|
-
//# sourceMappingURL=container-
|
|
496
|
+
//# sourceMappingURL=container-qU5VqCDl.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container-DrJQ6Zgx.mjs","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"sourcesContent":["/**\n * Collision-safe injection tokens with phantom type parameters.\n *\n * `createToken<T>(name)` is the recommended way to declare any DI token\n * that isn't a class. Each call returns a unique frozen object — even if\n * two files write `createToken<X>('Logger')`, they produce two distinct\n * references that the container treats as different tokens. Collisions\n * become impossible by construction, not by convention.\n *\n * The phantom type parameter `T` lets `container.resolve(token)` infer\n * the correct return type without any codegen.\n *\n * ## Hardening layers\n *\n * KickJS has four DI token kinds, listed from safest to riskiest:\n *\n * 1. **Class identity** — `container.resolve(UserService)`. Reference\n * equality, never collides. Type-safe via `Constructor<T>` overload.\n * 2. **`createToken<T>(name)`** — frozen object identity, never collides.\n * Type-safe via the `InjectionToken<T>` overload.\n * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`\n * is interned and CAN collide. Discouraged.\n * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.\n * Reserved for legacy code and runtime-computed token names.\n *\n * Prefer (1) and (2). Use (4) only when you have to.\n *\n * @example\n * ```ts\n * // src/tokens.ts\n * export const DATABASE_URL = createToken<string>('config.database.url')\n * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')\n *\n * // bootstrap\n * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)\n *\n * // anywhere else\n * const url = container.resolve(DATABASE_URL) // typed as `string`\n * ```\n *\n * @module @forinda/kickjs/core/token\n */\n\n/**\n * Symbol marker stamped on every InjectionToken so the container can\n * detect them at runtime regardless of which package created them.\n *\n * Uses `Symbol.for()` so cross-package isolation (different copies of\n * `@forinda/kickjs` loaded under different module identities) still\n * shares the same marker.\n */\nexport const INJECTION_TOKEN: unique symbol = Symbol.for('@kickjs/InjectionToken') as never\n\n/**\n * A type-safe DI token. Each `createToken()` call returns a unique frozen\n * object identified by reference, not by the `name` string. Two\n * `createToken<X>('foo')` calls in different files produce two distinct\n * tokens that the container treats independently.\n *\n * The phantom `_type` parameter is never assigned at runtime — it exists\n * solely to thread the type through `container.resolve(token)`.\n */\nexport interface InjectionToken<T> {\n readonly [INJECTION_TOKEN]: true\n /** Descriptive name used in error messages, logs, and devtools */\n readonly name: string\n /** Phantom — never assigned at runtime */\n readonly _type?: T\n}\n\n/**\n * Create a collision-safe injection token.\n *\n * The returned token is a frozen object identified by reference, not by\n * the `name` string. The `name` is used only for error messages, logs,\n * and debugging.\n */\nexport function createToken<T>(name: string): InjectionToken<T> {\n return Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name,\n })\n}\n\n/** Type guard — returns `true` if `value` is an InjectionToken */\nexport function isInjectionToken(value: unknown): value is InjectionToken<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[INJECTION_TOKEN] === true\n )\n}\n","import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\nimport { isInjectionToken, type InjectionToken } from './token'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n if (isInjectionToken(token)) return token.name\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\n/**\n * Type-safe registry of string DI tokens. Augmented by `kick typegen` —\n * the generated `.kickjs/types/registry.d.ts` adds entries like:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickJsRegistry {\n * UserService: import('../../src/modules/users/user.service').UserService\n * }\n * }\n * ```\n *\n * Once typegen has run, `container.resolve('UserService')` returns the\n * correct type instead of `any`. Class-token resolution\n * (`container.resolve(UserService)`) is already type-safe via the\n * `Constructor<T>` overload and does not need typegen.\n */\nexport interface KickJsRegistry {}\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by @forinda/kickjs-config\n * to return Zod-validated, type-coerced env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http\n * to return the current request's AsyncLocalStorage store.\n * Returns { instances: Map, values: Map } or null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /**\n * Resolve a dependency by its token.\n *\n * Four overloads, in order of preference:\n * - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.\n * Collision-safe by construction; no codegen required.\n * - **Class constructor** → returns an instance of that class. Always\n * type-safe; no codegen required.\n * - **String token in `KickJsRegistry`** (populated by `kick typegen`) →\n * returns the augmented type.\n * - **Anything else** → returns `any`. Use this only for legacy code or\n * string tokens that haven't been registered with typegen yet.\n */\n resolve<T>(token: InjectionToken<T>): T\n resolve<T>(token: Constructor<T>): T\n resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K]\n resolve<T = any>(token: any): T\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (set by @forinda/kickjs-config)\n // This returns Zod-validated, type-coerced values (e.g. PORT as number)\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps not using @forinda/kickjs-config\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAa,kBAAiC,OAAO,IAAI,yBAAyB;;;;;;;;AA0BlF,SAAgB,YAAe,MAAiC;AAC9D,QAAO,OAAO,OAAO;GAClB,kBAAkB;EACnB;EACD,CAAC;;;AAIJ,SAAgB,iBAAiB,OAAkD;AACjF,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,qBAAqB;;;;ACvE5D,MAAM,MAAM,aAAa,YAAY;;AAmBrC,SAAS,UACP,QACc;AACd,QAAO;EACL,MAAM;EACN,cAAc;EACd,qBAAqB;EACrB,cAAc,EAAE;EAChB,GAAG;EACJ;;;AAIH,SAAgB,UAAU,OAAoB;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,KAAI,iBAAiB,MAAM,CAAE,QAAO,MAAM;AAC1C,QAAO,OAAO,QAAQ,O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AErE;SAED,KAAI,sBAAsB;WAErB,KAAK;AACZ,OAAI,sBAAsB;AAC1B,OAAI,MACF,KACA,qBAAqB,UAAU,IAAI,OAAO,CAAC,GAAG,OAAO,cAAc,CAAC,mBACrE;;AAIL,SAAO;;;CAIT,oBAA4B,QAA+B;EACzD,MAAM,aAAa,aAA4B,SAAS,aAAa,QAAQ,EAAE,CAAC;EAChF,MAAM,eAAe,cAAmB,SAAS,QAAQ,OAAO;AAChE,SAAO,WAAW,KAAK,MAAM,UAAU;AAErC,UAAO,UADO,aAAa,UAAU,KACd;IACvB;;CAGJ,iBAAyB,UAAe,QAA2B;EAEjE,MAAM,iBAAiB,WAAwB,SAAS,WAAW,OAAO,UAAU;AAEpF,OAAK,MAAM,CAAC,MAAM,UAAU,gBAAgB;GAC1C,MAAM,gBACJ,SAAS,yBAAyB,SAAS,eAAe,OAAO,WAAW,KAAK;AACnF,OAAI,cACF,QAAO,eAAe,UAAU,MAAM;IACpC,WAAW,KAAK,QAAQ,cAAc;IACtC,YAAY;IACZ,cAAc;IACf,CAAC;;EAKN,MAAM,aAAa,WACjB,SAAS,OACT,OAAO,UACR;AAED,OAAK,MAAM,CAAC,MAAM,WAAW,WAC3B,QAAO,eAAe,UAAU,MAAM;GACpC,MAAM;AAGJ,QAAI,UAAU,cAAc;KAC1B,MAAM,MAAM,UAAU,aAAa,OAAO,OAAO;AACjD,SAAI,QAAQ,KAAA,EAAW,QAAO;;IAIhC,MAAM,MAAM,QAAQ,IAAI,OAAO;AAC/B,QAAI,QAAQ,KAAA,EAAW,QAAO;AAC9B,QAAI,OAAO,iBAAiB,KAAA,EAAW,QAAO,OAAO;AACrD,UAAM,IAAI,MACR,WAAW,OAAO,OAAO,4BAA4B,OAAO,OAAO,2CACpE;;GAEH,YAAY;GACZ,cAAc;GACf,CAAC"}
|
|
1
|
+
{"version":3,"file":"container-qU5VqCDl.mjs","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"sourcesContent":["/**\n * Collision-safe injection tokens with phantom type parameters.\n *\n * `createToken<T>(name)` is the recommended way to declare any DI token\n * that isn't a class. Each call returns a unique frozen object — even if\n * two files write `createToken<X>('Logger')`, they produce two distinct\n * references that the container treats as different tokens. Collisions\n * become impossible by construction, not by convention.\n *\n * The phantom type parameter `T` lets `container.resolve(token)` infer\n * the correct return type without any codegen.\n *\n * ## Hardening layers\n *\n * KickJS has four DI token kinds, listed from safest to riskiest:\n *\n * 1. **Class identity** — `container.resolve(UserService)`. Reference\n * equality, never collides. Type-safe via `Constructor<T>` overload.\n * 2. **`createToken<T>(name)`** — frozen object identity, never collides.\n * Type-safe via the `InjectionToken<T>` overload.\n * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`\n * is interned and CAN collide. Discouraged.\n * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.\n * Reserved for legacy code and runtime-computed token names.\n *\n * Prefer (1) and (2). Use (4) only when you have to.\n *\n * @example\n * ```ts\n * // src/tokens.ts\n * export const DATABASE_URL = createToken<string>('config.database.url')\n * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')\n *\n * // bootstrap\n * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)\n *\n * // anywhere else\n * const url = container.resolve(DATABASE_URL) // typed as `string`\n * ```\n *\n * @module @forinda/kickjs/core/token\n */\n\n/**\n * Symbol marker stamped on every InjectionToken so the container can\n * detect them at runtime regardless of which package created them.\n *\n * Uses `Symbol.for()` so cross-package isolation (different copies of\n * `@forinda/kickjs` loaded under different module identities) still\n * shares the same marker.\n */\nexport const INJECTION_TOKEN: unique symbol = Symbol.for('@kickjs/InjectionToken') as never\n\n/**\n * A type-safe DI token. Each `createToken()` call returns a unique frozen\n * object identified by reference, not by the `name` string. Two\n * `createToken<X>('foo')` calls in different files produce two distinct\n * tokens that the container treats independently.\n *\n * The phantom `_type` parameter is never assigned at runtime — it exists\n * solely to thread the type through `container.resolve(token)`.\n */\nexport interface InjectionToken<T> {\n readonly [INJECTION_TOKEN]: true\n /** Descriptive name used in error messages, logs, and devtools */\n readonly name: string\n /** Phantom — never assigned at runtime */\n readonly _type?: T\n}\n\n/**\n * Create a collision-safe injection token.\n *\n * The returned token is a frozen object identified by reference, not by\n * the `name` string. The `name` is used only for error messages, logs,\n * and debugging.\n */\nexport function createToken<T>(name: string): InjectionToken<T> {\n return Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name,\n })\n}\n\n/** Type guard — returns `true` if `value` is an InjectionToken */\nexport function isInjectionToken(value: unknown): value is InjectionToken<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[INJECTION_TOKEN] === true\n )\n}\n","import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\nimport { isInjectionToken, type InjectionToken } from './token'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n if (isInjectionToken(token)) return token.name\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\n/**\n * Type-safe registry of string DI tokens. Augmented by `kick typegen` —\n * the generated `.kickjs/types/registry.d.ts` adds entries like:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickJsRegistry {\n * UserService: import('../../src/modules/users/user.service').UserService\n * }\n * }\n * ```\n *\n * Once typegen has run, `container.resolve('UserService')` returns the\n * correct type instead of `any`. Class-token resolution\n * (`container.resolve(UserService)`) is already type-safe via the\n * `Constructor<T>` overload and does not need typegen.\n */\nexport interface KickJsRegistry {}\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by @forinda/kickjs-config\n * to return Zod-validated, type-coerced env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http\n * to return the current request's AsyncLocalStorage store.\n * Returns { instances: Map, values: Map } or null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /**\n * Resolve a dependency by its token.\n *\n * Four overloads, in order of preference:\n * - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.\n * Collision-safe by construction; no codegen required.\n * - **Class constructor** → returns an instance of that class. Always\n * type-safe; no codegen required.\n * - **String token in `KickJsRegistry`** (populated by `kick typegen`) →\n * returns the augmented type.\n * - **Anything else** → returns `any`. Use this only for legacy code or\n * string tokens that haven't been registered with typegen yet.\n */\n resolve<T>(token: InjectionToken<T>): T\n resolve<T>(token: Constructor<T>): T\n resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K]\n resolve<T = any>(token: any): T\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (set by @forinda/kickjs-config)\n // This returns Zod-validated, type-coerced values (e.g. PORT as number)\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps not using @forinda/kickjs-config\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAa,kBAAiC,OAAO,IAAI,yBAAyB;;;;;;;;AA0BlF,SAAgB,YAAe,MAAiC;AAC9D,QAAO,OAAO,OAAO;GAClB,kBAAkB;EACnB;EACD,CAAC;;;AAIJ,SAAgB,iBAAiB,OAAkD;AACjF,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,qBAAqB;;;;ACvE5D,MAAM,MAAM,aAAa,YAAY;;AAmBrC,SAAS,UACP,QACc;AACd,QAAO;EACL,MAAM;EACN,cAAc;EACd,qBAAqB;EACrB,cAAc,EAAE;EAChB,GAAG;EACJ;;;AAIH,SAAgB,UAAU,OAAoB;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,KAAI,iBAAiB,MAAM,CAAE,QAAO,MAAM;AAC1C,QAAO,OAAO,QAAQ,OAAO,MAAM;;AAsDrC,SAAS,qBAAsC;AAC7C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