@forinda/kickjs 3.2.0 → 4.0.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/README.md +13 -212
- package/dist/{adapter-DLEHb0K6.d.mts → adapter-BNw2pGbg.d.mts} +117 -7
- package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
- package/dist/{app-module-ERR9jhow.d.mts → app-module-CO0ksPCm.d.mts} +3 -3
- package/dist/{app-module-ERR9jhow.d.mts.map → app-module-CO0ksPCm.d.mts.map} +1 -1
- package/dist/{application-x8CXLOlv.mjs → application-Ce4DQN6m.mjs} +28 -9
- package/dist/application-Ce4DQN6m.mjs.map +1 -0
- package/dist/application-Czwm7Gty.d.mts +302 -0
- package/dist/application-Czwm7Gty.d.mts.map +1 -0
- package/dist/{bootstrap-CYnxozL_.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
- package/dist/{bootstrap-CYnxozL_.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
- package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
- package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
- package/dist/{cache-V91BNTIM.d.mts → cache-BStrqXSZ.d.mts} +2 -2
- package/dist/{cache-V91BNTIM.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +3 -3
- package/dist/{config-aWxKLk4A.mjs → config-wZ_TgBfs.mjs} +4 -4
- package/dist/{config-aWxKLk4A.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
- package/dist/{container-fIS1uLx-.d.mts → container-CnWDsxi-.d.mts} +9 -7
- package/dist/container-CnWDsxi-.d.mts.map +1 -0
- package/dist/{container-Dnk43k54.mjs → container-DYYSu58w.mjs} +313 -9
- package/dist/container-DYYSu58w.mjs.map +1 -0
- package/dist/{context-OktlOQBQ.mjs → context-BAGzqT7-.mjs} +33 -41
- package/dist/context-BAGzqT7-.mjs.map +1 -0
- package/dist/context-Ymvv-85x.d.mts +260 -0
- package/dist/context-Ymvv-85x.d.mts.map +1 -0
- package/dist/{context-decorator-GA8-hDLe.d.mts → context-decorator-B5v3VQCN.d.mts} +4 -4
- package/dist/{context-decorator-GA8-hDLe.d.mts.map → context-decorator-B5v3VQCN.d.mts.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +2 -2
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.d.mts +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +48 -16
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +35 -18
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +2 -2
- package/dist/core/logger.mjs +2 -4
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.d.mts +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-DANnH5-e.mjs → core-DBcoqPHM.mjs} +282 -8
- package/dist/core-DBcoqPHM.mjs.map +1 -0
- package/dist/cors-BfgqfLPd.d.mts +48 -0
- package/dist/cors-BfgqfLPd.d.mts.map +1 -0
- package/dist/{cron-CfsPdi7R.d.mts → cron-7zqvsmMI.d.mts} +1 -1
- package/dist/{cron-CfsPdi7R.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
- package/dist/csrf-DiK9zept.d.mts +52 -0
- package/dist/csrf-DiK9zept.d.mts.map +1 -0
- package/dist/{decorators-H42oPg0m.d.mts → decorators-BMvaLliz.d.mts} +147 -12
- package/dist/decorators-BMvaLliz.d.mts.map +1 -0
- package/dist/{env-Cs8Wt8A_.mjs → env-CdH5-dM_.mjs} +3 -4
- package/dist/{env-Cs8Wt8A_.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
- package/dist/error-handler-Xud_3Lah.d.mts +20 -0
- package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
- package/dist/{errors-D_CWI7Bl.d.mts → errors-uaHCeXRz.d.mts} +1 -1
- package/dist/{errors-D_CWI7Bl.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
- package/dist/{execution-context-Dl2CKqSo.d.mts → execution-context-DKnt61pY.d.mts} +1 -1
- package/dist/{execution-context-Dl2CKqSo.d.mts.map → execution-context-DKnt61pY.d.mts.map} +1 -1
- package/dist/helmet-CaMbjzBG.d.mts +41 -0
- package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
- package/dist/http/application.d.mts +2 -293
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +2 -27
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +3 -251
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.d.mts +2 -47
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -51
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +2 -19
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +2 -40
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.d.mts +2 -55
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +2 -9
- package/dist/http/middleware/request-id.mjs +12 -3
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +2 -31
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +2 -69
- package/dist/http/middleware/session.mjs +1 -1
- package/dist/http/middleware/spa.d.mts +2 -100
- package/dist/http/middleware/spa.mjs +5 -5
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -78
- package/dist/http/middleware/upload.mjs +1 -1
- package/dist/http/middleware/validate.d.mts +2 -22
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/views.d.mts +2 -61
- package/dist/http/middleware/views.mjs +16 -15
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +2 -32
- package/dist/http/router-builder.mjs +10 -14
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/{index-RNK41JPE.d.mts → index-B9cyOQAe.d.mts} +1 -1
- package/dist/{index-RNK41JPE.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
- package/dist/{index-Cf-MGrqT.d.mts → index-D-qhXg9M.d.mts} +3 -3
- package/dist/{index-Cf-MGrqT.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
- package/dist/{index-BQM9pJrV.d.mts → index-DQyWtyp0.d.mts} +241 -5
- package/dist/index-DQyWtyp0.d.mts.map +1 -0
- package/dist/index.d.mts +34 -152
- package/dist/index.mjs +14 -14
- package/dist/interfaces-B50n7dwl.d.mts +71 -0
- package/dist/{interfaces-CwcdqfNq.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
- package/dist/{logger-GK8yT0BD.d.mts → logger-CLVRZf2N.d.mts} +2 -4
- package/dist/{logger-GK8yT0BD.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
- package/dist/{metadata-BFuoSEX6.mjs → metadata-VQM9wChy.mjs} +2 -2
- package/dist/{metadata-BFuoSEX6.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
- package/dist/{path-Bj3vZMUY.d.mts → path-Diviu6hv.d.mts} +1 -1
- package/dist/path-Diviu6hv.d.mts.map +1 -0
- package/dist/{plugin-3rKA0Loy.d.mts → plugin-WdrDgNzk.d.mts} +45 -7
- package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
- package/dist/{query-BcYEjYyX.mjs → query-DJMxdx5r.mjs} +2 -2
- package/dist/{query-BcYEjYyX.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
- package/dist/rate-limit-DUwoICtI.d.mts +56 -0
- package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
- package/dist/{reactivity-CczHu3R-.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
- package/dist/{reactivity-CczHu3R-.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
- package/dist/request-id-BgglvZHN.d.mts +19 -0
- package/dist/request-id-BgglvZHN.d.mts.map +1 -0
- package/dist/request-logger-CWHbAzTE.d.mts +32 -0
- package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
- package/dist/router-builder-C799BAf0.d.mts +31 -0
- package/dist/router-builder-C799BAf0.d.mts.map +1 -0
- package/dist/session-N0hActOO.d.mts +70 -0
- package/dist/session-N0hActOO.d.mts.map +1 -0
- package/dist/spa-CrFR2_cz.d.mts +101 -0
- package/dist/spa-CrFR2_cz.d.mts.map +1 -0
- package/dist/upload-BueOnnLw.d.mts +79 -0
- package/dist/upload-BueOnnLw.d.mts.map +1 -0
- package/dist/validate-HwAyWTwH.d.mts +23 -0
- package/dist/validate-HwAyWTwH.d.mts.map +1 -0
- package/dist/views-DhQSXV2P.d.mts +176 -0
- package/dist/views-DhQSXV2P.d.mts.map +1 -0
- package/package.json +6 -9
- package/dist/adapter-DLEHb0K6.d.mts.map +0 -1
- package/dist/application-x8CXLOlv.mjs.map +0 -1
- package/dist/chunk-Bt-rz0Tp.mjs +0 -15
- package/dist/container-Dnk43k54.mjs.map +0 -1
- package/dist/container-fIS1uLx-.d.mts.map +0 -1
- package/dist/context-OktlOQBQ.mjs.map +0 -1
- package/dist/core-DANnH5-e.mjs.map +0 -1
- package/dist/decorators-H42oPg0m.d.mts.map +0 -1
- package/dist/http/application.d.mts.map +0 -1
- package/dist/http/bootstrap.d.mts.map +0 -1
- package/dist/http/context.d.mts.map +0 -1
- package/dist/http/middleware/cors.d.mts.map +0 -1
- package/dist/http/middleware/csrf.d.mts.map +0 -1
- package/dist/http/middleware/error-handler.d.mts.map +0 -1
- package/dist/http/middleware/helmet.d.mts.map +0 -1
- package/dist/http/middleware/rate-limit.d.mts.map +0 -1
- package/dist/http/middleware/request-id.d.mts.map +0 -1
- package/dist/http/middleware/request-logger.d.mts.map +0 -1
- package/dist/http/middleware/session.d.mts.map +0 -1
- package/dist/http/middleware/spa.d.mts.map +0 -1
- package/dist/http/middleware/upload.d.mts.map +0 -1
- package/dist/http/middleware/validate.d.mts.map +0 -1
- package/dist/http/middleware/views.d.mts.map +0 -1
- package/dist/http/router-builder.d.mts.map +0 -1
- package/dist/index-BQM9pJrV.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/interfaces-CwcdqfNq.d.mts +0 -54
- package/dist/path-Bj3vZMUY.d.mts.map +0 -1
- package/dist/plugin-3rKA0Loy.d.mts.map +0 -1
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
|
|
2
|
+
import { t as Container } from "./container-CnWDsxi-.mjs";
|
|
3
|
+
import { r as ContributorRegistration } from "./context-decorator-B5v3VQCN.mjs";
|
|
4
|
+
import { r as AppAdapter } from "./adapter-BNw2pGbg.mjs";
|
|
5
|
+
import { n as AppModuleClass } from "./app-module-CO0ksPCm.mjs";
|
|
6
|
+
import { t as KickPlugin } from "./plugin-WdrDgNzk.mjs";
|
|
7
|
+
import http from "node:http";
|
|
8
|
+
import { Express, RequestHandler } from "express";
|
|
9
|
+
|
|
10
|
+
//#region src/http/application.d.ts
|
|
11
|
+
/**
|
|
12
|
+
* A middleware entry in the declarative pipeline.
|
|
13
|
+
* Can be a bare handler or an object with path scoping.
|
|
14
|
+
*/
|
|
15
|
+
type MiddlewareEntry = RequestHandler | {
|
|
16
|
+
path: string;
|
|
17
|
+
handler: RequestHandler;
|
|
18
|
+
};
|
|
19
|
+
interface ApplicationOptions {
|
|
20
|
+
/** Feature modules to load */
|
|
21
|
+
modules: AppModuleClass[];
|
|
22
|
+
/** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */
|
|
23
|
+
adapters?: AppAdapter[];
|
|
24
|
+
/** Server port (falls back to PORT env var, then 3000) */
|
|
25
|
+
port?: number;
|
|
26
|
+
/** Global API prefix (default: '/api') */
|
|
27
|
+
apiPrefix?: string;
|
|
28
|
+
/** Default API version (default: 1) — routes become /{prefix}/v{version}/{path} */
|
|
29
|
+
defaultVersion?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Global middleware pipeline. Declared in order.
|
|
32
|
+
* Replaces the hardcoded middleware stack — you control exactly what runs.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* bootstrap({
|
|
37
|
+
* modules,
|
|
38
|
+
* middleware: [
|
|
39
|
+
* helmet(),
|
|
40
|
+
* cors(),
|
|
41
|
+
* compression(),
|
|
42
|
+
* morgan('dev'),
|
|
43
|
+
* express.json({ limit: '1mb' }),
|
|
44
|
+
* ],
|
|
45
|
+
* })
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* If omitted, a sensible default is applied:
|
|
49
|
+
* requestId(), express.json({ limit: '100kb' })
|
|
50
|
+
*/
|
|
51
|
+
middleware?: MiddlewareEntry[];
|
|
52
|
+
/** Plugins that bundle modules, adapters, middleware, and DI bindings */
|
|
53
|
+
plugins?: KickPlugin[];
|
|
54
|
+
/**
|
|
55
|
+
* Global Context Contributors (#107) that apply to every route in the
|
|
56
|
+
* application. Merge into the per-route pipeline at the `'global'`
|
|
57
|
+
* precedence level — they lose to module, adapter, class, and method
|
|
58
|
+
* contributors with the same key, providing app-wide defaults that any
|
|
59
|
+
* narrower scope can override.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* const StartedAt = defineContextDecorator({
|
|
64
|
+
* key: 'requestStartedAt',
|
|
65
|
+
* resolve: () => Date.now(),
|
|
66
|
+
* })
|
|
67
|
+
*
|
|
68
|
+
* bootstrap({
|
|
69
|
+
* modules,
|
|
70
|
+
* contributors: [StartedAt.registration],
|
|
71
|
+
* })
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
contributors?: ContributorRegistration[] | readonly ContributorRegistration[];
|
|
75
|
+
/**
|
|
76
|
+
* Backing store strategy for {@link RequestContext} `set/get` and the
|
|
77
|
+
* Context Contributor pipeline (#107).
|
|
78
|
+
*
|
|
79
|
+
* - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}
|
|
80
|
+
* automatically before any user middleware. If the user-supplied
|
|
81
|
+
* `middleware` list already includes `requestScopeMiddleware()`,
|
|
82
|
+
* detection skips the auto-mount so adopters can control its position.
|
|
83
|
+
* - `'manual'` — Application never mounts the wrapper. The Context
|
|
84
|
+
* Contributor pipeline still runs on every route — the runner is
|
|
85
|
+
* inserted by `router-builder` regardless of ALS state. What
|
|
86
|
+
* degrades without an ALS frame is the *backing store*:
|
|
87
|
+
* REQUEST-scoped DI throws (no `requestStore.getStore()` to read
|
|
88
|
+
* from), `Logger` loses its requestId context, and
|
|
89
|
+
* `RequestContext.set/get` throws. Use `'manual'` only when you
|
|
90
|
+
* genuinely intend to wrap requests in your own ALS frame (rare —
|
|
91
|
+
* multi-tenant adapters used to do this; post-Phase 3 they share
|
|
92
|
+
* the framework's frame instead).
|
|
93
|
+
*/
|
|
94
|
+
contextStore?: 'auto' | 'manual';
|
|
95
|
+
/** Express `trust proxy` setting */
|
|
96
|
+
trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean);
|
|
97
|
+
/** Maximum JSON body size (only used when middleware is not provided) */
|
|
98
|
+
jsonLimit?: string | number;
|
|
99
|
+
/**
|
|
100
|
+
* Log route summary on startup. Default: true in dev, false in production.
|
|
101
|
+
* Set to `true` to always log, `false` to always suppress.
|
|
102
|
+
*/
|
|
103
|
+
logRoutesTable?: boolean;
|
|
104
|
+
/**
|
|
105
|
+
* Maximum time (ms) to wait for graceful shutdown before forcing exit.
|
|
106
|
+
* Default: 30000 (30 seconds). Set to 0 to disable forced exit.
|
|
107
|
+
*/
|
|
108
|
+
shutdownTimeout?: number;
|
|
109
|
+
/**
|
|
110
|
+
* Enable cluster mode for multi-core utilization.
|
|
111
|
+
*
|
|
112
|
+
* When enabled, the primary process forks worker processes that share the
|
|
113
|
+
* same port via Node's built-in `cluster` module (OS load balancing).
|
|
114
|
+
*
|
|
115
|
+
* - `true` — use all available CPU cores
|
|
116
|
+
* - `{ workers: N }` — use exactly N workers
|
|
117
|
+
*
|
|
118
|
+
* Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is
|
|
119
|
+
* forwarded to all workers.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```ts
|
|
123
|
+
* bootstrap({ modules, cluster: true })
|
|
124
|
+
* bootstrap({ modules, cluster: { workers: 4 } })
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
cluster?: boolean | {
|
|
128
|
+
workers?: number;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Custom 404 handler for unmatched routes. Receives the raw Express
|
|
132
|
+
* `(req, res, next)` args. When omitted, the built-in handler returns
|
|
133
|
+
* `{ message: 'Not Found' }` with status 404.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* bootstrap({
|
|
138
|
+
* modules,
|
|
139
|
+
* onNotFound: (req, res) => {
|
|
140
|
+
* res.status(404).json({ error: 'Route not found', path: req.originalUrl })
|
|
141
|
+
* },
|
|
142
|
+
* })
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
onNotFound?: (req: any, res: any, next: any) => void;
|
|
146
|
+
/**
|
|
147
|
+
* Custom global error handler. Receives `(err, req, res, next)` — the
|
|
148
|
+
* standard Express error-handling signature. When omitted, the built-in
|
|
149
|
+
* handler formats ZodError, HttpException, and unexpected errors.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```ts
|
|
153
|
+
* bootstrap({
|
|
154
|
+
* modules,
|
|
155
|
+
* onError: (err, req, res, next) => {
|
|
156
|
+
* logger.error(err)
|
|
157
|
+
* res.status(err.status ?? 500).json({ error: err.message })
|
|
158
|
+
* },
|
|
159
|
+
* })
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
onError?: (err: any, req: any, res: any, next: any) => void;
|
|
163
|
+
/**
|
|
164
|
+
* Security defaults applied automatically unless opted out.
|
|
165
|
+
*
|
|
166
|
+
* When not specified, secure defaults are applied:
|
|
167
|
+
* - Helmet security headers are auto-injected
|
|
168
|
+
* - JSON body limit defaults to 1MB
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```ts
|
|
172
|
+
* bootstrap({
|
|
173
|
+
* modules,
|
|
174
|
+
* security: {
|
|
175
|
+
* helmet: false, // disable auto-helmet
|
|
176
|
+
* },
|
|
177
|
+
* })
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
security?: {
|
|
181
|
+
/** Auto-inject helmet security headers. Default: true */helmet?: boolean;
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The main application class. Wires together Express, the DI container,
|
|
186
|
+
* feature modules, adapters, and the middleware pipeline.
|
|
187
|
+
*/
|
|
188
|
+
declare class Application {
|
|
189
|
+
private readonly options;
|
|
190
|
+
private app;
|
|
191
|
+
private container;
|
|
192
|
+
private httpServer;
|
|
193
|
+
private readonly adapters;
|
|
194
|
+
private readonly plugins;
|
|
195
|
+
/** Number of HTTP requests currently being processed */
|
|
196
|
+
private _inFlightRequests;
|
|
197
|
+
/** Whether the application is draining (shutting down gracefully) */
|
|
198
|
+
private _draining;
|
|
199
|
+
/** Whether shutdown has already been initiated (prevents double-shutdown) */
|
|
200
|
+
private _shutdownInitiated;
|
|
201
|
+
/** Resolvers waiting for in-flight requests to reach zero */
|
|
202
|
+
private _drainResolvers;
|
|
203
|
+
constructor(options: ApplicationOptions);
|
|
204
|
+
/** Whether the application is currently draining in-flight requests */
|
|
205
|
+
get isDraining(): boolean;
|
|
206
|
+
/** Number of HTTP requests currently being processed */
|
|
207
|
+
get inFlightRequests(): number;
|
|
208
|
+
/** Get the DI container instance */
|
|
209
|
+
getContainer(): Container;
|
|
210
|
+
/**
|
|
211
|
+
* Express request handler — delegates to the internal Express app.
|
|
212
|
+
*
|
|
213
|
+
* Used by the Vite dev-server plugin to route requests through KickJS:
|
|
214
|
+
* ```ts
|
|
215
|
+
* const mod = await ssrLoadModule('virtual:kickjs/app')
|
|
216
|
+
* mod.app.handle(req, res, next)
|
|
217
|
+
* ```
|
|
218
|
+
*
|
|
219
|
+
* Also works as a standard Node.js request handler for production:
|
|
220
|
+
* ```ts
|
|
221
|
+
* http.createServer(app.handle.bind(app))
|
|
222
|
+
* ```
|
|
223
|
+
*/
|
|
224
|
+
handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void;
|
|
225
|
+
/**
|
|
226
|
+
* Full setup pipeline:
|
|
227
|
+
* 1. Adapter beforeMount hooks (early routes — docs, health)
|
|
228
|
+
* 2. Adapter middleware (phase: beforeGlobal)
|
|
229
|
+
* 3. Global middleware (user-declared or defaults)
|
|
230
|
+
* 4. Adapter middleware (phase: afterGlobal)
|
|
231
|
+
* 5. Module registration + DI bootstrap
|
|
232
|
+
* 6. Adapter middleware (phase: beforeRoutes)
|
|
233
|
+
* 7. Module route mounting
|
|
234
|
+
* 8. Adapter middleware (phase: afterRoutes)
|
|
235
|
+
* 9. Error handlers (notFound + global)
|
|
236
|
+
* 10. Adapter beforeStart hooks
|
|
237
|
+
*/
|
|
238
|
+
/** Build the adapter context object (shared across all hooks) */
|
|
239
|
+
private adapterCtx;
|
|
240
|
+
/** Call an adapter hook, awaiting async hooks and catching errors */
|
|
241
|
+
private callHook;
|
|
242
|
+
setup(): Promise<void>;
|
|
243
|
+
/** Register modules and DI without starting the HTTP server (used by kick tinker) */
|
|
244
|
+
registerOnly(): Promise<void>;
|
|
245
|
+
/**
|
|
246
|
+
* Start the HTTP server.
|
|
247
|
+
*
|
|
248
|
+
* In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
|
|
249
|
+
* created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
|
|
250
|
+
* `http.Server` through `afterStart({ server })` — zero adapter changes needed.
|
|
251
|
+
*
|
|
252
|
+
* In **production**: creates its own `http.Server` and binds to the port.
|
|
253
|
+
*/
|
|
254
|
+
start(): Promise<void>;
|
|
255
|
+
/** HMR rebuild: swap Express handler without restarting the server */
|
|
256
|
+
rebuild(): Promise<void>;
|
|
257
|
+
/**
|
|
258
|
+
* Graceful shutdown with request draining.
|
|
259
|
+
*
|
|
260
|
+
* 1. Stops accepting new connections (server.close())
|
|
261
|
+
* 2. Waits for in-flight requests to complete (up to shutdownTimeout)
|
|
262
|
+
* 3. Calls adapter.shutdown() for all registered adapters
|
|
263
|
+
* 4. Force-closes after timeout
|
|
264
|
+
*
|
|
265
|
+
* Safe to call multiple times — subsequent calls return the same promise.
|
|
266
|
+
*/
|
|
267
|
+
shutdown(): Promise<void>;
|
|
268
|
+
getExpressApp(): Express;
|
|
269
|
+
/** Get registered adapters — used by DevToolsAdapter for peer discovery */
|
|
270
|
+
getAdapters(): AppAdapter[];
|
|
271
|
+
/**
|
|
272
|
+
* Get registered plugins — used by DevToolsAdapter for topology
|
|
273
|
+
* introspection (architecture.md §23). Read-only; returns the
|
|
274
|
+
* already-sorted plugin list (post-`dependsOn` topo-sort).
|
|
275
|
+
*/
|
|
276
|
+
getPlugins(): readonly KickPlugin[];
|
|
277
|
+
getHttpServer(): http.Server | null;
|
|
278
|
+
/**
|
|
279
|
+
* Decide whether {@link Application} should auto-mount the
|
|
280
|
+
* {@link requestScopeMiddleware} ALS wrapper.
|
|
281
|
+
*
|
|
282
|
+
* Returns `false` when:
|
|
283
|
+
* - `contextStore: 'manual'` was set (caller manages ALS frames), or
|
|
284
|
+
* - the user-supplied `middleware` list already includes a
|
|
285
|
+
* `requestScopeMiddleware()` (detected via the symbol marker stamped
|
|
286
|
+
* in `middleware/request-scope.ts`).
|
|
287
|
+
*
|
|
288
|
+
* Otherwise `true` — preserves the historical default of "always wrap
|
|
289
|
+
* requests in an ALS frame" so existing apps see no behavior change.
|
|
290
|
+
*/
|
|
291
|
+
private shouldAutoMountRequestScope;
|
|
292
|
+
private collectAdapterMiddleware;
|
|
293
|
+
private mountMiddlewareList;
|
|
294
|
+
private mountMiddlewareEntry;
|
|
295
|
+
/** Middleware that tracks in-flight requests for graceful draining */
|
|
296
|
+
private requestTrackingMiddleware;
|
|
297
|
+
/** Mount /health/live and /health/ready endpoints at the root (no API prefix) */
|
|
298
|
+
private mountHealthEndpoints;
|
|
299
|
+
}
|
|
300
|
+
//#endregion
|
|
301
|
+
export { ApplicationOptions as n, MiddlewareEntry as r, Application as t };
|
|
302
|
+
//# sourceMappingURL=application-Czwm7Gty.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"application-Czwm7Gty.d.mts","names":[],"sources":["../src/http/application.ts"],"mappings":";;;;;;;;;;;;;;KAgCY,eAAA,GAAkB,cAAA;EAAmB,IAAA;EAAc,OAAA,EAAS,cAAA;AAAA;AAAA,UAEvD,kBAAA;;EAEf,OAAA,EAAS,cAAA;EAJmB;EAM5B,QAAA,GAAW,UAAA;EANkD;EAQ7D,IAAA;EARoF;EAUpF,SAAA;EARe;EAUf,cAAA;;;;;;;;;;;;;;;;;;;;;;EAuBA,UAAA,GAAa,eAAA;EAyBuC;EAtBpD,OAAA,GAAU,UAAA;EA8CV;;;;;;;;;;;;;;;;;;;;EA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UAAA;EAIvB,aAAA,CAAA,GAAiB,IAAA,CAAK,MAAA;;;;;;;;;;;;;;UAmBd,2BAAA;EAAA,QAWA,wBAAA;EAAA,QAmBA,mBAAA;EAAA,QAUA,oBAAA;;UASA,yBAAA;;UAsBA,oBAAA;AAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
+
import { t as Container } from "./container-DYYSu58w.mjs";
|
|
11
12
|
import { createLogger } from "./core/logger.mjs";
|
|
12
|
-
import
|
|
13
|
-
import "./core-DANnH5-e.mjs";
|
|
13
|
+
import "./core-DBcoqPHM.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-Ce4DQN6m.mjs";
|
|
16
|
+
import { a as reloadEnv } from "./env-CdH5-dM_.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-CB7bJeJG.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap-CYnxozL_.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,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,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C,SAAO,IAAI,YAAY,QAAQ;;CAQjC,MAAM,IAAI;AAGV,KAAI,CAAC,EAAE,oBAAoB;AACzB,UAAQ,GAAG,sBAAsB,QAAQ;AACvC,OAAI,MAAM,KAAK,qBAAqB;IACpC;AAEF,UAAQ,GAAG,uBAAuB,WAAW;AAC3C,OAAI,MAAM,QAAe,sBAAsB;IAC/C;AAEF,MAAI,CAAC,EAAE,oBACL,MAAK,MAAM,UAAU,CAAC,UAAU,UAAU,CACxC,SAAQ,GAAG,QAAQ,YAAY;AAC7B,OAAI,KAAK,YAAY,OAAO,oBAAoB;AAChD,OAAI,EAAE,MAAO,OAAM,EAAE,MAAM,UAAU;AACrC,WAAQ,KAAK,EAAE;IACf;AAIN,IAAE,qBAAqB;;AAIzB,KAAI,EAAE,OAAO;AACX,MAAI,MAAM,wBAAwB;AAClC,gBAAc;AACd,YAAU,OAAO;EAEjB,MAAM,WAAW,IAAI,YAAY,QAAQ;AACzC,IAAE,QAAQ;AACV,IAAE,qBAAqB,SAAS,cAAc;AAE9C,QAAM,SAAS,OAAO;AACtB,MAAI,MAAM,uBAAuB;AACjC,SAAO;;CAIT,MAAM,MAAM,IAAI,YAAY,QAAQ;AACpC,GAAE,QAAQ;AACV,GAAE,qBAAqB,IAAI,cAAc;AAEzC,KAAI,QAAQ,IAAI,aAAa;AAC3B,QAAM,IAAI,cAAc;AACxB,SAAO;;AAGT,OAAM,IAAI,OAAO;AAEjB,QAAO"}
|
|
1
|
+
{"version":3,"file":"bootstrap-CB7bJeJG.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,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;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Q,GAAG,uBAAuB,WAAW;AAC3C,OAAI,MAAM,QAAe,sBAAsB;IAC/C;AAEF,MAAI,CAAC,EAAE,oBACL,MAAK,MAAM,UAAU,CAAC,UAAU,UAAU,CACxC,SAAQ,GAAG,QAAQ,YAAY;AAC7B,OAAI,KAAK,YAAY,OAAO,oBAAoB;AAChD,OAAI,EAAE,MAAO,OAAM,EAAE,MAAM,UAAU;AACrC,WAAQ,KAAK,EAAE;IACf;AAIN,IAAE,qBAAqB;;AAIzB,KAAI,EAAE,OAAO;AACX,MAAI,MAAM,wBAAwB;AAClC,gBAAc;AACd,YAAU,OAAO;EAEjB,MAAM,WAAW,IAAI,YAAY,QAAQ;AACzC,IAAE,QAAQ;AACV,IAAE,qBAAqB,SAAS,cAAc;AAE9C,QAAM,SAAS,OAAO;AACtB,MAAI,MAAM,uBAAuB;AACjC,SAAO;;CAIT,MAAM,MAAM,IAAI,YAAY,QAAQ;AACpC,GAAE,QAAQ;AACV,GAAE,qBAAqB,IAAI,cAAc;AAEzC,KAAI,QAAQ,IAAI,aAAa;AAC3B,QAAM,IAAI,cAAc;AACxB,SAAO;;AAGT,OAAM,IAAI,OAAO;AAEjB,QAAO"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
|
|
2
|
+
import { n as ApplicationOptions, t as Application } from "./application-Czwm7Gty.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/http/bootstrap.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Bootstrap a KickJS application.
|
|
7
|
+
*
|
|
8
|
+
* Creates the Express app, registers modules and adapters, and starts
|
|
9
|
+
* the HTTP server. In dev mode (`kick dev`), the Vite plugin manages
|
|
10
|
+
* the server and HMR — source changes are picked up instantly without
|
|
11
|
+
* losing database connections or WebSocket state.
|
|
12
|
+
*
|
|
13
|
+
* @returns The {@link Application} instance.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* // src/index.ts
|
|
18
|
+
* import 'reflect-metadata'
|
|
19
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
20
|
+
* import { modules } from './modules'
|
|
21
|
+
*
|
|
22
|
+
* export const app = await bootstrap({ modules })
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
declare function bootstrap(options: ApplicationOptions): Promise<Application>;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { bootstrap as t };
|
|
28
|
+
//# sourceMappingURL=bootstrap-NxFRaNTh.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bootstrap-NxFRaNTh.d.mts","names":[],"sources":["../src/http/bootstrap.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;iBAAsB,SAAA,CAAU,OAAA,EAAS,kBAAA,GAAqB,OAAA,CAAQ,WAAA"}
|
|
@@ -56,7 +56,7 @@ declare class MemoryCacheProvider implements CacheProvider {
|
|
|
56
56
|
*
|
|
57
57
|
* @example
|
|
58
58
|
* ```ts
|
|
59
|
-
* import { setCacheProvider } from '@forinda/kickjs
|
|
59
|
+
* import { setCacheProvider } from '@forinda/kickjs'
|
|
60
60
|
* import { RedisCacheProvider } from './redis-cache'
|
|
61
61
|
*
|
|
62
62
|
* setCacheProvider(new RedisCacheProvider(redisClient))
|
|
@@ -92,4 +92,4 @@ declare function Cacheable(ttl?: number, options?: {
|
|
|
92
92
|
declare function CacheEvict(key: string): MethodDecorator;
|
|
93
93
|
//#endregion
|
|
94
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-
|
|
95
|
+
//# sourceMappingURL=cache-BStrqXSZ.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-
|
|
1
|
+
{"version":3,"file":"cache-BStrqXSZ.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"}
|
package/dist/config/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as baseEnvSchema, c as loadEnv, i as Env, l as reloadEnv, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as resetEnvCache } from "../index-
|
|
2
|
+
import { a as baseEnvSchema, c as loadEnv, i as Env, l as reloadEnv, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as resetEnvCache } from "../index-D-qhXg9M.mjs";
|
|
3
3
|
export { ConfigService, Env, TypedConfigService, baseEnvSchema, createConfigService, defineEnv, getEnv, loadEnv, reloadEnv, resetEnvCache };
|
package/dist/config/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
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-CdH5-dM_.mjs";
|
|
12
|
+
import { n as createConfigService, t as ConfigService } from "../config-wZ_TgBfs.mjs";
|
|
13
13
|
export { ConfigService, baseEnvSchema, createConfigService, defineEnv, getEnv, loadEnv, reloadEnv, resetEnvCache };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
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-CdH5-dM_.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;
|
|
@@ -91,7 +91,7 @@ ConfigService = __decorate([Service()], ConfigService);
|
|
|
91
91
|
* export type AppConfigService = InstanceType<typeof AppConfigService>
|
|
92
92
|
*
|
|
93
93
|
* // In a controller or service — inject it:
|
|
94
|
-
* @Controller(
|
|
94
|
+
* @Controller()
|
|
95
95
|
* class UserController {
|
|
96
96
|
* constructor(@Inject(AppConfigService) private config: AppConfigService) {
|
|
97
97
|
* const dbUrl = config.get('DATABASE_URL') // string — autocompletes!
|
|
@@ -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-wZ_TgBfs.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-
|
|
1
|
+
{"version":3,"file":"config-wZ_TgBfs.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()\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
|
-
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-
|
|
2
|
+
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-B50n7dwl.mjs";
|
|
3
3
|
//#region src/core/token.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Collision-safe injection tokens with phantom type parameters.
|
|
@@ -133,14 +133,16 @@ declare class Container {
|
|
|
133
133
|
/** Callback invoked on reset so decorators can update their container reference */
|
|
134
134
|
static _onReset: ((container: Container) => void) | null;
|
|
135
135
|
/**
|
|
136
|
-
* Environment resolver for @Value decorator. Set by
|
|
137
|
-
* to return Zod-validated, type-coerced
|
|
136
|
+
* Environment resolver for @Value decorator. Set by the unified
|
|
137
|
+
* `@forinda/kickjs` config layer to return Zod-validated, type-coerced
|
|
138
|
+
* env values instead of raw process.env strings.
|
|
138
139
|
*/
|
|
139
140
|
static _envResolver: ((key: string) => any) | null;
|
|
140
141
|
/**
|
|
141
|
-
* Request store provider for REQUEST-scoped DI. Set by
|
|
142
|
-
* to return the current request's
|
|
143
|
-
* Returns { instances: Map, values: Map } or
|
|
142
|
+
* Request store provider for REQUEST-scoped DI. Set by the HTTP layer
|
|
143
|
+
* inside `@forinda/kickjs` to return the current request's
|
|
144
|
+
* AsyncLocalStorage store. Returns { instances: Map, values: Map } or
|
|
145
|
+
* null if outside a request.
|
|
144
146
|
*/
|
|
145
147
|
static _requestStoreProvider: (() => {
|
|
146
148
|
instances: Map<any, any>;
|
|
@@ -250,4 +252,4 @@ declare class Container {
|
|
|
250
252
|
}
|
|
251
253
|
//#endregion
|
|
252
254
|
export { tokenName as a, createToken as c, KickJsRegistry as i, isInjectionToken as l, ContainerChangeEvent as n, INJECTION_TOKEN as o, ContainerChangeListener as r, InjectionToken as s, Container as t };
|
|
253
|
-
//# sourceMappingURL=container-
|
|
255
|
+
//# sourceMappingURL=container-CnWDsxi-.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"container-CnWDsxi-.d.mts","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"mappings":";;;;;;;AAmDA;;;;;AAWA;;;;;;;;;;;AAeA;;;;;;;;;;AAQA;;;;;;;;;;;;AClCA;;;;;AAqBA;;;AArBA,cDAa,eAAA;;;;;;;;AC6Bb;;UDlBiB,cAAA;EAAA,UACL,eAAA;ECiB0D;EAAA,SDf3D,IAAA;ECkCoB;EAAA,SDhCpB,KAAA,GAAQ,CAAA;AAAA;;AC+DnB;;;;;;iBDrDgB,WAAA,GAAA,CAAe,IAAA,WAAe,cAA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