@forinda/kickjs 2.0.1 → 2.1.0
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/adapter-BqGjZCSm.d.mts +122 -0
- package/dist/adapter-BqGjZCSm.d.mts.map +1 -0
- package/dist/app-module-CcEbAVtB.d.mts +33 -0
- package/dist/app-module-CcEbAVtB.d.mts.map +1 -0
- package/dist/application-DNHj-_UL.mjs +449 -0
- package/dist/application-DNHj-_UL.mjs.map +1 -0
- package/dist/bootstrap-DLEZaJ3b.mjs +205 -0
- package/dist/bootstrap-DLEZaJ3b.mjs.map +1 -0
- package/dist/{core/cache.d.ts → cache-DJeMaGqb.d.mts} +33 -31
- package/dist/cache-DJeMaGqb.d.mts.map +1 -0
- package/dist/chunk-C5Qp-JxE.mjs +15 -0
- package/dist/container-nBSIhyqV.d.mts +141 -0
- package/dist/container-nBSIhyqV.d.mts.map +1 -0
- package/dist/core/adapter.d.mts +3 -0
- package/dist/core/adapter.mjs +11 -0
- package/dist/core/app-module.d.mts +3 -0
- package/dist/core/app-module.mjs +11 -0
- package/dist/core/cache.d.mts +3 -0
- package/dist/core/cache.mjs +113 -0
- package/dist/core/cache.mjs.map +1 -0
- package/dist/core/container.d.mts +3 -0
- package/dist/core/container.mjs +426 -0
- package/dist/core/container.mjs.map +1 -0
- package/dist/core/cron.d.mts +3 -0
- package/dist/core/cron.mjs +42 -0
- package/dist/core/cron.mjs.map +1 -0
- package/dist/core/decorators.d.mts +3 -0
- package/dist/core/decorators.mjs +213 -0
- package/dist/core/decorators.mjs.map +1 -0
- package/dist/core/errors.d.mts +3 -0
- package/dist/core/errors.mjs +97 -0
- package/dist/core/errors.mjs.map +1 -0
- package/dist/core/interfaces.d.mts +3 -0
- package/dist/core/interfaces.mjs +44 -0
- package/dist/core/interfaces.mjs.map +1 -0
- package/dist/core/logger.d.mts +3 -0
- package/dist/core/logger.mjs +217 -0
- package/dist/core/logger.mjs.map +1 -0
- package/dist/core/path.d.mts +3 -0
- package/dist/core/path.mjs +45 -0
- package/dist/core/path.mjs.map +1 -0
- package/dist/core/plugin.d.mts +3 -0
- package/dist/core/plugin.mjs +11 -0
- package/dist/core/reactivity.d.mts +3 -0
- package/dist/core/reactivity.mjs +189 -0
- package/dist/core/reactivity.mjs.map +1 -0
- package/dist/core-BL_H8fEZ.mjs +121 -0
- package/dist/core-BL_H8fEZ.mjs.map +1 -0
- package/dist/{core/cron.d.ts → cron-RKhH5TOd.d.mts} +16 -14
- package/dist/cron-RKhH5TOd.d.mts.map +1 -0
- package/dist/decorators-CQ93ak6Z.d.mts +154 -0
- package/dist/decorators-CQ93ak6Z.d.mts.map +1 -0
- package/dist/errors-te5Km00o.d.mts +68 -0
- package/dist/errors-te5Km00o.d.mts.map +1 -0
- package/dist/http/application.d.mts +220 -0
- package/dist/http/application.d.mts.map +1 -0
- package/dist/http/application.mjs +12 -0
- package/dist/http/bootstrap.d.mts +43 -0
- package/dist/http/bootstrap.d.mts.map +1 -0
- package/dist/http/bootstrap.mjs +12 -0
- package/dist/http/context.d.mts +131 -0
- package/dist/http/context.d.mts.map +1 -0
- package/dist/http/context.mjs +220 -0
- package/dist/http/context.mjs.map +1 -0
- package/dist/http/middleware/cors.d.mts +48 -0
- package/dist/http/middleware/cors.d.mts.map +1 -0
- package/dist/http/middleware/cors.mjs +83 -0
- package/dist/http/middleware/cors.mjs.map +1 -0
- package/dist/http/middleware/csrf.d.mts +52 -0
- package/dist/http/middleware/csrf.d.mts.map +1 -0
- package/dist/http/middleware/csrf.mjs +72 -0
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +11 -0
- package/dist/http/middleware/error-handler.d.mts.map +1 -0
- package/dist/http/middleware/error-handler.mjs +52 -0
- package/dist/http/middleware/error-handler.mjs.map +1 -0
- package/dist/http/middleware/helmet.d.mts +41 -0
- package/dist/http/middleware/helmet.d.mts.map +1 -0
- package/dist/http/middleware/helmet.mjs +51 -0
- package/dist/http/middleware/helmet.mjs.map +1 -0
- package/dist/http/middleware/rate-limit.d.mts +56 -0
- package/dist/http/middleware/rate-limit.d.mts.map +1 -0
- package/dist/http/middleware/rate-limit.mjs +101 -0
- package/dist/http/middleware/rate-limit.mjs.map +1 -0
- package/dist/http/middleware/request-id.d.mts +10 -0
- package/dist/http/middleware/request-id.d.mts.map +1 -0
- package/dist/http/middleware/request-id.mjs +26 -0
- package/dist/http/middleware/request-id.mjs.map +1 -0
- package/dist/http/middleware/request-logger.d.mts +32 -0
- package/dist/http/middleware/request-logger.d.mts.map +1 -0
- package/dist/http/middleware/request-logger.mjs +49 -0
- package/dist/http/middleware/request-logger.mjs.map +1 -0
- package/dist/http/middleware/session.d.mts +67 -0
- package/dist/http/middleware/session.d.mts.map +1 -0
- package/dist/http/middleware/session.mjs +152 -0
- package/dist/http/middleware/session.mjs.map +1 -0
- package/dist/http/middleware/spa.d.mts +101 -0
- package/dist/http/middleware/spa.d.mts.map +1 -0
- package/dist/http/middleware/spa.mjs +108 -0
- package/dist/http/middleware/spa.mjs.map +1 -0
- package/dist/http/middleware/{upload.d.ts → upload.d.mts} +21 -17
- package/dist/http/middleware/upload.d.mts.map +1 -0
- package/dist/http/middleware/upload.mjs +191 -0
- package/dist/http/middleware/upload.mjs.map +1 -0
- package/dist/http/middleware/validate.d.mts +18 -0
- package/dist/http/middleware/validate.d.mts.map +1 -0
- package/dist/http/middleware/validate.mjs +62 -0
- package/dist/http/middleware/validate.mjs.map +1 -0
- package/dist/http/middleware/views.d.mts +62 -0
- package/dist/http/middleware/views.d.mts.map +1 -0
- package/dist/http/middleware/views.mjs +65 -0
- package/dist/http/middleware/views.mjs.map +1 -0
- package/dist/http/query/index.d.mts +3 -0
- package/dist/http/query/index.mjs +12 -0
- package/dist/http/{router-builder.d.ts → router-builder.d.mts} +9 -5
- package/dist/http/router-builder.d.mts.map +1 -0
- package/dist/http/router-builder.mjs +67 -0
- package/dist/http/router-builder.mjs.map +1 -0
- package/dist/index-C0gbnpSg.d.mts +107 -0
- package/dist/index-C0gbnpSg.d.mts.map +1 -0
- package/dist/index-Cls52etj.d.mts +148 -0
- package/dist/index-Cls52etj.d.mts.map +1 -0
- package/dist/index.d.mts +133 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +126 -0
- package/dist/index.mjs.map +1 -0
- package/dist/interfaces-D-48zotH.d.mts +52 -0
- package/dist/interfaces-D-48zotH.d.mts.map +1 -0
- package/dist/logger-Dzj-TF0t.d.mts +119 -0
- package/dist/logger-Dzj-TF0t.d.mts.map +1 -0
- package/dist/metadata-fmvikBA0.mjs +76 -0
- package/dist/metadata-fmvikBA0.mjs.map +1 -0
- package/dist/{core/path.d.ts → path-LmwfhfyH.d.mts} +7 -3
- package/dist/path-LmwfhfyH.d.mts.map +1 -0
- package/dist/plugin-DIoPIpSm.d.mts +95 -0
- package/dist/plugin-DIoPIpSm.d.mts.map +1 -0
- package/dist/query-7cdHF6ry.mjs +164 -0
- package/dist/query-7cdHF6ry.mjs.map +1 -0
- package/dist/{core/reactivity.d.ts → reactivity-BbS-99ow.d.mts} +21 -20
- package/dist/reactivity-BbS-99ow.d.mts.map +1 -0
- package/package.json +73 -43
- package/dist/chunk-DVVP7zzD.js +0 -7
- package/dist/core/adapter.d.ts +0 -109
- package/dist/core/adapter.d.ts.map +0 -1
- package/dist/core/adapter.js +0 -0
- package/dist/core/app-module.d.ts +0 -28
- package/dist/core/app-module.d.ts.map +0 -1
- package/dist/core/app-module.js +0 -0
- package/dist/core/cache.d.ts.map +0 -1
- package/dist/core/cache.js +0 -57
- package/dist/core/container.d.ts +0 -63
- package/dist/core/container.d.ts.map +0 -1
- package/dist/core/container.js +0 -117
- package/dist/core/cron.d.ts.map +0 -1
- package/dist/core/cron.js +0 -22
- package/dist/core/decorators.d.ts +0 -153
- package/dist/core/decorators.d.ts.map +0 -1
- package/dist/core/decorators.js +0 -141
- package/dist/core/errors.d.ts +0 -64
- package/dist/core/errors.d.ts.map +0 -1
- package/dist/core/errors.js +0 -67
- package/dist/core/index.d.ts +0 -14
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/interfaces.d.ts +0 -44
- package/dist/core/interfaces.d.ts.map +0 -1
- package/dist/core/interfaces.js +0 -25
- package/dist/core/logger.d.ts +0 -43
- package/dist/core/logger.d.ts.map +0 -1
- package/dist/core/logger.js +0 -54
- package/dist/core/path.d.ts.map +0 -1
- package/dist/core/path.js +0 -12
- package/dist/core/plugin.d.ts +0 -90
- package/dist/core/plugin.d.ts.map +0 -1
- package/dist/core/plugin.js +0 -0
- package/dist/core/reactivity.d.ts.map +0 -1
- package/dist/core/reactivity.js +0 -101
- package/dist/core-B6Okew3W.js +0 -7
- package/dist/http/application.d.ts +0 -103
- package/dist/http/application.d.ts.map +0 -1
- package/dist/http/application.js +0 -167
- package/dist/http/bootstrap.d.ts +0 -22
- package/dist/http/bootstrap.d.ts.map +0 -1
- package/dist/http/bootstrap.js +0 -40
- package/dist/http/context.d.ts +0 -129
- package/dist/http/context.d.ts.map +0 -1
- package/dist/http/context.js +0 -115
- package/dist/http/index.d.ts +0 -16
- package/dist/http/index.d.ts.map +0 -1
- package/dist/http/middleware/cors.d.ts +0 -43
- package/dist/http/middleware/cors.d.ts.map +0 -1
- package/dist/http/middleware/cors.js +0 -31
- package/dist/http/middleware/csrf.d.ts +0 -47
- package/dist/http/middleware/csrf.d.ts.map +0 -1
- package/dist/http/middleware/csrf.js +0 -25
- package/dist/http/middleware/error-handler.d.ts +0 -6
- package/dist/http/middleware/error-handler.d.ts.map +0 -1
- package/dist/http/middleware/error-handler.js +0 -37
- package/dist/http/middleware/helmet.d.ts +0 -36
- package/dist/http/middleware/helmet.d.ts.map +0 -1
- package/dist/http/middleware/helmet.js +0 -20
- package/dist/http/middleware/rate-limit.d.ts +0 -51
- package/dist/http/middleware/rate-limit.d.ts.map +0 -1
- package/dist/http/middleware/rate-limit.js +0 -46
- package/dist/http/middleware/request-id.d.ts +0 -5
- package/dist/http/middleware/request-id.d.ts.map +0 -1
- package/dist/http/middleware/request-id.js +0 -12
- package/dist/http/middleware/request-logger.d.ts +0 -27
- package/dist/http/middleware/request-logger.d.ts.map +0 -1
- package/dist/http/middleware/request-logger.js +0 -16
- package/dist/http/middleware/session.d.ts +0 -62
- package/dist/http/middleware/session.d.ts.map +0 -1
- package/dist/http/middleware/session.js +0 -76
- package/dist/http/middleware/spa.d.ts +0 -93
- package/dist/http/middleware/spa.d.ts.map +0 -1
- package/dist/http/middleware/spa.js +0 -52
- package/dist/http/middleware/upload.d.ts.map +0 -1
- package/dist/http/middleware/upload.js +0 -119
- package/dist/http/middleware/validate.d.ts +0 -13
- package/dist/http/middleware/validate.d.ts.map +0 -1
- package/dist/http/middleware/validate.js +0 -45
- package/dist/http/middleware/views.d.ts +0 -56
- package/dist/http/middleware/views.d.ts.map +0 -1
- package/dist/http/middleware/views.js +0 -18
- package/dist/http/query/index.d.ts +0 -4
- package/dist/http/query/index.d.ts.map +0 -1
- package/dist/http/query/index.js +0 -10
- package/dist/http/query/parse-query.d.ts +0 -44
- package/dist/http/query/parse-query.d.ts.map +0 -1
- package/dist/http/query/types.d.ts +0 -100
- package/dist/http/query/types.d.ts.map +0 -1
- package/dist/http/router-builder.d.ts.map +0 -1
- package/dist/http/router-builder.js +0 -37
- package/dist/index.d.ts +0 -25
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -103
- package/dist/query-Bym31XRp.js +0 -88
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"application-DNHj-_UL.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/**\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.info('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 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 ?? '100kb' }))\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 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.info('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.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)\n }\n\n log.info(` 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.info('Attached to Vite dev server (adapters use Vite httpServer)')\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.info('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.info('Shutdown already in progress, skipping duplicate call')\n return\n }\n this._shutdownInitiated = true\n this._draining = true\n\n log.info('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.info(`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.info('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,M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S,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"}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { t as __require } from "./chunk-C5Qp-JxE.mjs";
|
|
12
|
+
import { createLogger } from "./core/logger.mjs";
|
|
13
|
+
import { Container } from "./core/container.mjs";
|
|
14
|
+
import "./core-BL_H8fEZ.mjs";
|
|
15
|
+
import { reactive, ref } from "./core/reactivity.mjs";
|
|
16
|
+
import { t as Application } from "./application-DNHj-_UL.mjs";
|
|
17
|
+
import cluster from "node:cluster";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
//#region src/http/cluster.ts
|
|
20
|
+
const log$1 = createLogger("Cluster");
|
|
21
|
+
/** Returns true if the current process is the cluster primary */
|
|
22
|
+
function isClusterPrimary() {
|
|
23
|
+
return cluster.isPrimary;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fork worker processes and manage the cluster lifecycle.
|
|
27
|
+
*
|
|
28
|
+
* The primary process forks `workers` child processes. Each worker
|
|
29
|
+
* shares the same port via Node's built-in `cluster` module (OS
|
|
30
|
+
* round-robin load balancing).
|
|
31
|
+
*
|
|
32
|
+
* Features:
|
|
33
|
+
* - Graceful shutdown with timeout fallback to forceful kill
|
|
34
|
+
* - Auto-restart dead workers (respects voluntary disconnects)
|
|
35
|
+
* - Startup timeout detection (stuck workers)
|
|
36
|
+
* - Crash loop prevention (backoff on rapid failures)
|
|
37
|
+
* - Comprehensive lifecycle logging
|
|
38
|
+
*/
|
|
39
|
+
function setupClusterPrimary(opts) {
|
|
40
|
+
const numWorkers = opts.workers ?? os.cpus().length;
|
|
41
|
+
const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5e3;
|
|
42
|
+
const restartDelay = opts.restartDelay ?? 1e3;
|
|
43
|
+
const maxFailures = opts.maxFailures ?? 5;
|
|
44
|
+
const restartWindow = opts.restartWindow ?? 3e4;
|
|
45
|
+
const startupTimeouts = /* @__PURE__ */ new Map();
|
|
46
|
+
const state = reactive({
|
|
47
|
+
failureTimestamps: [],
|
|
48
|
+
shuttingDown: false
|
|
49
|
+
});
|
|
50
|
+
const activeWorkers = ref(0);
|
|
51
|
+
log$1.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`);
|
|
52
|
+
for (let i = 0; i < numWorkers; i++) cluster.fork();
|
|
53
|
+
cluster.on("fork", (worker) => {
|
|
54
|
+
const timeout = setTimeout(() => {
|
|
55
|
+
log$1.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`);
|
|
56
|
+
worker.kill();
|
|
57
|
+
}, 1e4);
|
|
58
|
+
startupTimeouts.set(worker.id, timeout);
|
|
59
|
+
activeWorkers.value++;
|
|
60
|
+
log$1.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`);
|
|
61
|
+
});
|
|
62
|
+
cluster.on("listening", (worker, address) => {
|
|
63
|
+
const timeout = startupTimeouts.get(worker.id);
|
|
64
|
+
if (timeout) {
|
|
65
|
+
clearTimeout(timeout);
|
|
66
|
+
startupTimeouts.delete(worker.id);
|
|
67
|
+
}
|
|
68
|
+
log$1.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`);
|
|
69
|
+
});
|
|
70
|
+
cluster.on("online", (worker) => {
|
|
71
|
+
log$1.debug(`Worker ${worker.process.pid} online (id=${worker.id})`);
|
|
72
|
+
});
|
|
73
|
+
cluster.on("exit", (worker, code, signal) => {
|
|
74
|
+
const timeout = startupTimeouts.get(worker.id);
|
|
75
|
+
if (timeout) {
|
|
76
|
+
clearTimeout(timeout);
|
|
77
|
+
startupTimeouts.delete(worker.id);
|
|
78
|
+
}
|
|
79
|
+
activeWorkers.value--;
|
|
80
|
+
if (worker.exitedAfterDisconnect) {
|
|
81
|
+
log$1.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
while (state.failureTimestamps.length > 0 && now - state.failureTimestamps[0] >= restartWindow) state.failureTimestamps.shift();
|
|
86
|
+
state.failureTimestamps.push(now);
|
|
87
|
+
if (state.failureTimestamps.length > maxFailures) {
|
|
88
|
+
log$1.error(`${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`);
|
|
89
|
+
if (activeWorkers.value === 0) {
|
|
90
|
+
log$1.error("All workers have crashed, exiting primary");
|
|
91
|
+
process.exit(1);
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
log$1.warn(`Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`);
|
|
96
|
+
setTimeout(() => {
|
|
97
|
+
if (activeWorkers.value < numWorkers) cluster.fork();
|
|
98
|
+
}, restartDelay);
|
|
99
|
+
});
|
|
100
|
+
cluster.on("disconnect", (worker) => {
|
|
101
|
+
log$1.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`);
|
|
102
|
+
});
|
|
103
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => {
|
|
104
|
+
if (state.shuttingDown) return;
|
|
105
|
+
state.shuttingDown = true;
|
|
106
|
+
log$1.info(`Primary received ${signal}, disconnecting workers...`);
|
|
107
|
+
cluster.disconnect(() => {
|
|
108
|
+
log$1.info("All workers disconnected, exiting primary");
|
|
109
|
+
process.exit(0);
|
|
110
|
+
});
|
|
111
|
+
setTimeout(() => {
|
|
112
|
+
log$1.warn("Graceful shutdown timed out, forcing exit");
|
|
113
|
+
process.exit(1);
|
|
114
|
+
}, gracefulTimeout).unref();
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/http/bootstrap.ts
|
|
119
|
+
/** Try to reload env from .env file if config package is available */
|
|
120
|
+
function tryReloadEnv() {
|
|
121
|
+
try {
|
|
122
|
+
__require("@forinda/kickjs-config").reloadEnv?.();
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
125
|
+
const log = createLogger("Process");
|
|
126
|
+
/**
|
|
127
|
+
* Bootstrap a KickJS application with zero boilerplate.
|
|
128
|
+
*
|
|
129
|
+
* ## Dev Mode (with @forinda/kickjs-vite)
|
|
130
|
+
*
|
|
131
|
+
* When the Vite plugin is active (`globalThis.__kickjs_httpServer` is set),
|
|
132
|
+
* `bootstrap()` sets up the Express app and adapters but does NOT start
|
|
133
|
+
* the HTTP server — Vite owns the port. The returned `app` object has a
|
|
134
|
+
* `.handle(req, res, next)` method that the Vite dev-server plugin calls
|
|
135
|
+
* on each request via `ssrLoadModule()`.
|
|
136
|
+
*
|
|
137
|
+
* ## Production Mode
|
|
138
|
+
*
|
|
139
|
+
* Without the Vite plugin, `bootstrap()` creates its own `http.Server`,
|
|
140
|
+
* binds to the port, and starts listening — same behavior as before.
|
|
141
|
+
*
|
|
142
|
+
* ## HMR
|
|
143
|
+
*
|
|
144
|
+
* On subsequent calls (module re-evaluation), `bootstrap()` rebuilds the
|
|
145
|
+
* Express app and swaps the request handler without restarting the server.
|
|
146
|
+
*
|
|
147
|
+
* @returns The Application instance. In Vite dev mode, the Express handler
|
|
148
|
+
* is accessible at `app.handle` for the dev-server plugin to use.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```ts
|
|
152
|
+
* // src/index.ts
|
|
153
|
+
* import 'reflect-metadata'
|
|
154
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
155
|
+
* import { modules } from './modules'
|
|
156
|
+
*
|
|
157
|
+
* // Export for Vite plugin (dev) — also works standalone (prod)
|
|
158
|
+
* export const app = await bootstrap({ modules })
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
async function bootstrap(options) {
|
|
162
|
+
if (options.cluster && cluster.isPrimary) {
|
|
163
|
+
setupClusterPrimary(typeof options.cluster === "object" ? options.cluster : {});
|
|
164
|
+
return new Application(options);
|
|
165
|
+
}
|
|
166
|
+
const g = globalThis;
|
|
167
|
+
if (!g.__kickBootstrapped) {
|
|
168
|
+
process.on("uncaughtException", (err) => {
|
|
169
|
+
log.error(err, "Uncaught exception");
|
|
170
|
+
});
|
|
171
|
+
process.on("unhandledRejection", (reason) => {
|
|
172
|
+
log.error(reason, "Unhandled rejection");
|
|
173
|
+
});
|
|
174
|
+
if (!g.__kickjs_httpServer) for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, async () => {
|
|
175
|
+
log.info(`Received ${signal}, shutting down...`);
|
|
176
|
+
if (g.__app) await g.__app.shutdown();
|
|
177
|
+
process.exit(0);
|
|
178
|
+
});
|
|
179
|
+
g.__kickBootstrapped = true;
|
|
180
|
+
}
|
|
181
|
+
if (g.__app) {
|
|
182
|
+
log.info("HMR: Rebuilding application...");
|
|
183
|
+
tryReloadEnv();
|
|
184
|
+
Container.reset();
|
|
185
|
+
const freshApp = new Application(options);
|
|
186
|
+
g.__app = freshApp;
|
|
187
|
+
g.__kickjs_container = freshApp.getContainer();
|
|
188
|
+
await freshApp.start();
|
|
189
|
+
log.info("HMR: Application rebuilt with fresh modules");
|
|
190
|
+
return freshApp;
|
|
191
|
+
}
|
|
192
|
+
const app = new Application(options);
|
|
193
|
+
g.__app = app;
|
|
194
|
+
g.__kickjs_container = app.getContainer();
|
|
195
|
+
if (process.env.KICK_TINKER) {
|
|
196
|
+
await app.registerOnly();
|
|
197
|
+
return app;
|
|
198
|
+
}
|
|
199
|
+
await app.start();
|
|
200
|
+
return app;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
export { isClusterPrimary as n, bootstrap as t };
|
|
204
|
+
|
|
205
|
+
//# sourceMappingURL=bootstrap-DLEZaJ3b.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bootstrap-DLEZaJ3b.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 { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\n\n/** Try to reload env from .env file if config package is available */\nfunction tryReloadEnv(): void {\n try {\n const config = require('@forinda/kickjs-config')\n config.reloadEnv?.()\n } catch {\n // Config package not installed — skip\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application with zero boilerplate.\n *\n * ## Dev Mode (with @forinda/kickjs-vite)\n *\n * When the Vite plugin is active (`globalThis.__kickjs_httpServer` is set),\n * `bootstrap()` sets up the Express app and adapters but does NOT start\n * the HTTP server — Vite owns the port. The returned `app` object has a\n * `.handle(req, res, next)` method that the Vite dev-server plugin calls\n * on each request via `ssrLoadModule()`.\n *\n * ## Production Mode\n *\n * Without the Vite plugin, `bootstrap()` creates its own `http.Server`,\n * binds to the port, and starts listening — same behavior as before.\n *\n * ## HMR\n *\n * On subsequent calls (module re-evaluation), `bootstrap()` rebuilds the\n * Express app and swaps the request handler without restarting the server.\n *\n * @returns The Application instance. In Vite dev mode, the Express handler\n * is accessible at `app.handle` for the dev-server plugin to use.\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 for Vite plugin (dev) — also works standalone (prod)\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 if (options.cluster && cluster.isPrimary) {\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 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.info('HMR: Rebuilding application...')\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.info('HMR: Application rebuilt with fresh modules')\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,KAAK,WAAW,GAAG,MAAM,CAAC;CAC7C,MAAM,kBAAkB,KAAK,2BAA2B;CACxD,MAAM,eAAe,KAAK,gBAAgB;CAC1C,MAAM,cAAc,KAAK,eAAe;CACxC,MAAM,gBAAgB,KAAK,iBAAiB;CAE5C,MAAM,kCAAkB,IAAI,KAA6B;CACzD,MAAM,QAAQ,SAAS;EACrB,mBAAmB,EAAE;EACrB,cAAc;EACf,CAAC;CACF,MAAM,gBAAgB,IAAI,EAAE;AAE5B,OAAI,KAAK,WAAW,QAAQ,IAAI,YAAY,WAAW,YAAY;AAGnE,MAAK,IAAI,IAAI,GAAG,IAAI,YAAY,IAC9B,SAAQ,MAAM;AAIhB,SAAQ,GAAG,SAAS,WAAW;EAC7B,MAAM,UAAU,iBAAiB;AAC/B,SAAI,MAAM,UAAU,OAAO,QAAQ,IAAI,yCAAyC;AAChF,UAAO,MAAM;KACZ,IAAM;AAET,kBAAgB,IAAI,OAAO,IAAI,QAAQ;AACvC,gBAAc;AACd,QAAI,MAAM,UAAU,OAAO,QAAQ,IAAI,cAAc,OAAO,GAAG,GAAG;GAClE;AAGF,SAAQ,GAAG,cAAc,QAAQ,YAAY;EAC3C,MAAM,UAAU,gBAAgB,IAAI,OAAO,GAAG;AAC9C,MAAI,SAAS;AACX,gBAAa,QAAQ;AACrB,mBAAgB,OAAO,OAAO,GAAG;;AAEnC,QAAI,KAAK,UAAU,OAAO,QAAQ,IAAI,gBAAgB,QAAQ,QAAQ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qB,IAAI,cAAc;AAEzC,KAAI,QAAQ,IAAI,aAAa;AAC3B,QAAM,IAAI,cAAc;AACxB,SAAO;;AAGT,OAAM,IAAI,OAAO;AAEjB,QAAO"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
|
|
2
|
+
//#region src/core/cache.d.ts
|
|
2
3
|
declare const CACHEABLE_META: unique symbol;
|
|
3
4
|
/**
|
|
4
5
|
* Abstract cache backend. Implement this interface to use Redis, Memcached,
|
|
@@ -24,30 +25,30 @@ declare const CACHEABLE_META: unique symbol;
|
|
|
24
25
|
* }
|
|
25
26
|
* ```
|
|
26
27
|
*/
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
28
|
+
interface CacheProvider {
|
|
29
|
+
/** Retrieve a cached value. Return null if not found or expired. */
|
|
30
|
+
get(key: string): Promise<any | null>;
|
|
31
|
+
/** Store a value with a TTL in milliseconds. */
|
|
32
|
+
set(key: string, value: any, ttlMs: number): Promise<void>;
|
|
33
|
+
/** Delete a specific cache key. */
|
|
34
|
+
del(key: string): Promise<void>;
|
|
35
|
+
/** Delete all keys matching a prefix. Used by @CacheEvict. */
|
|
36
|
+
delByPrefix?(prefix: string): Promise<void>;
|
|
37
|
+
/** Optional cleanup on shutdown. */
|
|
38
|
+
shutdown?(): Promise<void>;
|
|
38
39
|
}
|
|
39
40
|
/**
|
|
40
41
|
* Default in-memory cache provider using a Map.
|
|
41
42
|
* Suitable for development and single-instance deployments.
|
|
42
43
|
* For multi-instance or production, use a Redis-backed provider.
|
|
43
44
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
45
|
+
declare class MemoryCacheProvider implements CacheProvider {
|
|
46
|
+
private store;
|
|
47
|
+
get(key: string): Promise<any | null>;
|
|
48
|
+
set(key: string, value: any, ttlMs: number): Promise<void>;
|
|
49
|
+
del(key: string): Promise<void>;
|
|
50
|
+
delByPrefix(prefix: string): Promise<void>;
|
|
51
|
+
shutdown(): Promise<void>;
|
|
51
52
|
}
|
|
52
53
|
/**
|
|
53
54
|
* Set the global cache provider used by @Cacheable and @CacheEvict.
|
|
@@ -61,14 +62,14 @@ export declare class MemoryCacheProvider implements CacheProvider {
|
|
|
61
62
|
* setCacheProvider(new RedisCacheProvider(redisClient))
|
|
62
63
|
* ```
|
|
63
64
|
*/
|
|
64
|
-
|
|
65
|
+
declare function setCacheProvider(provider: CacheProvider): void;
|
|
65
66
|
/** Get the current cache provider */
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
67
|
+
declare function getCacheProvider(): CacheProvider;
|
|
68
|
+
interface CacheOptions {
|
|
69
|
+
/** Time-to-live in seconds (default: 60) */
|
|
70
|
+
ttl?: number;
|
|
71
|
+
/** Cache key prefix (default: ClassName.methodName) */
|
|
72
|
+
key?: string;
|
|
72
73
|
}
|
|
73
74
|
/**
|
|
74
75
|
* Cache the return value of a method for the specified TTL.
|
|
@@ -79,8 +80,8 @@ export interface CacheOptions {
|
|
|
79
80
|
* @param ttl - Time-to-live in seconds (default: 60)
|
|
80
81
|
* @param options.key - Custom cache key prefix
|
|
81
82
|
*/
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
declare function Cacheable(ttl?: number, options?: {
|
|
84
|
+
key?: string;
|
|
84
85
|
}): MethodDecorator;
|
|
85
86
|
/**
|
|
86
87
|
* Evict cached values matching a key prefix after the method executes.
|
|
@@ -88,6 +89,7 @@ export declare function Cacheable(ttl?: number, options?: {
|
|
|
88
89
|
*
|
|
89
90
|
* @param key - Cache key prefix to evict (matches the @Cacheable key)
|
|
90
91
|
*/
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
declare function CacheEvict(key: string): MethodDecorator;
|
|
93
|
+
//#endregion
|
|
94
|
+
export { Cacheable as a, setCacheProvider as c, CacheProvider as i, CacheEvict as n, MemoryCacheProvider as o, CacheOptions as r, getCacheProvider as s, CACHEABLE_META as t };
|
|
95
|
+
//# sourceMappingURL=cache-DJeMaGqb.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-DJeMaGqb.d.mts","names":[],"sources":["../src/core/cache.ts"],"mappings":";;cAEM,cAAA;;AAFmB;;;;;AA8BzB;;;;;;;;;;;;;;;;;;UAAiB,aAAA;EAMX;EAJJ,GAAA,CAAI,GAAA,WAAc,OAAA;EAMlB;EAJA,GAAA,CAAI,GAAA,UAAa,KAAA,OAAY,KAAA,WAAgB,OAAA;EAIf;EAF9B,GAAA,CAAI,GAAA,WAAc,OAAA;EAIL;EAFb,WAAA,EAAa,MAAA,WAAiB,OAAA;EAEV;EAApB,QAAA,KAAa,OAAA;AAAA;;;;;;cAUF,mBAAA,YAA+B,aAAA;EAAA,QAClC,KAAA;EAEF,GAAA,CAAI,GAAA,WAAc,OAAA;EAUlB,GAAA,CAAI,GAAA,UAAa,KAAA,OAAY,KAAA,WAAgB,OAAA;EAI7C,GAAA,CAAI,GAAA,WAAc,OAAA;EAIlB,WAAA,CAAY,MAAA,WAAiB,OAAA;EAQ7B,QAAA,CAAA,GAAY,OAAA;AAAA;;;;;;;;;;;;;iBAqBJ,gBAAA,CAAiB,QAAA,EAAU,aAAA;;iBAK3B,gBAAA,CAAA,GAAoB,aAAA;AAAA,UAMnB,YAAA;EAXD;EAad,GAAA;;EAEA,GAAA;AAAA;AAVF;;;;;AAMA;;;;AANA,iBAwBgB,SAAA,CAAU,GAAA,WAAc,OAAA;EAAY,GAAA;AAAA,IAAiB,eAAA;;;;;;;iBAgCrD,UAAA,CAAW,GAAA,WAAc,eAAA"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
//#region \0rolldown/runtime.js
|
|
13
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
14
|
+
//#endregion
|
|
15
|
+
export { __require as t };
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
|
|
2
|
+
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-D-48zotH.mjs";
|
|
3
|
+
//#region src/core/container.d.ts
|
|
4
|
+
/** Format a token for display in error messages */
|
|
5
|
+
declare function tokenName(token: any): string;
|
|
6
|
+
/** A single container change event */
|
|
7
|
+
interface ContainerChangeEvent {
|
|
8
|
+
token: string;
|
|
9
|
+
event: 'registered' | 'resolved' | 'invalidated';
|
|
10
|
+
kind?: ClassKind;
|
|
11
|
+
timestamp: number;
|
|
12
|
+
}
|
|
13
|
+
/** Listener that receives batched change events */
|
|
14
|
+
type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void;
|
|
15
|
+
/**
|
|
16
|
+
* Inversion-of-Control (IoC) container that manages dependency registration,
|
|
17
|
+
* resolution, and lifecycle. Implements the Singleton pattern so all parts of
|
|
18
|
+
* the application share a single container instance.
|
|
19
|
+
*
|
|
20
|
+
* Supports constructor injection, property injection (@Autowired),
|
|
21
|
+
* factory registrations, and lifecycle hooks (@PostConstruct).
|
|
22
|
+
*
|
|
23
|
+
* Persistent state (DB connections, Redis, etc.) is stored on globalThis so
|
|
24
|
+
* it survives both Container.reset() and Vite module re-evaluation.
|
|
25
|
+
*/
|
|
26
|
+
declare class Container {
|
|
27
|
+
private static instance;
|
|
28
|
+
private registrations;
|
|
29
|
+
private resolving;
|
|
30
|
+
private changeListeners;
|
|
31
|
+
private pendingChanges;
|
|
32
|
+
private notifyTimer;
|
|
33
|
+
private static readonly DEBOUNCE_MS;
|
|
34
|
+
/** Callback set by the decorators module to flush pending registrations */
|
|
35
|
+
static _onReady: ((container: Container) => void) | null;
|
|
36
|
+
/** Callback invoked on reset so decorators can update their container reference */
|
|
37
|
+
static _onReset: ((container: Container) => void) | null;
|
|
38
|
+
/**
|
|
39
|
+
* Environment resolver for @Value decorator. Set by @forinda/kickjs-config
|
|
40
|
+
* to return Zod-validated, type-coerced env values instead of raw process.env strings.
|
|
41
|
+
*/
|
|
42
|
+
static _envResolver: ((key: string) => any) | null;
|
|
43
|
+
/**
|
|
44
|
+
* Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http
|
|
45
|
+
* to return the current request's AsyncLocalStorage store.
|
|
46
|
+
* Returns { instances: Map, values: Map } or null if outside a request.
|
|
47
|
+
*/
|
|
48
|
+
static _requestStoreProvider: (() => {
|
|
49
|
+
instances: Map<any, any>;
|
|
50
|
+
values: Map<any, any>;
|
|
51
|
+
} | null) | null;
|
|
52
|
+
static getInstance(): Container;
|
|
53
|
+
/**
|
|
54
|
+
* Resets the container by replacing the singleton with a fresh instance.
|
|
55
|
+
* Persistent registrations (DB, Redis, etc.) are replayed from globalThis
|
|
56
|
+
* so they survive both reset() and Vite module re-evaluation.
|
|
57
|
+
*/
|
|
58
|
+
static reset(): void;
|
|
59
|
+
/**
|
|
60
|
+
* Create an isolated container instance (not the global singleton).
|
|
61
|
+
* Useful for concurrent tests that must not share DI state.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```ts
|
|
65
|
+
* const container = Container.create()
|
|
66
|
+
* container.register(UserService, UserService)
|
|
67
|
+
* const svc = container.resolve(UserService)
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
static create(): Container;
|
|
71
|
+
/** Register a class constructor under the given token */
|
|
72
|
+
register(token: any, target: Constructor, scope?: Scope): void;
|
|
73
|
+
/** Register a factory function under the given token */
|
|
74
|
+
registerFactory(token: any, factory: () => any, scope?: Scope): void;
|
|
75
|
+
/** Register a pre-constructed singleton instance */
|
|
76
|
+
registerInstance(token: any, instance: any): void;
|
|
77
|
+
/** Check if a binding exists for the given token */
|
|
78
|
+
has(token: any): boolean;
|
|
79
|
+
/** Return a snapshot of all registered tokens with their scope and instantiation status */
|
|
80
|
+
getRegistrations(): Array<{
|
|
81
|
+
token: string;
|
|
82
|
+
scope: string;
|
|
83
|
+
kind: ClassKind;
|
|
84
|
+
instantiated: boolean;
|
|
85
|
+
resolveCount: number;
|
|
86
|
+
lastResolvedAt?: number;
|
|
87
|
+
firstResolvedAt?: number;
|
|
88
|
+
resolveDurationMs?: number;
|
|
89
|
+
postConstructStatus: PostConstructStatus;
|
|
90
|
+
dependencies: string[];
|
|
91
|
+
}>;
|
|
92
|
+
/** Resolve a dependency by its token */
|
|
93
|
+
resolve<T = any>(token: any): T;
|
|
94
|
+
/** Lifecycle hook called during Application.setup() after module registration */
|
|
95
|
+
bootstrap(): void;
|
|
96
|
+
/**
|
|
97
|
+
* Subscribe to container changes. Returns an unsubscribe function.
|
|
98
|
+
*
|
|
99
|
+
* Changes are batched (50ms debounce) so bulk operations like
|
|
100
|
+
* `kick g module` creating 10+ files emit ONE batch, not 10 events.
|
|
101
|
+
*
|
|
102
|
+
* Any adapter can subscribe:
|
|
103
|
+
* - SwaggerAdapter: re-build spec when controllers change
|
|
104
|
+
* - DevToolsAdapter: push SSE events to dashboard
|
|
105
|
+
* - WsAdapter: re-discover namespaces when controllers change
|
|
106
|
+
* - OtelAdapter: emit tracing spans for DI resolution
|
|
107
|
+
* - Custom user adapters
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* const unsub = container.onChange((changes) => {
|
|
112
|
+
* for (const c of changes) {
|
|
113
|
+
* console.log(`${c.event}: ${c.token} (${c.kind})`)
|
|
114
|
+
* }
|
|
115
|
+
* })
|
|
116
|
+
* // later:
|
|
117
|
+
* unsub()
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
onChange(callback: ContainerChangeListener): () => void;
|
|
121
|
+
/**
|
|
122
|
+
* Invalidate a specific registration. Clears the cached instance so the
|
|
123
|
+
* next resolve() creates a fresh one. Also invalidates dependents
|
|
124
|
+
* (anything that injected this token) by walking the dependency graph.
|
|
125
|
+
*
|
|
126
|
+
* Called by the Vite HMR plugin when a module file changes.
|
|
127
|
+
* Skips persistent registrations (DB connections, etc.).
|
|
128
|
+
*/
|
|
129
|
+
invalidate(token: any): void;
|
|
130
|
+
/** Batch-emit a change event (debounced, flushed after 50ms of quiet) */
|
|
131
|
+
private emit;
|
|
132
|
+
/** Flush pending change events immediately (useful in tests) */
|
|
133
|
+
flushChanges(): void;
|
|
134
|
+
private createInstance;
|
|
135
|
+
/** Extract dependency token names from constructor metadata */
|
|
136
|
+
private extractDependencies;
|
|
137
|
+
private injectProperties;
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
export { tokenName as i, ContainerChangeEvent as n, ContainerChangeListener as r, Container as t };
|
|
141
|
+
//# sourceMappingURL=container-nBSIhyqV.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"container-nBSIhyqV.d.mts","names":[],"sources":["../src/core/container.ts"],"mappings":";;;;iBAiDgB,SAAA,CAAU,KAAA;AAA1B;AAAA,UAoBiB,oBAAA;EACf,KAAA;EACA,KAAA;EACA,IAAA,GAAO,SAAA;EACP,SAAA;AAAA;;KAIU,uBAAA,IAA2B,OAAA,EAAS,oBAAA;;;;;;;;AAAhD;;;;cA+Ba,SAAA;EAAA,eACI,QAAA;EAAA,QACP,aAAA;EAAA,QACA,SAAA;EAAA,QAGA,eAAA;EAAA,QACA,cAAA;EAAA,QACA,WAAA;EAAA,wBACgB,WAAA;EAoBF;EAAA,OAjBf,QAAA,IAAY,SAAA,EAAW,SAAA;EA4FD;EAAA,OA1FtB,QAAA,IAAY,SAAA,EAAW,SAAA;EAwGyB;;;;EAAA,OAnGhD,YAAA,IAAgB,GAAA;EAyUJ;;;;;EAAA,OAnUZ,qBAAA;IACM,SAAA,EAAW,GAAA;IAAe,MAAA,EAAQ,GAAA;EAAA;EAAA,OAGxC,WAAA,CAAA,GAAe,SAAA;EAjBf;;;;;EAAA,OAkCA,KAAA,CAAA;EA3BA;;;;;;;;;;;EAAA,OAgFA,MAAA,CAAA,GAAU,SAAA;EAKjB;EAAA,QAAA,CAAS,KAAA,OAAY,MAAA,EAAQ,WAAA,EAAa,KAAA,GAAO,KAAA;EAApB;EAc7B,eAAA,CAAgB,KAAA,OAAY,OAAA,aAAoB,KAAA,GAAO,KAAA;EAdN;EAqDjD,gBAAA,CAAiB,KAAA,OAAY,QAAA;EAvC7B;EAoEA,GAAA,CAAI,KAAA;EApEwB;EAyE5B,gBAAA,CAAA,GAAoB,KAAA;IAClB,KAAA;IACA,KAAA;IACA,IAAA,EAAM,SAAA;IACN,YAAA;IACA,YAAA;IACA,cAAA;IACA,eAAA;IACA,iBAAA;IACA,mBAAA,EAAqB,mBAAA;IACrB,YAAA;EAAA;EAPM;EA8BR,OAAA,SAAA,CAAiB,KAAA,QAAa,CAAA;EA5B5B;EAyHF,SAAA,CAAA;EAvHE;;;;;;;;;;;;;;;;;;;;;;;;EAsJF,QAAA,CAAS,QAAA,EAAU,uBAAA;;;;;;;;;EAanB,UAAA,CAAW,KAAA;;UAyBH,IAAA;;EAkBR,YAAA,CAAA;EAAA,QAgBQ,cAAA;;UA8DA,mBAAA;EAAA,QASA,gBAAA;AAAA"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
|
|
2
|
+
import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider, t as CACHEABLE_META } from "../cache-DJeMaGqb.mjs";
|
|
3
|
+
export { CACHEABLE_META, CacheEvict, CacheOptions, CacheProvider, Cacheable, MemoryCacheProvider, getCacheProvider, setCacheProvider };
|